body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have to check for the Highest Date from CostRepository whether it is create date or edit date then i have to get value in that field. edit date can be null. i don't know how to fix the codesmell.</p> <pre><code>var allCostsInThisPo = CostRepository .GetAll() .WhereInPo(po.po_surr_key); if (allCostsInThisPo.Any()) { var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item =&gt; item.create_date).First(); var allEditedCosts = allCostsInThisPo.Where(item=&gt;item.update_date != null); if (allEditedCosts.Any()) { var costWithMaxEditedDate = allEditedCosts.OrderByDescending(item =&gt; item.update_date).First(); if (costWithMaxCreatedDate.create_date &gt; costWithMaxEditedDate.update_date) { history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date); } else { history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxEditedDate.EditedByUser.user_fullname, costWithMaxEditedDate.update_date.Value); } } else { history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date); } } </code></pre>
[]
[ { "body": "<p>Let's indent the code properly and remove unnecessary whitespace:</p>\n\n<pre><code>var allCostsInThisPo = CostRepository\n .GetAll()\n .WhereInPo(po.po_surr_key);\n\nif (allCostsInThisPo.Any())\n{\n var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item =&gt; item.create_date).First();\n var allEditedCosts = allCostsInThisPo.Where(item=&gt;item.update_date != null);\n\n if (allEditedCosts.Any())\n {\n var costWithMaxEditedDate = allEditedCosts.OrderByDescending(item =&gt; item.update_date).First();\n\n if (costWithMaxCreatedDate.create_date &gt; costWithMaxEditedDate.update_date)\n {\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date);\n }\n else\n {\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxEditedDate.EditedByUser.user_fullname, costWithMaxEditedDate.update_date.Value); \n }\n }\n else\n {\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date); \n }\n}\n</code></pre>\n\n<p>What the code is actually doing is that it assigns values <code>history.AllocationInfo</code> depending on some conditions. The assignement is always using the very long <code>BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay</code> called with different arguments. Let's return those arguments instead.</p>\n\n<pre><code>private AllocationHistoryInfo RetrieveAllocationHistoryInfo(dynamic allCostsInThisPo)\n{\n var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item =&gt; item.create_date).First();\n var allEditedCosts = allCostsInThisPo.Where(item=&gt;item.update_date != null);\n\n if (allEditedCosts.Any())\n {\n var costWithMaxEditedDate = allEditedCosts.OrderByDescending(item =&gt; item.update_date).First();\n\n if (costWithMaxCreatedDate.create_date &gt; costWithMaxEditedDate.update_date)\n {\n return new AllocationHistoryInfo(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date);\n }\n else\n {\n return new AllocationHistoryInfo(costWithMaxEditedDate.EditedByUser.user_fullname, costWithMaxEditedDate.update_date.Value); \n }\n }\n else\n {\n return new AllocationHistoryInfo(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date); \n }\n}\n\n// Later in code:\nvar allCostsInThisPo = CostRepository\n .GetAll()\n .WhereInPo(po.po_surr_key);\n\nif (allCostsInThisPo.Any())\n{\n var allocationHistoryInfo = this.RetrieveAllocationHistoryInfo(allCostsInThisPo);\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(allocationHistoryInfo.Cost, allocationHistoryInfo.CreateDate);\n}\n</code></pre>\n\n<p>Given that <code>return</code> will stop processing the method, we can now shorten the code like this.</p>\n\n<pre><code>private AllocationHistoryInfo RetrieveAllocationHistoryInfo(dynamic allCostsInThisPo)\n{\n var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item =&gt; item.create_date).First();\n var allEditedCosts = allCostsInThisPo.Where(item=&gt;item.update_date != null);\n if (allEditedCosts.Any())\n {\n var costWithMaxEditedDate = allEditedCosts.OrderByDescending(item =&gt; item.update_date).First();\n if (costWithMaxCreatedDate.create_date &lt;= costWithMaxEditedDate.update_date)\n {\n return new AllocationHistoryInfo(costWithMaxEditedDate.EditedByUser.user_fullname, costWithMaxEditedDate.update_date.Value); \n }\n }\n\n return new AllocationHistoryInfo(costWithMaxCreatedDate.CreatedByUser.user_fullname, costWithMaxCreatedDate.create_date); \n}\n\n// Later in code:\nvar allCostsInThisPo = CostRepository\n .GetAll()\n .WhereInPo(po.po_surr_key);\n\nif (allCostsInThisPo.Any())\n{\n var allocationHistoryInfo = this.RetrieveAllocationHistoryInfo(allCostsInThisPo);\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(allocationHistoryInfo.Cost, allocationHistoryInfo.CreateDate);\n}\n</code></pre>\n\n<p>This final version is still difficult to read and understand. Your strong point is to name your variables correctly, so I won't spend too much time trying to rename them. If <code>EditedByUser</code> and <code>CreatedByUser</code> share the same interface, you can slighly simplify the method by adding a constructor overload to <code>AllocationHistoryInfo</code>, taking the interface as a parameter, leading to <code>costWithMaxEditedDate.EditedByUser</code> and <code>costWithMaxCreatedDate.CreatedByUser</code>, without <code>user_fullname</code>. A few minor changes may simplify the code, but not too much.</p>\n\n<p>You may also try to:</p>\n\n<ul>\n<li><p>Refactor the single method into several smaller ones,</p></li>\n<li><p>Comment the code.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:44:03.107", "Id": "43499", "Score": "0", "body": "What do you mean by “indent the code properly”? The change you made to the initialization of `allCostsInThisPo`? I'm not sure that's an improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:46:57.213", "Id": "43501", "Score": "0", "body": "Also, why did you decide to use `dynamic`? That's usually a bad idea, unless there is a good reason to use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:52:00.070", "Id": "43502", "Score": "0", "body": "@svick: by \"indent the code properly\", I mean what you did in your edit of the question. As for the initialization, I should review it carefully; there may be mistakes in my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:52:57.963", "Id": "43503", "Score": "0", "body": "@svick: I used `dynamic` because there is no way to determine the actual type from the piece of code given in the question. So yes, the OP should use the real type instead of `dynamic`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:53:42.413", "Id": "43504", "Score": "0", "body": "Well, that's usually an artifact of people copying code that's inside a method inside a class inside a namespace, so it appears more indented than it has to here, but it's actually okay in the real code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T12:17:45.993", "Id": "27892", "ParentId": "27888", "Score": "0" } }, { "body": "<p>You could try and make LINQ do more, to me it is more readable but it may not be to your style.</p>\n\n<pre><code>var allCostsInThisPo = CostRepository\n .GetAll()\n .WhereInPo(po.po_surr_key);\n\nif (allCostsInThisPo.Any())\n{ \n var costWithMaxCreatedDate = allCostsInThisPo.OrderByDescending(item =&gt; item.create_date)\n .Select(c =&gt; new { Name = c.CreatedByUser.user_fullname, Date = c.create_date})\n .First();\n\n // if there is a max edited date greated than the cost created date then this will\n // be populated, otherwise will be null. \n var costWithMaxEditedDate = allCostsInThisPo.Where(item =&gt; item.update_date.HasValue &amp;&amp; item.update_date.Value &gt; costWithMaxCreatedDate.Date)\n .OrderByDescending(c =&gt; item.update_date.Value) \n .Select(c =&gt; new { Name = c.EditedByUser.user_fullname, Date = c.update_date.Value}) \n .FirstOrDefault();\n\n var maxCost = costWithMaxEditedDate ?? costWithMaxCreatedDate;\n\n history.AllocationInfo = BuilkConstant.LogHistorySetting.GetAllocationHistoryLogDisplay(maxCost.Name, maxCost.Date); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T14:26:37.880", "Id": "27899", "ParentId": "27888", "Score": "3" } } ]
{ "AcceptedAnswerId": "27899", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T10:13:32.130", "Id": "27888", "Score": "1", "Tags": [ "c#" ], "Title": "Refactor selective item by highest create date or update date" }
27888
<p>I am trying to draw a Checkerboard pattern on a LCD using a GUI library called emWin. I have actually managed to draw it using the following code. But having this many loops in the program body for a single task, that too in the internal flash of the microcontroller is not a good idea.</p> <p>For those who have not worked with emWin, I will try and explain a few things before we go for the actual logic. </p> <ul> <li><code>GUI_RECT</code> is a structure which id define source files of emWin and I am blind to it.</li> <li><code>Rect</code>, <code>Rect2</code>, <code>Rect3</code>.. and so on until <code>Rect10</code> are objects. </li> <li>Elements of the <code>Rect</code> array are <code>{x0,y0,x1,y1}</code>, where <code>x0</code>, <code>y0</code> are starting locations of the rectangle in the X-Y plane and x1, y1 are end locations of the Rectangle in the X-Y plane.</li> </ul> <p><code>Rect={0,0,79,79}</code> is a rectangle that starts at the top left of the LCD and is up to (79,79), so it's basically a square.</p> <ul> <li>The function <code>GUI_setBkColor(int color);</code> sets the color of the background.</li> <li>The function <code>GUI_setColor(int color);</code> sets the color of the foreground.</li> <li><code>GUI_WHITE</code> and <code>DM_CHECKERBOARD_COLOR</code> are two color values, <code>#define</code>ed</li> <li><code>GUI_FillRectEx(&amp;Rect);</code> will draw the rectangle.</li> </ul> <p>The code below works fine but I want to make it smarter.</p> <pre><code>GUI_RECT Rect = {0, 0, 79, 79}; GUI_RECT Rect2 = {80, 0, 159, 79}; GUI_RECT Rect3 = {160, 0, 239, 79}; GUI_RECT Rect4 = {240, 0, 319, 79}; GUI_RECT Rect5 = {320, 0, 399, 79}; GUI_RECT Rect6 = {400, 0, 479, 79}; GUI_RECT Rect7 = {480, 0, 559, 79}; GUI_RECT Rect8 = {560, 0, 639, 79}; GUI_RECT Rect9 = {640, 0, 719, 79}; GUI_RECT Rect10 = {720, 0, 799, 79}; WM_SelectWindow(Win_DM_Main); GUI_SetBkColor(GUI_BLACK); GUI_Clear(); for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(GUI_WHITE); else GUI_SetColor(DM_CHECKERBOARD_COLOR); GUI_FillRectEx(&amp;Rect); Rect.y0 += 80; Rect.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(DM_CHECKERBOARD_COLOR); else GUI_SetColor(GUI_WHITE); GUI_FillRectEx(&amp;Rect2); Rect2.y0 += 80; Rect2.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(GUI_WHITE); else GUI_SetColor(DM_CHECKERBOARD_COLOR); GUI_FillRectEx(&amp;Rect3); Rect3.y0 += 80; Rect3.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(DM_CHECKERBOARD_COLOR); else GUI_SetColor(GUI_WHITE); GUI_FillRectEx(&amp;Rect4); Rect4.y0 += 80; Rect4.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(GUI_WHITE); else GUI_SetColor(DM_CHECKERBOARD_COLOR); GUI_FillRectEx(&amp;Rect5); Rect5.y0 += 80; Rect5.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(DM_CHECKERBOARD_COLOR); else GUI_SetColor(GUI_WHITE); GUI_FillRectEx(&amp;Rect6); Rect6.y0 += 80; Rect6.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(GUI_WHITE); else GUI_SetColor(DM_CHECKERBOARD_COLOR); GUI_FillRectEx(&amp;Rect7); Rect7.y0 += 80; Rect7.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(DM_CHECKERBOARD_COLOR); else GUI_SetColor(GUI_WHITE); GUI_FillRectEx(&amp;Rect8); Rect8.y0 += 80; Rect8.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(GUI_WHITE); else GUI_SetColor(DM_CHECKERBOARD_COLOR); GUI_FillRectEx(&amp;Rect9); Rect9.y0 += 80; Rect9.y1 += 80; } for(i = 0; i &lt; 6; i++) { if(i%2 == 0) GUI_SetColor(DM_CHECKERBOARD_COLOR); else GUI_SetColor(GUI_WHITE); GUI_FillRectEx(&amp;Rect10); Rect10.y0 += 80; Rect10.y1 += 80; } </code></pre>
[]
[ { "body": "<p>C-style pseudo-code:</p>\n\n<pre><code>char cellSize = 50;\nint cellX,cellY;\nColor cellColor;\n\nfor ( char row = 0 ; row &lt; 8 ; row++ )\n{\n for ( char col = 0 ; col &lt; 8 ; col++ )\n {\n cellX = col*cellSize\n cellY = row*cellSize;\n cellColor = (row+col)%2 ? COLOR_WHITE : COLOR_BLACK;\n drawRect(cellX,cellY,cellSize,cellSize,cellColor);\n }\n}\n</code></pre>\n\n<p>I believe the algorithm of drawing a checkerboard is that trivial. Draw cell by cell moving from left to right and from bottom to top and choose color basing on whether the sum of <code>row</code> and <code>col</code> is even or odd.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:24:23.280", "Id": "43489", "Score": "0", "body": "Totally agree with with what you said regarding drawing the checkerboard, but here this function `GUI_FillRectEx` is a library function call, and that I can not change, and I have no other alternative like writing my own function to draw like the one `drawRect(cellX,cellY,cellSize,cellSize,cellSize,cellColor);` you suggested" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:31:52.543", "Id": "43490", "Score": "2", "body": "`I have no other alternative like writing my own function to draw like the one` In fact it is a very good practice. You should split your code in functions doing exactly one thing. So extracting the functionality of drawing a rectangle from the function drawing the checker-board is what you should do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:14:32.087", "Id": "27890", "ParentId": "27889", "Score": "3" } }, { "body": "<p>It's unlikely that your app's performance concerns are due to the excessive looping. They are all small loops and should rip through pretty quickly, even on an embedded controller. I suspect your expensive call is the GUI_FillRectEx() calls.</p>\n\n<p>That said, there are techniques to clean up your code and make it more maintainable.</p>\n\n<ul>\n<li>Look for the duplicated logic. </li>\n</ul>\n\n<p>Notice how you have the same loop structure + code for each of those blocks?</p>\n\n<pre><code>for(i = 0; i &lt; 6; i++)\n{\n if(i%2 == 0)\n GUI_SetColor(DM_CHECKERBOARD_COLOR); \n else\n GUI_SetColor(GUI_WHITE);\n</code></pre>\n\n<p>While the cost isn't necessarily great in this case, you are repeating it for each of your rectangles.</p>\n\n<ul>\n<li><p>Look for the actions that don't need to occur.</p>\n\n<ol>\n<li><p>In this case, do you really need to paint both the white and black squares? Could you \"cheat\" by using a black canvas and only paint the white squares? That would cut your FillRectEx() calls in half.</p></li>\n<li><p>Do you really need to declare 10 Rect's and increment coordinates on each loop? How about declaring a fixed array ahead of time and pre-populate / hard code all the coordinates?</p></li>\n</ol></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:28:18.233", "Id": "43492", "Score": "0", "body": "Sir, totally agree with you. The same thing occurred to me as well of drawing alternate white squares on a black background, but the requirements are like, I should have a background color other than the two colors used to draw the checkerboard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:29:33.863", "Id": "43493", "Score": "0", "body": "@ GlenH7: I will try and spend some time coding to see if I can manage that with two Rects, each for single color." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:45:00.350", "Id": "43500", "Score": "1", "body": "@wedapashi having two rectangles will simplify the code but will require more calculations in order to complete the task. You need to decide on which path you want to follow. If execution time is critical, minimize calculations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T11:18:56.883", "Id": "27891", "ParentId": "27889", "Score": "4" } }, { "body": "<p>The basic concept behind this pseudo-code is to place the 10 separate loops into one single loop and implement the functionality through array indices.</p>\n\n<pre><code>GUI_RECT Rect = new int[10][4];\nint checkerIndex = 0;\nfor (int groi = 0; groi &lt; 10; groi++)\n{\n Rect[groi] = {groi*80, 0, (groi+1)*80 - 1, 79};\n}\n\nWM_SelectWindow(Win_DM_Main);\nGUI_SetBkColor(GUI_BLACK);\nGUI_Clear();\n\nfor(int groi = 0; groi &lt; 10; groi++)\n{\n for(i = 0; i &lt; 6; i++)\n {\n if(i%2 == checkerIndex)\n GUI_SetColor(GUI_WHITE);\n else\n GUI_SetColor(DM_CHECKERBOARD_COLOR);\n\n GUI_FillRectEx(&amp;Rect[groi]);\n\n Rect[groi].y0 += 80;\n Rect[groi].y1 += 80;\n }\n checkerIndex = 1 - checkerIndex;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-11T20:24:37.800", "Id": "101181", "Score": "0", "body": "@Jamal sorry, you're right. The basic concept behind this pseudo-code was to place the 10 separate loops into one single loop and implement the functionality through array indices. However I applied a fix to it otherwise the checkerboard pattern would not show." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T05:38:39.203", "Id": "101812", "Score": "0", "body": "There's other ways to simplify it, for instance, `checkerIndex = 1-checkerIndex;` instead of that monstrosity." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T15:29:49.927", "Id": "27904", "ParentId": "27889", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T10:54:49.153", "Id": "27889", "Score": "7", "Tags": [ "c", "computational-geometry", "embedded" ], "Title": "Optimizing a loop in C for a microcontroller" }
27889
<p>I tried this so far:</p> <pre><code>public String readchar (Reader input) throws java.io.IOException { int i16 = input.read(); // UTF-16 as int if (i16 == -1) return null; char c16 = (char)i16; // UTF-16 if (Character.isHighSurrogate(c16)) { int low_i16 = input.read(); // low surrogate UTF-16 as int if (low_i16 == -1) throw new java.io.IOException ("Can not read low surrogate"); char low_c16 = (char)low_i16; int codepoint = Character.toCodePoint(c16, low_c16); return new String (Character.toChars(codepoint)); } else return Character.toString(c16); } </code></pre> <p>But it contains unsafe casts. I have no idea how to avoid them. Is it possible?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:10:13.883", "Id": "43496", "Score": "0", "body": "What do you mean by _unsafe casts_? Casting from `int` to `char` will never crash, and because of your `int`s coming from `input.read();` you won't lose any information by the cast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T10:09:41.460", "Id": "43730", "Score": "0", "body": "@jlordo I mean with *unsafe* a loose of data, because `int` does not fit into `char`." } ]
[ { "body": "<p>The javadoc of the <code>read</code> method <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/Reader.html#read%28%29\" rel=\"nofollow\">states</a>:</p>\n\n<blockquote>\n <p>Returns: The character read, as an integer in the range <strong>0 to 65535</strong>\n (0x00-0xffff), or -1 if the end of the stream has been reached</p>\n</blockquote>\n\n<p>The <code>char</code> primative <a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html\" rel=\"nofollow\">is</a> \"a single 16-bit Unicode character. It has a <strong>minimum value of</strong> '<code>\\u0000</code>' (or <strong>0</strong>) and a <strong>maximum value of</strong> '<code>\\uffff</code>' (or <strong>65,535 inclusive</strong>).\"</p>\n\n<p>(emphasis mine)</p>\n\n<p>It would appear that your two C-style casts are safe.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:02:12.817", "Id": "27922", "ParentId": "27893", "Score": "1" } } ]
{ "AcceptedAnswerId": "27922", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T12:19:43.360", "Id": "27893", "Score": "1", "Tags": [ "java" ], "Title": "How to read a complete Unicode code point as String?" }
27893
<p>I wrote a recursive function that traverses nested DOM nodes of the following form:</p> <pre><code>&lt;a href="#" title="test"&gt; &lt;div id="nested-image"&gt; &lt;img src="image.jpg" /&gt; &lt;/div&gt; &lt;/a&gt; </code></pre> <p>The recursive function is the following:</p> <pre><code>function getNestedNodes(node) { var ary = []; for(var i = 0; i &lt; node.length; ++i) { var myJSONChildren = {}; if(node[i].childElementCount) { var myNode = node[i].children; for(var j = 0; j &lt; myNode.length; ++j) { for(var k =0, attrs = myNode[j].attributes, l = attrs.length; k &lt; l; ++k) { myJSONChildren['tag'] = myNode[j].nodeName; myJSONChildren[attrs.item(k).nodeName] = attrs.item(k).nodeValue; }; } myJSONChildren['children'] = getNestedNodes(myNode); //Recursive Call ary.push(myJSONChildren); }; } return ary; } </code></pre> <p>so if I call that function this way:</p> <pre><code>var links = document.querySelectorAll('a'); getNestedNodes(node); </code></pre> <p>it returns a JSON array of the following form:</p> <pre><code>[{ tag:'a', href:"#, title:"test", children:[{ tag:"div", id:"nested-image", children:[{ tag:"img", src:"image.jpg" }] }] }] }] </code></pre> <p>However, I think that my function is way too complex, and I know that there must a better way to get the same results. </p> <p>Any help will be greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T16:13:18.430", "Id": "60208", "Score": "0", "body": "Since the DOM is essentially a tree... I'd suggest checking out some tree traversal algorithms. This wikipedia page provides some recursive traversal pseudocode algorithms: http://en.wikipedia.org/wiki/Tree_traversal And these jQuery functions should help too: http://api.jquery.com/category/traversing/tree-traversal/" } ]
[ { "body": "<p>Note that when you do <code>document.querySelectorAll</code> you are getting not a single node but a list of nodes. This seems to be causing confusion because your function refers to <code>node.length</code> - but a single node does not have any length property. Your original function also does not seem to behave exactly as you want it to in that it excludes the parent node (<code>a</code> in your example).</p>\n\n<p>If you ensure that you are passing the function a single node, then it can indeed be simplified a lot:</p>\n\n<pre><code>function getTree(node) {\n var r = {tag: node.nodeName}, a, i;\n if (node.childElementCount) {\n r.children = [];\n for (i = 0; a = node.children[i]; i++) {\n r.children.push(getTree(a));\n }\n }\n for (i = 0; a = node.attributes[i]; i++) {\n r[a.nodeName] = a.nodeValue;\n }\n return r; \n}\nvar links = document.querySelectorAll('a');\nconsole.log(getTree(links[0])); // only pass the first node to the function\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/gpk3T/2/\" rel=\"nofollow\">(JSfiddle here)</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-28T19:24:26.427", "Id": "29092", "ParentId": "27898", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T14:24:32.103", "Id": "27898", "Score": "3", "Tags": [ "javascript", "optimization", "recursion", "dom" ], "Title": "Optimize Recursive Function to traverse nested DOM nodes" }
27898
<p>This Python class takes a GF2 (finite field mod 2, basically binary) polynomial in string form, converts it to a binary value, then does arithmetic operations, then converts the result back into a polynomial in string form. </p> <p>There are 2 parts I'd like to direct your attention to. I'll call them exhibits a and b. </p> <p>For exhibit a, the regex has to be done on the string upon intake, so there were some issues with how class instances were used in terms of still allowing the string format. So that's the reason why the class is being called at the bottom. That should be invisible to the user (unless they actually go looking in the file), and when they call the class in whatever file is being used, then it should just be another class and they go on about their business. Not saying it's good coding, just saying why it looks like that. I'm sure it looks duck-taped from the professional Python coder's perspective, but for me I was pretty glad to solve it any way possible. </p> <p>Also somewhat duck-taped was the modular inverse function, which I'll give as exhibit b.</p> <p>I'm teaching myself Python and trying to drop all my beginner bad habits quickly. Just trying to get some good advice on the code.</p> <pre><code>import re class gf2pim: def id(self,lst): #returns modulus 2 (1,0,0,1,1,....) for input lists return [int(lst[i])%2 for i in range(len(lst))] def listToInt(self,lst): #converts list to integer for later use result = obj.id(lst) return int(''.join(map(str,result))) def parsePolyToListInput(self,poly): c = [int(i.group(0)) for i in re.finditer(r'\d+', poly)] #re.finditer returns an iterator return [1 if x in c else 0 for x in xrange(max(c), -1, -1)] def prepBinary(self,x,y): #converts to base 2 and orders min and max for use x = obj.parsePolyToListInput(x); y = obj.parsePolyToListInput(y) a = obj.listToInt(x); b = obj.listToInt(y) bina = int(str(a),2); binb = int(str(b),2) #a = min(bina,binb); b = max(bina,binb); return bina,binb #bina,binb are binary values like 110100101100..... def add(self,a,b): # a,b are GF(2) polynomials like x**7 + x**3 + x**0 .... bina,binb = obj.prepBinary(a,b) return obj.outFormat(bina^binb) #returns binary string def subtract(self,x,y): # same as addition in GF(2) return obj.add(x,y) def multiply(self,a,b): # a,b are GF(2) polynomials like x**7 + x**3 + x**0 .... a,b = obj.prepBinary(a,b) return obj.outFormat(a*b) #returns product of 2 polynomials in gf2 def divide(self,a,b): #a,b are GF(2) polynomials like x**7 + x**3 + x**0 .... a,b = obj.prepBinary(a,b) #bitsa = "{0:b}".format(a); bitsb = "{0:b}".format(b) return obj.outFormat(a/b),obj.outFormat(a%b) #returns remainder and quotient formatted as polynomials def quotient(self,a,b): #separate quotient function for clarity when calling return obj.divide(a,b)[1] def remainder(self,a,b): #separate remainder function for clarity when calling return obj.divide(a,b)[0] def outFormat(self,raw): # process resulting values into polynomial format raw = "{0:b}".format(raw); raw = str(raw[::-1]); g = [] #reverse binary string for enumeration g = [i for i,c in enumerate(raw) if c == '1'] processed = "x**"+" + x**".join(map(str, g[::-1])) if len(g) == 0: return 0 #return 0 if list empty return processed #returns result in gf(2) polynomial form def extendedEuclideanGF2(self,a,b): # extended euclidean. a,b are values 10110011... in integer form inita,initb=a,b; x,prevx=0,1; y,prevy = 1,0 while b != 0: q = int("{0:b}".format(a//b),2) a,b = b,int("{0:b}".format(a%b),2); x,prevx = (int("{0:b}".format(prevx-q*x)), int("{0:b}".format(x,2))); y,prevy=(prevy-q*y, y) #print("%d * %d + %d * %d = %d" % (inita,prevx,initb,prevy,a)) return a,prevx,prevy # returns gcd of (a,b), and factors s and t def modular_inverse(self,a,mod): # a,mod are GF(2) polynomials like x**7 + x**3 + x**0 .... a,mod = obj.prepBinary(a,mod) bitsa = int("{0:b}".format(a),2); bitsb = int("{0:b}".format(mod),2) #return bitsa,bitsb,type(bitsa),type(bitsb),a,mod,type(a),type(mod) gcd,s,t = obj.extendedEuclideanGF2(a,mod); s = int("{0:b}".format(s)) initmi = s%mod; mi = int("{0:b}".format(initmi)) print ("%d * %d mod %d = 1"%(a,initmi,mod)) if gcd !=1: return obj.outFormat(mi),False return obj.outFormat(mi) # returns modular inverse of a,mod obj = gf2pim() </code></pre>
[]
[ { "body": "<p>speaking to exhibit a:</p>\n\n<p>Perhaps I'm missing something, but AFAICT your class does not seem to carry any state: there aren't any variables shared between functions or persisting between function calls. </p>\n\n<p>If that's so, it's easier and simpler just to make it a module -- it's merely a collection of related functions, not collection of data and methods for manipulating the data. You can get away from the whole obj business by just removing the class header and all references to 'self'. Other users would import the module and call the functions directly with no extra work. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T20:12:37.383", "Id": "43583", "Score": "0", "body": "you're right. i will be making the case to leave this as a module. i'm wondering if class or module in this case would affect the performance or if this is more for readability/style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T21:06:46.790", "Id": "43585", "Score": "0", "body": "There's really no performance implications - it's just a paradigm thing. Classes are bundles of state-plus-methods, modules are just collections of methods. Technically modules can have state too (your 'obj' is a module level variable) but by convention most folks use classes for stateful collections of functionality and modules for stateless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T21:09:59.380", "Id": "43586", "Score": "0", "body": "The only other rational for using a class would be if you had sets of similar functionality and passed classes along to other code which could call the methods without knowing implementation details: eg, you might have bunch of classes representing different languages that all had the same 'say_hello' method. Instead of a ton of code for 'if language == 'english' then' choices, you'd just pass in an English or Spanish or Chinese class and the calling code would call 'say_hello' and get the right response. Could do the same with modules but it's more common to uses classes for that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T04:19:01.587", "Id": "27934", "ParentId": "27900", "Score": "2" } }, { "body": "<p>I would first like to recommend reading <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for style recommendations. Following the style guide is optional, but makes your code more readable and more understandable for other pythonistas as much python code out there follows this PEP. There is even a conformance <a href=\"https://pypi.python.org/pypi/pep8\" rel=\"nofollow\">checker</a> you can run yourself.</p>\n\n<p>I would therefore make the class GF2PIM (acronyms are in <code>class</code> names are always a problem) or GF2Pim. And no camelCasing in method names ( parse_poly_to_list_input instead of parsePolyToListInput ).</p>\n\n<p>Within the class methods you refer to the global <code>obj</code>. E.g. in <code>listToInt</code> which calls <code>obj.id()</code>. This then means that within <code>id()</code> (the method from gf2pim, not the python <a href=\"http://docs.python.org/2/library/functions.html#id\" rel=\"nofollow\">build-in function id</a>) the first parameter (<code>self</code>) will be <code>obj</code>. <code>listToInt</code> however is itself called with <code>obj</code> as its first parameter (in <code>prepBinary()</code>). You should remove the references within the <code>gf2pim</code> to <code>obj</code> and only use <code>self</code> so for <code>listToInt()</code> you would get:</p>\n\n<pre><code>def list_to_int(self, lst):\n \"\"\"converts list to integer for later use\"\"\"\n result = self.id(lst)\n return int(''.join(map(str, result)))\n</code></pre>\n\n<p>The comment on what the function does was changed to a documentation string (which can be viewed with obj.list_to_int.<strong>doc</strong> and which intelligent editors will display on use of the method).</p>\n\n<p>As <code>id()</code> is not using <code>self</code> at all you can make it a <a href=\"http://docs.python.org/2/library/functions.html#staticmethod\" rel=\"nofollow\">staticmethod</a>:</p>\n\n<pre><code>@staticmethod\ndef id(lst):\n \"\"\"returns modulus 2 (1,0,0,1,1,....) for input lists\"\"\"\n return [int(lst[i])%2 for i in range(len(lst))]\n</code></pre>\n\n<p>It is unclear how gf2pim is used after the creation of <code>obj</code> doesn't do anything since gf2pim has no <code>__init__()</code>. It is probable that the creation of an gf2pim object can be diverted to the user of this module. </p>\n\n<p>After cleaning things up that way there can probably be done more, but here is where I would start. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T20:15:29.927", "Id": "43584", "Score": "0", "body": "new users can't upvote, so maybe someone will help you out there. i implemented what you said, and it definitely looks better using self instead of some awkward class instance from outside the class, etc. i also put in the doc strings. thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T04:27:19.450", "Id": "27935", "ParentId": "27900", "Score": "2" } } ]
{ "AcceptedAnswerId": "27935", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T14:48:36.100", "Id": "27900", "Score": "3", "Tags": [ "python", "optimization", "performance", "mathematics" ], "Title": "Python -- polynomial operations class" }
27900
<p>Resharper thinks I should change this</p> <pre><code>while (dockPanel.Contents.Count() &gt; 0) </code></pre> <p>to the following:</p> <pre><code>while (dockPanel.Contents.Any()) </code></pre> <p>Without thinking twice about it, I switched to the any version because .Any() is more readable for me. But a coworker of mine sees the change and asked why I did it. I explained that this improves readability but his objection was the following:</p> <ul> <li>Any is an ambiguous word.</li> <li>People may not be familiar with LINQ, so they might not be aware of what Any does at first glance.</li> <li>Count > 0 is universal. You don't have to know C# to find out what you're trying to do.</li> </ul> <p>The confusion is probably compounded by the fact that I'm working overseas. People here speak little to no English here.</p> <p>Which method should I stick with?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T16:09:49.633", "Id": "43508", "Score": "0", "body": "“because I know ReSharper is smarter than me” I've had to disable several ReSharper's suggestions, because they actually produced code that I thought was less readable than the original." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T18:36:57.430", "Id": "43520", "Score": "0", "body": "The while (collection has elements) loop strikes me as odd. Presumably the collection is being emptied out as part of the loop body? Would it be clearer to use a foreach (item in collection) and then empty it at the end?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T20:29:55.527", "Id": "60553", "Score": "0", "body": "I find all three arguments to bogus. What I read from this is one grumped coder who can't handle to be corrected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-17T08:38:29.270", "Id": "170768", "Score": "0", "body": "Note that [`.Count`](https://msdn.microsoft.com/en-us/library/27b47ht3.aspx) and [`.Count()`](https://msdn.microsoft.com/en-us/library/bb338038.aspx) are NOT the same thing when working with `List<T>`." } ]
[ { "body": "<p>For me, it's about intent. What does your code's business logic say if you read it in English (or your native language)?</p>\n\n<p>It usually comes to me as \"If there are any employees who are in the management role, then show a particular option panel\".</p>\n\n<p>And that means <code>.Any()</code>. Not <code>.Count()</code>. Very few times will I find myself using <code>.Count()</code> unless the underlying rule talks about \"more than one\" or \"more than two\" of something.</p>\n\n<p>As a bonus, <code>.Any()</code> can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be <code>IF EXISTS(...)</code> rather than <code>SELECT COUNT ...</code> or even <code>SELECT * ...</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T15:24:56.970", "Id": "27903", "ParentId": "27901", "Score": "19" } }, { "body": "<p>I agree with Resharper and I'd go for the <code>.Any()</code> version.</p>\n\n<p>The reason is that I associate <code>.Count()</code> with operations in which the number of elements actually matters while in your case you just need to check if there is at least one element.</p>\n\n<p>On the opposite <code>.Any()</code> helps you communicate that you need to iterate until you have no more elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T16:35:34.700", "Id": "43511", "Score": "2", "body": "«`.Any()` helps you communicate that you need to iterate __until you have no more elements__ ». I don't think so: Doesn't __`any`__ rather mean you'll stop iterating as soon as you find __one__ match?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T07:39:56.633", "Id": "43952", "Score": "0", "body": "Poster probably meant \"you need to iterate until you have no more elements *that need to be filtered through*\". If it already has a match, then there is no need to filter through any more elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-02T16:58:40.077", "Id": "220934", "Score": "0", "body": "Any is perfect. \"while there's **any**thing there do this...\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T15:34:43.860", "Id": "27905", "ParentId": "27901", "Score": "3" } } ]
{ "AcceptedAnswerId": "27903", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T14:49:24.390", "Id": "27901", "Score": "6", "Tags": [ "c#" ], "Title": "List<T> Any vs Count, which one is better for readability?" }
27901
<p>This is a multi-threaded socket client written to talk to the <a href="http://scrolls.com" rel="nofollow">Scrolls</a> socket server. The idea is to send commands to the socket server and respond to messages received via callbacks. I've never done multi-threading before and would like the code reviewed for code correctness, best practices, and potential issues regarding how I'm handling threading.</p> <p><a href="https://github.com/david-torres/ScrollsSocketClient" rel="nofollow">GitHub</a></p> <pre><code>from Crypto.Cipher import PKCS1_v1_5 from Crypto.PublicKey import RSA from base64 import b64encode from threading import Thread from Queue import Queue import socket import json import time class PingThread(Thread): def __init__(self, scrolls_client): self.scrolls_client = scrolls_client self.stopped = False Thread.__init__(self) def run(self): while not self.stopped: self.scrolls_client.send({'msg': 'Ping'}) time.sleep(10) class MessageThread(Thread): def __init__(self, scrolls_client): self.scrolls_client = scrolls_client self.stopped = False Thread.__init__(self) def run(self): while not self.stopped: # grab a message from queue message = self.scrolls_client.queue.get() # make a copy of the current subscribers to keep this thread-safe current_subscribers = dict(self.scrolls_client.subscribers) # send message to subscribers for subscriber_key, subscriber_callback in current_subscribers.iteritems(): # msg or op should match what we asked for if 'msg' in message and message['msg'] == subscriber_key: subscriber_callback(message) elif 'op' in message and message['op'] == subscriber_key: subscriber_callback(message) # signals to queue job is done self.scrolls_client.queue.task_done() class ReceiveThread(Thread): def __init__(self, scrolls_client): self.scrolls_client = scrolls_client self.stopped = False Thread.__init__(self) def run(self): while not self.stopped: self.scrolls_client.receive() class ScrollsSocketClient(object): """ A Python client for the Scrolls socket server. Usage: YOUR_SCROLLS_EMAIL = 'user@example.com' YOUR_SCROLLS_PASSWORD = 'password' scrolls = ScrollsApi(YOUR_SCROLLS_EMAIL, YOUR_SCROLLS_PASSWORD) """ queue = Queue() subscribers = {} _socket_recv = 8192 _scrolls_host = '54.208.22.193' _scrolls_port = 8081 _scrolls_publickey = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYUK5tWE8Yb564e5VBs05uqh38 mLSRF76iHY4IVHtpXT3FiI6SWoVDyOAiAAe/IJwzUmjCp8V4nmNX26nQuHR4iK/c U9G7XhpBLfmQx0Esx5tJbYM0GR9Ww4XeXj3xZZBL39MciohrFurBENTFtrlu0EtM 3T8DbLpZaJeXTle7VwIDAQAB -----END PUBLIC KEY-----""" def __init__(self, email, password): self.email = email self.password = password self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((self._scrolls_host, self._scrolls_port)) self.ping_thread = PingThread(self) self.message_thread = MessageThread(self) self.receive_thread = ReceiveThread(self) # self.ping_thread.start() self.receive_thread.start() self.message_thread.start() def login(self): login_params = { 'msg': 'SignIn', 'email': self._encrypt(self.email), 'password': self._encrypt(self.password) } self.send(login_params) self.ping_thread.start() def subscribe(self, event, callback): # add subscribers self.subscribers[event] = callback def unsubscribe(self, event): # rm subscribers self.subscribers.pop(event) def send(self, params): # send message self.socket.send(json.dumps(params)) def receive(self): stream_data = '' data_json = None while (1): # read data from the buffer data = self.socket.recv(self._socket_recv) if not data: # no more data being transmitted break else: # append data to the response stream_data += data try: # line breaks means we are handling multiple responses if stream_data.find("\n\n"): # split and parse each response for stream_data_line in stream_data.split("\n\n"): # try to load as JSON data_json = json.loads(stream_data_line) # we have a response, add it to the queue self.queue.put(data_json) except: # invalid json, incomplete data pass def quit(self): # stop all threads and close the socket self.receive_thread.stopped = True self.receive_thread._Thread__stop() self.message_thread.stopped = True self.message_thread._Thread__stop() self.ping_thread.stopped = True self.ping_thread._Thread__stop() self.socket.close() def _encrypt(self, data): key = RSA.importKey(self._scrolls_publickey) cipher = PKCS1_v1_5.new(key) encrypted_data = cipher.encrypt(data) return b64encode(encrypted_data) </code></pre>
[]
[ { "body": "<p>Instead of:</p>\n\n<pre><code>Thread.__init__(self)\n</code></pre>\n\n<p>Do (for example):</p>\n\n<pre><code>super(MessageThread, self).__init__()\n</code></pre>\n\n<p>Also it's more Pythonic to do:</p>\n\n<pre><code>while True:\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>while (1):\n</code></pre>\n\n<p>Instead of using the stopped variables, it may be more efficient to use a variable such as:</p>\n\n<pre><code>self.active = True\n</code></pre>\n\n<p>That way you can do this which saves you from having to do extra processing on the \"not\" every iteration:</p>\n\n<pre><code>while self.active:\n</code></pre>\n\n<p>Even better though may be to just do while True and instead of setting stopped to True and calling <em>Thread</em>_stop(), just call exit() on the threads, then you shouldn't need the stopped variables at all.</p>\n\n<p>Also in receive() you could simplify it slightly</p>\n\n<pre><code>def receive(self):\n stream_data = ''\n\n while True:\n # read data from the buffer\n data = self.socket.recv(self._socket_recv)\n\n if not data:\n # no more data being transmitted\n return # now you don't need an else\n\n # append data to the response\n stream_data += data\n try:\n # line breaks means we are handling multiple responses\n if stream_data.find(\"\\n\\n\"):\n # split and parse each response\n for stream_data_line in stream_data.split(\"\\n\\n\"):\n\n # we have a response, add it to the queue\n # no need to store json.loads result that's only used once\n self.queue.put(json.loads(stream_data_line))\n except:\n # invalid json, incomplete data\n pass\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T00:45:25.300", "Id": "28108", "ParentId": "27909", "Score": "2" } }, { "body": "<p>You should read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP0008</a>, it's the invaluable Python style guide. One such suggestion is to structure your modules so that all the plain <code>import</code> statements are first, separated from the <code>from _ import _</code> lines. It's neater and easier to read.</p>\n\n<pre><code>import socket\nimport json\nimport time\n\nfrom base64 import b64encode\nfrom threading import Thread\n\nfrom Queue import Queue\nfrom Crypto.Cipher import PKCS1_v1_5\nfrom Crypto.PublicKey import RSA\n</code></pre>\n\n<p>Why are you using two different <code>if</code> statements to run the same line? If you need to run it in either case, use <code>or</code>, not an <code>elif</code>.</p>\n\n<pre><code> if ('msg' in message and message['msg'] == subscriber_key or\n 'op' in message and message['op'] == subscriber_key):\n subscriber_callback(message)\n</code></pre>\n\n<p>If you're going to have a comment under a function declaration, you should make it a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">docstring</a> so that it can be useful to others reading your code (as docstrings are accessible programmatically through the interpreter). </p>\n\n<pre><code>def subscribe(self, event, callback):\n \"\"\"Add subscribers\"\"\"\n</code></pre>\n\n<p>Though in that particular case it seems pretty clear what <code>subscribe</code> does to me.</p>\n\n<p>Your <code>receive</code> function has a lot of unnecessary comments, I'd strip them out especially in places that are pretty clear from the actual code. In particular:</p>\n\n<pre><code> if not data:\n # no more data being transmitted\n break\n else:\n # append data to the response\n stream_data += data\n</code></pre>\n\n<p>Instead of using <code>str.find(s)</code> use <code>if s in str</code>. It's faster and more Pythonic:</p>\n\n<pre><code> if \"\\n\\n\" in stream_data:\n</code></pre>\n\n<p>Never use <code>except</code> without giving it a specific exception to look for. If you made a syntax error like a typo then you'd actually not notice because of that <code>except</code> and you'd probably think there was a problem with the JSON. If you're looking for errors from invalid JSON, that raises a <code>ValueError</code>, so raise that instead.</p>\n\n<pre><code> except ValueError:\n # invalid json, incomplete data\n pass\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-28T17:06:53.867", "Id": "102198", "ParentId": "27909", "Score": "1" } } ]
{ "AcceptedAnswerId": "28108", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T16:59:39.277", "Id": "27909", "Score": "3", "Tags": [ "python", "multithreading", "socket" ], "Title": "Multi-threaded socket client for Scrolls" }
27909
<p>I was able to pull the records I wanted but I have a feeling it could be written better for these particular MySQL query strings.</p> <pre><code>SELECT ID,XAxis,YAxis,Player,Castle,Alliance FROM SC75 WHERE Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75) AND hex(Player) IN (hex('Vandiel')) UNION SELECT SC.ID,XAxis,YAxis,SC.Player,Castle,Alliance FROM SC75 AS SC INNER JOIN AltFiller AS AF ON hex(AF.Player) IN (hex('Vandiel')) WHERE SC.Player = AF.Alts AND Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75) ORDER BY Player,Castle </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:24:35.277", "Id": "43535", "Score": "0", "body": "This doesn't look too awkward given the scarce information provided, but for starters - why do you have a table named ``SC75``? Does that mean that you also have tables ``SC74``, ``SC73`` and so forth? Does the ``75`` in ``SC75`` relate to ``Server = 75``?\n\nIf you posted the schema, I could have some comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:59:29.103", "Id": "43541", "Score": "0", "body": "Pretty much and I came across other Database knowledgable person and was pointed out a few flaw but improved, will be posting in a few what was pointed out :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:02:21.563", "Id": "43543", "Score": "0", "body": "Okay, but a broken schema leads to broken queries. This query could potentially be much simpler if you used a better schema. In other words, asking about whether a query \"looks right\" will usually wind up becoming a discussion about the schema it is using. So you should start out getting the schema right (feel free to post it in another review question here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:10:49.560", "Id": "43545", "Score": "0", "body": "See below for changes I've made." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T16:57:10.073", "Id": "43576", "Score": "0", "body": "Sorry. I think you're answering a question I didn't ask :) When i write \"database schema\", I refer to the table layout." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T07:50:34.803", "Id": "48223", "Score": "0", "body": "Explain why you use `hex(stuff) IN hex('Vandiel')` instead of just `stuff = 'Vandiel'`?" } ]
[ { "body": "<p>The two parts to the <code>UNION</code> have too much in common. I believe this query is equivalent to yours.</p>\n\n<pre><code>SELECT ID, XAxis, YAxis, Player, Castle, Alliance\n FROM SC75\n WHERE\n Snap = (SELECT MAX(SavedSnap) FROM DataSnap WHERE Server = 75)\n AND\n (\n (hex(Player) IN (hex('Vandiel'))\n OR\n Player IN\n (\n SELECT AF.Alts\n FROM AltFiller AS AF\n WHERE hex(AF.Player) IN (hex('Vandiel'))\n )\n )\n ORDER BY Player, Castle;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T07:39:53.070", "Id": "30350", "ParentId": "27911", "Score": "2" } } ]
{ "AcceptedAnswerId": "30350", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T18:19:10.120", "Id": "27911", "Score": "1", "Tags": [ "sql", "mysql" ], "Title": "Pulling player records" }
27911
<p>I'm always programmatically creating and laying out UI elements in multiple ViewControllers and I've wanted an easy way to get relevant Screen information (sizes/points) globally using a helper class. </p> <p>I've created a FlexibleScreen class and would like some constructive feedback. In addition to the typical code review feedback of format, syntax, etc I would really like to know how well this solves my problem functionally and what suggestions you have about the design or what additional functionality I could add.</p> <p><strong>FlexibleScreen.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface FlexibleScreen : NSObject +(CGSize)getScreenSize; +(CGPoint)getCenter; +(CGPoint)getCenterWithY:(double)y; +(CGPoint)getCenterWithX:(double)x; @end </code></pre> <p><strong>FlexibleScreen.m</strong></p> <pre><code>#import "FlexibleScreen.h" @interface FlexibleScreen() @property (assign) CGRect bounds; @end @implementation FlexibleScreen +(CGSize)getScreenSize { return CGSizeMake([[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height); } +(CGPoint)getCenter { return CGPointMake([[UIScreen mainScreen] bounds].size.width/2, [[UIScreen mainScreen] bounds].size.height/2); } +(CGPoint)getCenterWithY:(double)y { return CGPointMake([[UIScreen mainScreen] bounds].size.width/2, y); } +(CGPoint)getCenterWithX:(double)x { return CGPointMake(x, [[UIScreen mainScreen] bounds].size.height/2); } @end </code></pre> <p><strong>Implementing Code</strong></p> <pre><code>#import "FlexibleScreen.h" </code></pre> <p>...</p> <pre><code>CGRect headerFrame = CGRectMake(0, 0, [FlexibleScreen getScreenSize].width, HEADER_HEIGHT); CGRect footerFrame = CGRectMake(0, [FlexibleScreen getScreenSize].height-FOOTER_HEIGHT, [FlexibleScreen getScreenSize].width, FOOTER_HEIGHT); </code></pre> <p>...</p> <pre><code>[label setCenter:[FlexibleScreen getCenterWithY:0]]; </code></pre> <p><strong>UPDATE:</strong> As I used this more I realized I wanted it to be a lot simpler. Here is my latest version <a href="https://github.com/koreyhinton/UIScreenFlexible" rel="nofollow">GitHub: UIScreen+Flexible</a>.</p>
[]
[ { "body": "<p>Some thoughts on it:</p>\n\n<ol>\n<li><p><strong>Code:</strong> I'd suggest to create a <a href=\"http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html\" rel=\"nofollow\">Category</a> on <code>UIScreen</code>. This is even more elegant than creating a separate class.</p></li>\n<li><p><strong>Naming:</strong> In Objective-C getter usually do not have the prefix <em>\"get\"</em>.</p></li>\n<li><p><strong>General approach:</strong> Without knowing the background of your app and any detailed implementation, it's not common to layout UIViews relatively to the screen. As you're using <code>UIViewControllers</code>, any additional view should be added as a subview to the <code>UIViewController's view</code>. This ensures that layout and orientation changes are handled for you and are automatically being applied to all subviews by the <code>UIViewController</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T06:39:03.537", "Id": "28632", "ParentId": "27914", "Score": "2" } }, { "body": "<p>Here are some changes I've made so far to <a href=\"https://github.com/koreyhinton/FlexibleScreen\" rel=\"nofollow\">FlexibleScreen (GitHub)</a>:</p>\n\n<h2>1. Status Bar Height</h2>\n\n<p>I also found that the status bar height plays a role into how much height is left on-screen if the status bar is present so I added this method which will be used by +getScreenSize to report an accurate screen size:</p>\n\n<pre><code>+(double)statusBarHeight\n{\n double statusBarHeight = 0;\n if (![UIApplication sharedApplication].statusBarHidden){\n statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;\n }\n return statusBarHeight;\n}\n</code></pre>\n\n<h2>2. Global Import FlexibleScreen</h2>\n\n<p>I also imported FlexibleScreen.h in *-Prefix.ch so that it was globally accessible without having to import in each file. I will eventually change FlexibleScreen to be a category like Florain Mielke suggested and that way I won't have to import it at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:41:02.940", "Id": "28747", "ParentId": "27914", "Score": "0" } }, { "body": "<p>Consider using more of what Core Graphics gives you. There are methods along the lines of <code>CGRectGetMaxX(rect)</code>, <code>CGRectGetMidY(rect)</code> and <code>CGRectGetWidth(rect)</code> that does that kind of basic math for you. It reads cleaner and other coders who are used to Objective-C will immediately recognize them and understand the code.</p>\n\n<p>Also, there is some code duplication where you calculate the center x twice and the center y twice. You can introduce two private methods to get rid of that duplication (I've also removed the \"get\" prefix as it is not commonly used in Objective-C and switched to <code>CGFloat</code> instead of <code>double</code>).</p>\n\n<p>(If you really want to get rid of code duplication then you can create a method to get the bounds of the main screen. I did so in the code below)</p>\n\n<pre><code>+(CGRect)screenBounds\n{\n return [[UIScreen mainScreen] bounds];\n}\n\n+(CGFloat)centerX \n{\n return CGRectGetMidX([self screenBounds]);\n}\n\n+(CGFloat)centerY \n{\n return CGRectGetMidY([self screenBounds]);\n}\n\n+(CGPoint)center\n{\n return CGPointMake([self centerX], [self centerY]);\n}\n\n+(CGPoint)centerWithY:(CGFloat)y\n{\n return CGPointMake([self centerX], y);\n}\n\n+(CGPoint)centerWithX:(CGFloat)x\n{\n return CGPointMake(x, [self centerY]);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:36:18.293", "Id": "30276", "ParentId": "27914", "Score": "2" } } ]
{ "AcceptedAnswerId": "28632", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T18:45:16.757", "Id": "27914", "Score": "0", "Tags": [ "classes", "objective-c", "ios" ], "Title": "Objective-C class for placing UI elements based on screen size" }
27914
<p>I'd appreciate a review of at least some of this javascript, if anyone has time. It's really long, but I think it's useful. It's designed to let you create forms and do javascripty things by only modifying html tags and attributes.</p> <p>Take a look at what it's supposed to do here: <a href="https://docs.google.com/document/d/1T08AJr4OGR2ohXLeSK3WjKn8zG-sSLi3Vz1Ya5tLkQY/edit?usp=sharing" rel="nofollow">https://docs.google.com/document/d/1T08AJr4OGR2ohXLeSK3WjKn8zG-sSLi3Vz1Ya5tLkQY/edit?usp=sharing</a></p> <pre><code>//Configuration variables var config = jQuery("edfconfig"); function getConfigBoolean(attr) { if (config != null) return jQuery(config).attr(attr) != undefined; } function getConfigValue(attr) { if (config != null) return jQuery(config).attr(attr); } var noasterisks = getConfigBoolean("noasterisks"); var addafter = getConfigBoolean("addafter"); var doactions = getConfigBoolean("doactions"); var noappend = getConfigBoolean("noappend"); var requiredmessage = getConfigValue("requiredmessage"); var requiredmessageid = getConfigValue("requiredmessageid"); //eDomForm variables var attrs = jQuery("edfvars")[0]; var variables = {}; if (attrs != null) for (i=0;i&lt;attrs.attributes.length;i++) { variables[attrs.attributes[i].nodeName] = attrs.attributes[i].nodeValue; } //Function because jQuery doesn't have a selector for the name attribute function getByName(n) { return document.getElementsByName(n); } //required fields have the class required_field var required = jQuery(".required_field"); //message div to display global form messages var message = jQuery("#message"); //reference to the entire form itself var form = jQuery("#form"); //form data jQuery(form).data("required_empty",required.length); //Add next and back buttons jQuery(".form_page").each(function(i){ jQuery(this).prepend('&lt;button type="button" class="back"&gt;Back&lt;/button&gt; &lt;button type="button" class="next"&gt;Next&lt;/button&gt;'); }); //Next and Back buttons var pages = jQuery(".form_page"); var backButtons = jQuery(".back"); var nextButtons = jQuery(".next"); for (i=0;i&lt;pages.length;i++) { if (i != pages.length-1) { nextButtons[i].onclick = function() { jQuery(this).closest("div").fadeOut(); jQuery(this).closest("div").nextAll(":not(.disabled):first").fadeIn(); }; } else { jQuery(nextButtons[i]).remove(); } if (i != 0) { backButtons[i].onclick = function(i) { jQuery(this).closest("div").fadeOut(); jQuery(this).closest("div").prevAll(":not(.disabled):first").fadeIn(); }; } else { jQuery(backButtons[i]).remove(); } } //Aliases function getByAlias(a) { return jQuery("[alias="+a+"]"); } function hasClass(element, cls) { return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') &gt; -1; } var aliases = jQuery(".alias"); //Connect all aliases and original fields to each other jQuery(".alias").each(function(i){ var alias = jQuery(this).attr("alias"); var allaliases = jQuery("[alias="+alias+"]"); var alloriginals = jQuery("."+alias); jQuery(alloriginals).each(function(j){ var thisOriginal = this; jQuery(allaliases).each(function(k) { var thisAlias = this; if (hasClass(thisOriginal,"required_field")) { jQuery(thisAlias).addClass("required_field"); } thisAlias.onchange = aliasChange.bind(null,thisAlias,thisOriginal,thisAlias.onchange); thisOriginal.onchange = aliasChange.bind(null,thisOriginal,thisAlias,thisOriginal.onchange); jQuery(allaliases).each(function(l){ var innerAlias = this; innerAlias.onchange = aliasChange.bind(null,innerAlias,thisAlias,innerAlias.onchange); thisAlias.onchange = aliasChange.bind(null,thisAlias,innerAlias,thisAlias.onchange); }); }); jQuery(alloriginals).each(function(j){ var innerOriginal = this; innerOriginal.onchange = aliasChange.bind(null,innerOriginal,thisOriginal,innerOriginal.onchange); thisOriginal.onchange = aliasChange.bind(null,thisOriginal,innerOriginal,thisOriginal.onchange); }); }); }); function aliasChange(o,a,func) { if (func != null) func(); a.value = o.value; if (a.onblur != null) a.onblur(); } var radioGroupCounter = 1; var actions = {}; jQuery(document).ready(function() { //Prevent form submission if required fields have not been filled in if (form[0] != null) form[0].onsubmit = function() { var required_fields = document.getElementsByClassName("required_field"); for (i=0;i&lt;required_fields.length;i++) { if (required_fields[i].value == "") { jQuery("#"+requiredmessageid).html(requiredmessage); return false; } } jQuery("#"+requiredmessageid).html(""); return true; }; window.activate = function(func) { actions[func](); }; //action functions window.write = function(text) { document.write(text); }; window.writeTo = function(to,text) { jQuery("."+to).each(function(){ jQuery(this).append(text); }); }; window.writeOver = function(to,text) { jQuery("."+to).each(function() { jQuery(this).html(text); }); }; window.hide = function(what) { jQuery("."+what).each(function() { jQuery(this).hide(); }); }; window.show = function(what) { jQuery("."+what).each(function() { jQuery(this).show(); }); }; window.set = function(what,val) { variables[what] = val; }; //Action tags function handleActionTags() { jQuery("action").each(function(i) { var id = jQuery(this).attr("id"); var type = jQuery(this).attr("type"); var args = jQuery(this).attr("arguments").split(" "); for (i=0;i&lt;args.length;i++) { var name = args[i].match(/%(.+)%/); if (name != null) { args[i] = variables[name[1]]; } } actions[id] = function() { window[type].apply(null,args); }; }); } handleActionTags(); //Custom Events jQuery("[onempty]").each(function() { if (jQuery(this).val() == "") { jQuery(this).data("empty",true); } jQuery(this).on("keyup",function() { if (jQuery(this).val() == "") { jQuery(this).data("empty",true); eval(jQuery(this).attr("onempty")); } }); }); jQuery("[onnotempty]").each(function() { jQuery(this).on("keyup",function() { if (jQuery(this).val() != "" &amp;&amp; jQuery(this).data("empty")) { jQuery(this).data("empty",false); eval(jQuery(this).attr("onnotempty")); } }); }); jQuery("[oncheck]").each(function() { jQuery(this).on("change",function() { if (jQuery(this).is(":checked")) { eval(jQuery(this).attr("oncheck")); } }); }); jQuery("[onuncheck]").each(function() { jQuery(this).on("change",function() { if (!jQuery(this).is(":checked")) { eval(jQuery(this).attr("onuncheck")); } }); }); //Hidden pages function handleHiddenPages() { jQuery(".revealer").each(function(i){ var page = jQuery(this).attr("page"); jQuery(this).click(function(){ if (jQuery(this).is(":checked")) { jQuery("."+page).removeClass("disabled"); } else { jQuery("."+page).addClass("disabled"); } }); }); } handleHiddenPages(); //Switchers function handleSwitchers() { jQuery(".switcher").each(function(x){ var connections = jQuery(this).attr("connections"); connections = jQuery.parseJSON(connections); var connectedSections = {}; for (var key in connections) { //if something like a-b if (connections[key].indexOf("-") &gt; -1) { var nums = connections[key].split("-"); var resultNums = []; for (i=0;i&lt;nums.length;i++) { nums[i] = parseInt(nums[i]); } for (i=nums[0];i&lt;=nums[nums.length-1];i++) { resultNums.push(i+""); connectedSections[i] = key; } } else { if (connections.hasOwnProperty(key)) connectedSections[connections[key]] = key; } } jQuery(this).change(function(){ for (var key in connectedSections) { jQuery("."+connectedSections[key]).hide(); } jQuery("."+connectedSections[jQuery(this).val()]).show(); }); }); } handleSwitchers(); //Displayers/Hiders function handleDisplayers() { jQuery(".displayer").each(function(x){ var connected = jQuery(this).attr("display"); var special = ""; var connecteds = []; if (connected.indexOf(" ") &gt; -1) { connecteds = connected.split(" "); var special = connecteds[0]; connected = connecteds[1]; } var name = jQuery(this).attr("name"); var group = getByName(name); jQuery(group).each(function() { jQuery(this).on("click",function() { var button = this; if (jQuery(this).attr("display") != null) { if (special == "") { jQuery("."+connected).each(function() { jQuery(this).show(); }); } else if (special == "next") { jQuery("."+connected).each(function() { if (button.compareDocumentPosition(this) == 4) { jQuery(this).show(); return false; } }); } else if (special == "prev") { jQuery(jQuery("."+connected).get().reverse()).each(function(i) { if (button.compareDocumentPosition(this) == 2) { jQuery(this).show(); return false; } }); } }else { if (special == "") { jQuery("."+connected).each(function() { jQuery(this).hide(); }); } else if (special == "next") jQuery("."+connected).each(function() { if (button.compareDocumentPosition(this) == 4) { jQuery(this).hide(); return false; } }); else if (special == "prev") jQuery(jQuery("."+connected).get().reverse()).each(function(i) { if (button.compareDocumentPosition(this) == 2) { jQuery(this).hide(); return false; } }); } }); }); }); } handleDisplayers(); //findNext function from stackoverflow /** * Find the next element matching a certain selector. Differs from next() in * that it searches outside the current element's parent. * * @param selector The selector to search for * @param steps (optional) The number of steps to search, the default is 1 * @param scope (optional) The scope to search in, the default is document wide */ $.fn.findNext = function(selector, steps, scope) { // Steps given? Then parse to int if (steps) { steps = Math.floor(steps); } else if (steps === 0) { // Stupid case :) return this; } else { // Else, try the easy way var next = this.next(selector); if (next.length) return next; // Easy way failed, try the hard way :) steps = 1; } // Set scope to document or user-defined scope = (scope) ? $(scope) : $(document); // Find kids that match selector: used as exclusion filter var kids = this.find(selector); // Find in parent(s) hay = $(this); while(hay[0] != scope[0]) { // Move up one level hay = hay.parent(); // Select all kids of parent // - excluding kids of current element (next != inside), // - add current element (will be added in document order) var rs = hay.find(selector).not(kids).add($(this)); // Move the desired number of steps var id = rs.index(this) + steps; // Result found? then return if (id &gt; -1 &amp;&amp; id &lt; rs.length) return $(rs[id]); } // Return empty result return $([]); } //Adding New Sections function handleAdds() { jQuery(".add").each(function(x){ var add = jQuery(this).attr("add"); if (add.indexOf(" ") &gt; -1) { add = add.split(" "); } var to = jQuery(this).attr("to"); var radiogroup = jQuery(this).attr("radiogroup"); if (radiogroup != null) radiogroup = radiogroup.split(" "); var cpy = jQuery("&lt;div /&gt;").append(jQuery("."+add).clone()).html(); if (to == null) { jQuery(this).click(function() { var text = cpy; var counter = radioGroupCounter++; if (radiogroup != null) for (i=0;i&lt;radiogroup.length;i++) { var re = new RegExp(radiogroup[i]+"\\[\\d\\]","g"); text = text.replace(re,radiogroup[i]+"["+(counter)+"]"); } if (addafter) jQuery(this).after(text); else jQuery(this).before(text); handleHiddenPages(); handleDisplayers(); handleSwitchers(); }); } else { if (to.indexOf(" ") &gt; -1) { to = to.split(" "); } jQuery(this).click(function() { var text = cpy; var counter = radioGroupCounter++; if (radiogroup != null) for (i=0;i&lt;radiogroup.length;i++) { var re = new RegExp(radiogroup[i]+"\\[\\d\\]","g"); text = text.replace(re,radiogroup[i]+"["+(counter)+"]"); console.log(text); } jQuery("#"+to).append(text); handleHiddenPages(); handleDisplayers(); handleSwitchers(); }); } }); } handleAdds(); //Action tags function handleAll() { handleHiddenPages(); handleDisplayers(); handleSwitchers(); handleAdds(); handleActionTags(); } }); required = jQuery(".required_field"); //Loop through required fields, adding the onblur event //so that whenever the user deselects a required field, //if it is blank the asterisk will turn red. for (i=0;i&lt;required.length;i++) { jQuery(required[i]).after("&lt;span&gt;*&lt;/span&gt;"); jQuery(required[i]).data("empty",true); required[i].onblur = function() { if (this.value == "") { jQuery(this).next().css("color","#f00"); } else { jQuery(this).next().css("color","#000"); } }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T01:45:23.903", "Id": "43554", "Score": "1", "body": "Just in the first few lines: config if a jQuery object, but you're still doing jQuery(config), so you're creating another jQuery object. Not only that, but you're doing it every time you call getConfig*." } ]
[ { "body": "<p>After looking through your code I have a few suggestions for you that are mainly best practice type suggestions:</p>\n\n<ol>\n<li><strong>Avoid global variables</strong></li>\n</ol>\n\n<p>You are defining just about all of your code at the global scope which is a bad practice that can lead to conflicts with other scripts. For instance, you have defined <code>config</code> as a global variable. That is a really common variable name and another script may use a global variable named <code>config</code> which could cause problems with both scripts. </p>\n\n<p>Consider at the very least defining all of your code inside a self-executing function:</p>\n\n<p><code>(function(){/*Your code*/});</code></p>\n\n<p>Or even better create a namespace and define all of your variables and functions there:</p>\n\n<pre><code>var yourNamespace = {\n YourFunctionName : function(){},\n config : {}\n}\n</code></pre>\n\n<ol>\n<li><strong>Always use brackets after <code>if</code> statements</strong></li>\n</ol>\n\n<p>In several place you are omitting the <code>{}</code> after if statements. This is perfectly valid JavaScript, but it creates some readability issues and can also lead to bugs. Lets say in the future you require two statements after your <code>if</code> statement and you forget to add the braces. Anyway, the point is there is no good reason not to put in the braces.</p>\n\n<ol>\n<li><strong>Use <code>!==</code> and <code>===</code> instead of <code>!=</code> and '=='</strong></li>\n</ol>\n\n<p>There is no good reason to use <code>!=</code> and <code>==</code>. When testing for equality or inequality you should be checking for type and value equality. Using the <code>!=</code> and <code>==</code> can lead to surprising results that are not at all intuitive. </p>\n\n<ol>\n<li><strong>Use a single <code>var</code> keyword</strong></li>\n</ol>\n\n<p>This is a bit of a style suggestion that most JS developers adhere to but is by no means absolutely necessary. Again, this will make your code look better to many developers but is functionally equivalent to what you have.</p>\n\n<pre><code>var noasterisks = getConfigBoolean(\"noasterisks\"),\n addafter = getConfigBoolean(\"addafter\"),\n doactions = getConfigBoolean(\"doactions\"),\n noappend = getConfigBoolean(\"noappend\"),\n requiredmessage = getConfigValue(\"requiredmessage\"),\n requiredmessageid = getConfigValue(\"requiredmessageid\");\n</code></pre>\n\n<p>This is not an exhaustive list, but the first three suggestions will make your code more maintainable and easier to debug than it stands.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:00:51.263", "Id": "43531", "Score": "0", "body": "Thanks for the suggestions. I'll probably use the majority of them. Especially the first one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T19:45:03.510", "Id": "27920", "ParentId": "27915", "Score": "3" } } ]
{ "AcceptedAnswerId": "27920", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T18:59:11.190", "Id": "27915", "Score": "3", "Tags": [ "javascript", "html", "form", "dom" ], "Title": "Javascript Form Manipulator Code Review" }
27915
<p>I have created a video/article slider. It works fine, but I have a feeling it's not quite a standard solution.</p> <p>I would appreciate it if someone could review my code, so that if there are mistakes, I could learn from them.</p> <pre><code>&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script&gt; var move = function slide() { $('#container').animate({'marginLeft' : '-=707px'}, 500); } //setInterval(function(){slide()},3000000); &lt;/script&gt; &lt;script&gt; window.addEventListener("load", function(){ //slide 1, slide 2 setTimeout(function(){ var video0 = document.createElement('video'); video0.src = 'images/video/trx.mp4'; video0.id = 'video0'; video0.autoplay = true; video0.controls = true; document.getElementById("vidcont_0").appendChild(video0) slide2(); },30000); }); //slide 3 var slide2 = function(){ move(); setTimeout(function(){ slide3(); }, 30000); } //slide 4 var slide3 = function(){ move(); setTimeout(function(){ var video1 = document.createElement('video'); video1.src = 'images/video/trx.mp4'; video1.id = 'video1'; video1.autoplay = true; video1.controls = true; document.getElementById("vidcont_1").appendChild(video1); slide4(); }, 30000); } //slide 5 var slide4 = function(){ move(); setTimeout(function(){ slide5(); }, 30000); } //slide 6 function slide5(){ move(); setTimeout(function(){ video2 = document.createElement('video'); video2.src = 'images/video/trx.mp4'; video2.id = 'video2'; video2.autoplay = true; video2.controls = true; document.getElementById("vidcont_2").appendChild(video2); //window.open("http://server.info-spot.net", "_self"); slide6(); }, 30000); } //slide 7 var slide6 = function(){ move(); setTimeout(function(){ move(); }, 30000); } &lt;/script&gt; &lt;style type="text/css"&gt; body {} #wrapper {width:707px; height:820px;overflow:;} #container {width:5000px;height:820px;} #video0 {width:707px; height:820px;float:left;} #video1 {width:707px;height:820px;float:left;background:##F93;} #video2 {width:707px;height:820px;float:left;background:#093;} #video3 {width:707px;height:820px;float:left;background:#F0F;} #article0 {float:left;width:707px;height:820px;background:#999;} #article1 {float:left;width:707px;height:820px;background:#f00;} #article2 {float:left;width:707px;height:820px;background:#06F;} #article3 {float:left;width:707px;height:820px;background:#06F;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;div id="container"&gt; &lt;div id="article0"&gt;Article 0&lt;/div&gt; &lt;div id="vidcont_0"&gt;&lt;/div&gt; &lt;div id="article1"&gt;Article 1&lt;/div&gt; &lt;div id="vidcont_1"&gt;&lt;/div&gt; &lt;div id="article2"&gt;Article 2&lt;/div&gt; &lt;div id="vidcont_2"&gt;&lt;/div&gt; &lt;div id="article3"&gt;Article 3&lt;/div&gt; &lt;/div&gt;&lt;!----end container---&gt; &lt;/div&gt; &lt;!----end wrapper---&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I would consider having the css be in an external css file and javascript in an external js file since there is quite a bit of non-HTML code, but that is just my own preference.</p>\n\n<p>I would get rid of extra <strong>whitespace</strong> and a lot of rework can be done with <strong>indentation</strong> to make the code more readable. </p>\n\n<p>You can also <strong>group variable assignments together</strong>:</p>\n\n<pre><code>var video1 = document.createElement('video');\nvideo1.src = 'images/video/trx.mp4';\nvideo1.id = 'video1';\nvideo1.autoplay = true;\nvideo1.controls = true;\n</code></pre>\n\n<p>And <strong>group methods together</strong>:</p>\n\n<pre><code>document.getElementById(\"vidcont_2\").appendChild(video2); \nslide6();\n</code></pre>\n\n<p>I would <strong>consolidate &lt;script&gt; tags</strong> that are right next to each other.</p>\n\n<p><strong>Remove old code</strong> that is commented out if you're not planning on using it.</p>\n\n<hr>\n\n<h2>Reformatted:</h2>\n\n<pre><code>&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\" type=\"text/javascript\"&gt;\n\nvar move = function slide() {\n $('#container').animate({'marginLeft' : '-=707px'}, 500);\n}\n\nwindow.addEventListener(\"load\", function(){\n\n //slide 1, slide 2\n setTimeout(function(){\n var video0 = document.createElement('video');\n video0.src = 'images/video/trx.mp4';\n video0.id = 'video0';\n video0.autoplay = true;\n video0.controls = true;\n\n document.getElementById(\"vidcont_0\").appendChild(video0);\n slide2();\n\n },30000);\n});\n\n//slide 3\nvar slide2 = function(){ \n\n move(); \n\n setTimeout(function(){ \n slide3(); \n }, 30000);\n}\n\n//slide 4\nvar slide3 = function(){ \n move(); \n\n setTimeout(function(){ \n var video1 = document.createElement('video');\n video1.src = 'images/video/trx.mp4';\n video1.id = 'video1';\n video1.autoplay = true;\n video1.controls = true;\n\n document.getElementById(\"vidcont_1\").appendChild(video1); \n slide4();\n\n }, 30000);\n }\n\n //slide 5\n var slide4 = function(){ \n move(); \n setTimeout(function(){ \n slide5(); \n\n }, 30000);\n}\n\n//slide 6\nfunction slide5(){ \n move(); \n\n setTimeout(function(){\n video2 = document.createElement('video');\n video2.src = 'images/video/trx.mp4';\n video2.id = 'video2';\n video2.autoplay = true;\n video2.controls = true;\n\n document.getElementById(\"vidcont_2\").appendChild(video2); \n slide6(); \n\n }, 30000);\n}\n\n//slide 7\nvar slide6 = function(){ \n move(); \n setTimeout(function(){ \n move();\n }, 30000);\n}\n\n&lt;/script&gt;\n\n&lt;style type=\"text/css\"&gt;\nbody {}\n#wrapper {width:707px; height:820px;overflow:;}\n#container {width:5000px;height:820px;}\n#video0 {width:707px; height:820px;float:left;}\n#video1 {width:707px;height:820px;float:left;background:##F93;}\n#video2 {width:707px;height:820px;float:left;background:#093;}\n#video3 {width:707px;height:820px;float:left;background:#F0F;}\n#article0 {float:left;width:707px;height:820px;background:#999;}\n#article1 {float:left;width:707px;height:820px;background:#f00;}\n#article2 {float:left;width:707px;height:820px;background:#06F;}\n#article3 {float:left;width:707px;height:820px;background:#06F;}\n&lt;/style&gt;\n\n&lt;/head&gt;\n\n&lt;body&gt;\n&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"container\"&gt;\n &lt;div id=\"article0\"&gt;Article 0&lt;/div&gt;\n &lt;div id=\"vidcont_0\"&gt;&lt;/div&gt; \n &lt;div id=\"article1\"&gt;Article 1&lt;/div&gt;\n &lt;div id=\"vidcont_1\"&gt;&lt;/div&gt; \n &lt;div id=\"article2\"&gt;Article 2&lt;/div&gt;\n &lt;div id=\"vidcont_2\"&gt;&lt;/div&gt; \n &lt;div id=\"article3\"&gt;Article 3&lt;/div&gt;\n &lt;/div&gt;&lt;!----end container---&gt; \n&lt;/div&gt; &lt;!----end wrapper---&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;\n</code></pre>\n\n<p><strong>Additional Note:</strong> I would also improve the <strong>comments</strong> to be more descriptive and helpful.</p>\n\n<ul>\n<li><code>&lt;!----end container---&gt;</code> is unnecessary if you have proper indentation</li>\n<li><code>//slide 5</code> right before <code>var slide4</code> is confusing</li>\n<li>If you keep HTML, CSS, and JavaScript in the same file I would comment each section as such.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:16:57.300", "Id": "43546", "Score": "0", "body": "Thank you really much for the suggestions. I have nicely separated the code formats in separate files. Now it is more clear and nice to have only HTML to work with in the index file." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:22:02.937", "Id": "27925", "ParentId": "27917", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T19:31:01.237", "Id": "27917", "Score": "1", "Tags": [ "javascript" ], "Title": "Video/article slider." }
27917
<p>I have a function that I intend to use for validating zip codes and I wanted to know if my way could be made better.</p> <pre><code>function zipcode (inputtxt) { var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/; if((inputtxt.value.match(zipcode)) { return true; } else { alert("message"); return false; } } </code></pre>
[]
[ { "body": "<p>Changes I would make: (but not necessary)</p>\n\n<ul>\n<li>Make sure <code>inputtext</code> has a value, and isn't undefined, so it wouldn't throw an error in your <code>if</code> statement.</li>\n<li>Replace the <code>if</code> statement with <code>return</code> instead. (This is mostly to minimize the code a bit, something your minifier won't do for you).</li>\n</ul>\n\n<p>Except for that, it seems ok (I'm not looking into the logic of the regex, since I'm not sure how a zipcode should be parsed).</p>\n\n<pre><code>function zipcode (inputtxt) \n{ \n\n if (!inputtxt || !inputtxt.value) return false;\n var zipcode = /^\\+?([0-9]{2})\\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/; \n\n return ((inputtxt.value.match(zipcode));\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:04:30.167", "Id": "27923", "ParentId": "27918", "Score": "3" } }, { "body": "<p>Um. There is verry little code, so one can not say much about your code. It does, what it should, I assume. </p>\n\n<p>One thing, I see is, that you are alerting a message, which has nothing to do with the validation. So if you are looking for <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a> - the separation of concerns, you take the alert out and put it elsewhere.</p>\n\n<p>Of course you could shrink the whole thing down to</p>\n\n<pre><code>function checkZipcode(zip) {\n if(!zip) throw new TypeError(\"zip is not defined\"); \n return /^\\+?([0-9]{2})\\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/.test(zip); \n}\n</code></pre>\n\n<p>done. But whether this is an improvement or not is open.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:13:43.650", "Id": "27924", "ParentId": "27918", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T19:32:50.280", "Id": "27918", "Score": "1", "Tags": [ "javascript", "form", "validation" ], "Title": "Form validation for zip codes" }
27918
<ol> <li><p>I am concerned about creating too many objects in my code. </p></li> <li><p>Am I using duplicate code? Can I cut down on the number of lines of code?</p></li> </ol> <p>Note: I only want to use recursion to solve this. Any suggestions on the design of the program and naming convention used here are appreciated.</p> <pre><code>import java.util.ArrayList; class Subsets { public static void main(String[] args) { ArrayList&lt;Integer&gt; superSet = new ArrayList&lt;Integer&gt;(); superSet.add(1); superSet.add(2); superSet.add(3); superSet.add(4); ArrayList&lt;ArrayList&lt;Integer&gt;&gt; lists = Subsets.getSubsets(superSet); System.out.println("final set ==&gt; " + lists); } static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; getSubsets(ArrayList&lt;Integer&gt; SubList) { if (SubList.size() &gt; 0) { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; list = addToList(SubList.remove(0), SubList); return list; } else { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; list = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(); list.add(SubList); return list; } } private static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; addToList( Integer firstElement, ArrayList&lt;Integer&gt; SubList) { ArrayList&lt;ArrayList&lt;Integer&gt;&gt; listOfLists = getSubsets(SubList); ArrayList&lt;ArrayList&lt;Integer&gt;&gt; superList = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(); for (ArrayList&lt;Integer&gt; iList : listOfLists) { superList.add(new ArrayList&lt;Integer&gt;(iList)); iList.add(firstElement); superList.add(new ArrayList&lt;Integer&gt;(iList)); } return superList; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T14:22:13.040", "Id": "43573", "Score": "0", "body": "You may try and operate on the original list's `.toArray()`: this way you will have no need to create sublists of your original list" } ]
[ { "body": "<p>My only input is about the <code>getSubsets()</code> method. I'd change it to:</p>\n\n<pre><code> static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; getSubsets(ArrayList&lt;Integer&gt; SubList) {\n ArrayList&lt;ArrayList&lt;Integer&gt;&gt; list; //You're gonna make a list either way.\n if (SubList.size() &gt; 0) {\n list = addToList(SubList.remove(0), SubList);\n } else {\n list = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();\n list.add(SubList);\n }\n return list;//You only need one return statement\n }\n</code></pre>\n\n<p>I generally don't like multiple return statements, because each one represents a path through which your method can just end abruptly, even if there's more code. But this <strong>is</strong> something up for debate (see <a href=\"https://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement\">this</a>). </p>\n\n<p>You also make a list object in both cases, so why not just make it upfront and make things more readable?</p>\n\n<p>Also, I would douse that code in comments. And finally, I'd probably just make my own class instead of dealing with that horrible syntax.</p>\n\n<p>This saves you from typos, too:</p>\n\n<pre><code>class ArrayListHolder extends ArrayList&lt;ArrayList&lt;Integer&gt;&gt;{\n //This can be an inner class. \n}\n\n //For example, your addToList method will look like:\n\nprivate static ArrayListHolder addToList(\n Integer firstElement, ArrayList&lt;Integer&gt; SubList) {\n ArrayListHolder listOfLists = getSubsets(SubList);\n ArrayListHolder superList = new ArrayListHolder();\n for (ArrayList&lt;Integer&gt; iList : listOfLists) {\n superList.add(new ArrayList&lt;Integer&gt;(iList));\n iList.add(firstElement);\n superList.add(new ArrayList&lt;Integer&gt;(iList));\n }\n return superList;\n}\n</code></pre>\n\n<p>That's just purely my opinion on what you should do. No real reason other than readability, and my hatred for the <code>ArrayList</code> syntax. Otherwise, good job.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T15:20:37.673", "Id": "27948", "ParentId": "27927", "Score": "1" } }, { "body": "<p>You can combine your two methods in just one method, making the whole process much easier to understand due to less \"jumping around\".</p>\n\n<pre><code>static &lt;T&gt; List&lt;List&lt;T&gt;&gt; getSublists(List&lt;T&gt; list) {\n if (list.isEmpty()) {\n // if empty, return just that empty list\n return Collections.singletonList(list);\n } else {\n List&lt;List&lt;T&gt;&gt; sublists = new ArrayList&lt;List&lt;T&gt;&gt;();\n T first = list.get(0);\n // for each sublist starting at second element...\n for (List&lt;T&gt; sublist : getSublists(list.subList(1, list.size()))) {\n //... add that sublist with and without the first element\n // (two lines more, but this preserves the original order)\n List&lt;T&gt; sublistWithFirst= new ArrayList&lt;T&gt;();\n sublistWithFirst.add(first);\n sublistWithFirst.addAll(sublist);\n sublists.add(sublist);\n sublists.add(sublistWithFirst);\n }\n return sublists;\n }\n}\n</code></pre>\n\n<p>Some more points:</p>\n\n<ul>\n<li>I'd recommend using the more generic <code>List</code> whenever possible.</li>\n<li>Also, no need to restrict the method to lists of integers.</li>\n<li>That code definitely deserves some comments.</li>\n<li>You are actually returning sub-<em>lists</em>; name your methods accordingly.</li>\n<li>Note that by calling <code>remove</code> on the input list, you are <em>modifying</em> the original list!</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T22:55:10.803", "Id": "27952", "ParentId": "27927", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:50:27.833", "Id": "27927", "Score": "1", "Tags": [ "java", "performance" ], "Title": "Printing out all the subsets of a set" }
27927
<p>I have seen this question asked a few times, but I do not entirely understand the solutions provided. Below is a bit of code I came up with for splitting up an arraylist into five parts. I have tested and changed the array size from 0 to 16 and it works fine.</p> <p>I am sure there is a "better" way of doing this, so I would like to see what others think.</p> <pre><code>public static void main(String[] args) { ArrayList&lt;String&gt; arrayList = new ArrayList&lt;String&gt;(); arrayList.add("A");//1 arrayList.add("B");//2 arrayList.add("C");//3 arrayList.add("D");//4 arrayList.add("E");//5 arrayList.add("F");//6 arrayList.add("G");//7 arrayList.add("H");//8 arrayList.add("I");//9 arrayList.add("J");//10 arrayList.add("K");//11 arrayList.add("L");//12 arrayList.add("M");//13 arrayList.add("N");//14 arrayList.add("O");//15 arrayList.add("P");//16 arrayList.add("X");//17 int i1 = (int) Math.ceil(arrayList.size()/5.0); List&lt;String&gt; sublist = new ArrayList&lt;String&gt;(); int x=0; for(int p=0; p&lt;i1; p++) { if(arrayList.size()&gt;=(x+5)) { sublist = new ArrayList&lt;String&gt;(arrayList.subList(x, x+5)); x+=5; } else sublist = new ArrayList&lt;String&gt;(arrayList.subList(x, arrayList.size())); for(String slist : sublist) { System.out.println("i:"+slist); } } } </code></pre>
[]
[ { "body": "<p>It seems like you are mixing up the number of segments and the number of elements per segment. In your example, both are the same, so the result is correct, but in other cases it will not be. For instance, <code>i1</code> is created as the number of elements per segment, with the number of segments being hard-coded as <code>5.0</code>. Then, in the loop, you treat <code>i1</code> as the number of segments, while the number of elements per segment is hard-coded as <code>5</code>. Mistakes like this will be easier to spot if you use properly named variables, like <code>numSegments</code> or <code>segmentSize</code> instead of <code>i1</code> or integer constants.</p>\n\n<p>Also:</p>\n\n<ul>\n<li>no need to wrap the sublists into <code>new ArrayList</code></li>\n<li>you can just count by increments according to the number of elements per sublist instead of using two counters, for the current sublist and the offset</li>\n<li>you could use a ternary <code>... ? ... : ...</code> instead of that <code>if/else</code></li>\n</ul>\n\n<p>How about this:</p>\n\n<pre><code>public static void main(String[] args) {\n List&lt;String&gt; arrayList = new ArrayList&lt;String&gt;();\n for (int i = 0; i &lt; 23; i++) {\n arrayList.add(String.valueOf(i));\n }\n\n int size = 5;\n for (int start = 0; start &lt; arrayList.size(); start += size) {\n int end = Math.min(start + size, arrayList.size());\n List&lt;String&gt; sublist = arrayList.subList(start, end);\n System.out.println(sublist);\n }\n}\n</code></pre>\n\n<p>Here, <code>size</code> is the number of elements in each sublist. So instead of counting the segment of the list and increasing a second counter by 5 each time, you can just increase the first counter by five in the third argument of the <code>for</code> loop. Also, you can use the result of <code>subList</code> directly, without passing it to a constructor first. And you can get rid of the <code>if-else</code> by using <code>min</code> to determine the end index.</p>\n\n<p>Output:</p>\n\n<pre><code>[0, 1, 2, 3, 4]\n[5, 6, 7, 8, 9]\n[10, 11, 12, 13, 14]\n[15, 16, 17, 18, 19]\n[20, 21, 22]\n</code></pre>\n\n<p>If instead of sublists with 5 elements you wanted five sublists, then use this (same result for the given example, but different for other list sizes):</p>\n\n<pre><code>int size = (int) Math.ceil(arrayList.size() / 5.0);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T11:51:29.390", "Id": "94362", "Score": "0", "body": "How to split array list in to equal parts of we dont know the chunk size (5 in your case) but we know the number of parts we want to make. e.g. how to split above 23 items in to 4 parts (dont know how many items should go to each part). My real use case is to split big file in to number of files" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T11:53:35.230", "Id": "94363", "Score": "0", "body": "@user1191081 Maybe I'm missing something, but you just divide? 23 items to 4 parts -> 23/4 == 5.something -> 6 parts, i.e. `ceil(numItems/numParts)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-05T07:46:18.750", "Id": "367234", "Score": "0", "body": "Why the simultaneous downvote to all three answers?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:18:37.040", "Id": "27930", "ParentId": "27928", "Score": "10" } }, { "body": "<p>You can use Java 8 <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-\" rel=\"nofollow noreferrer\"><code>Collectors.groupingBy(Function&lt;T,K&gt; classifier)</code></a> to do a list partitioning. What it does it simply divides an input list (e.g. <code>List&lt;String&gt;</code>) and divides it to a collection of n-size lists (e.g. <code>Collection&lt;List&lt;String&gt;&gt;</code>). Take a look at following code:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.stream.Collectors;\n\npublic class Partition {\n\n public static void main(String[] args) {\n final List&lt;String&gt; list = Arrays.asList(\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"X\");\n\n final AtomicInteger counter = new AtomicInteger(0);\n final int size = 5;\n\n final Collection&lt;List&lt;String&gt;&gt; partitioned = list.stream()\n .collect(Collectors.groupingBy(it -&gt; counter.getAndIncrement() / size))\n .values();\n\n partitioned.forEach(System.out::println);\n }\n}\n</code></pre>\n\n<p>We starts with <code>list</code> containing 17 elements. Our goal is to divide this list into lists of size 5 at maximum, no matter how many elements input list contains. What we do is we group all elements using a key computed as <code>counter / size</code>, so it generates a map like:</p>\n\n<pre><code>{0=[A,B,C,D,E], 1=[F,G,H,I,J], 2=[K,L,M,N,O], 3=[P,X]}\n</code></pre>\n\n<p>We are only interested in values of this map, so calling <code>Map.values()</code> method returns:</p>\n\n<pre><code>[[A,B,C,D,E], [F,G,H,I,J], [K,L,M,N,O], [P,X]]\n</code></pre>\n\n<p>And you can display these lists one by one with <code>partitioned.forEach(System.out::println)</code></p>\n\n<pre><code>[A, B, C, D, E]\n[F, G, H, I, J]\n[K, L, M, N, O]\n[P, X]\n</code></pre>\n\n<p>I hope it helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-15T10:31:20.480", "Id": "362612", "Score": "0", "body": "Neat. But is `Map.values()` guaranteed to return those in sorted order?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-17T20:25:07.203", "Id": "182991", "ParentId": "27928", "Score": "3" } } ]
{ "AcceptedAnswerId": "27930", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T19:34:53.060", "Id": "27928", "Score": "5", "Tags": [ "java" ], "Title": "Split Java ArrayList into equal parts" }
27928
<p>Okay, so I finally tackled <a href="http://projecteuler.net/problem=13" rel="nofollow">#13 from Project Euler</a>. I'm said to announce it took me almost 2 hours to come up with this solution, after about an hour of thinking on how to do it.</p> <p>Here's what I did:</p> <pre><code>private void Euler13() { // store 50 digit numbers into a 100 by 50 array int[,] superMegaInt = { {3,7,1,0,7,2,8,7,5,3,3,9,0,2,1,0,2,7,9,8,7,9,7,9,9,8,2,2,0,8,3,7,5,9,0,2,4,6,5,1,0,1,3,5,7,4,0,2,5,0}, {4,6,3,7,6,9,3,7,6,7,7,4,9,0,0,0,9,7,1,2,6,4,8,1,2,4,8,9,6,9,7,0,0,7,8,0,5,0,4,1,7,0,1,8,2,6,0,5,3,8}, {7,4,3,2,4,9,8,6,1,9,9,5,2,4,7,4,1,0,5,9,4,7,4,2,3,3,3,0,9,5,1,3,0,5,8,1,2,3,7,2,6,6,1,7,3,0,9,6,2,9}, {9,1,9,4,2,2,1,3,3,6,3,5,7,4,1,6,1,5,7,2,5,2,2,4,3,0,5,6,3,3,0,1,8,1,1,0,7,2,4,0,6,1,5,4,9,0,8,2,5,0}, {2,3,0,6,7,5,8,8,2,0,7,5,3,9,3,4,6,1,7,1,1,7,1,9,8,0,3,1,0,4,2,1,0,4,7,5,1,3,7,7,8,0,6,3,2,4,6,6,7,6}, {8,9,2,6,1,6,7,0,6,9,6,6,2,3,6,3,3,8,2,0,1,3,6,3,7,8,4,1,8,3,8,3,6,8,4,1,7,8,7,3,4,3,6,1,7,2,6,7,5,7}, {2,8,1,1,2,8,7,9,8,1,2,8,4,9,9,7,9,4,0,8,0,6,5,4,8,1,9,3,1,5,9,2,6,2,1,6,9,1,2,7,5,8,8,9,8,3,2,7,3,8}, {4,4,2,7,4,2,2,8,9,1,7,4,3,2,5,2,0,3,2,1,9,2,3,5,8,9,4,2,2,8,7,6,7,9,6,4,8,7,6,7,0,2,7,2,1,8,9,3,1,8}, {4,7,4,5,1,4,4,5,7,3,6,0,0,1,3,0,6,4,3,9,0,9,1,1,6,7,2,1,6,8,5,6,8,4,4,5,8,8,7,1,1,6,0,3,1,5,3,2,7,6}, {7,0,3,8,6,4,8,6,1,0,5,8,4,3,0,2,5,4,3,9,9,3,9,6,1,9,8,2,8,9,1,7,5,9,3,6,6,5,6,8,6,7,5,7,9,3,4,9,5,1}, {6,2,1,7,6,4,5,7,1,4,1,8,5,6,5,6,0,6,2,9,5,0,2,1,5,7,2,2,3,1,9,6,5,8,6,7,5,5,0,7,9,3,2,4,1,9,3,3,3,1}, {6,4,9,0,6,3,5,2,4,6,2,7,4,1,9,0,4,9,2,9,1,0,1,4,3,2,4,4,5,8,1,3,8,2,2,6,6,3,3,4,7,9,4,4,7,5,8,1,7,8}, {9,2,5,7,5,8,6,7,7,1,8,3,3,7,2,1,7,6,6,1,9,6,3,7,5,1,5,9,0,5,7,9,2,3,9,7,2,8,2,4,5,5,9,8,8,3,8,4,0,7}, {5,8,2,0,3,5,6,5,3,2,5,3,5,9,3,9,9,0,0,8,4,0,2,6,3,3,5,6,8,9,4,8,8,3,0,1,8,9,4,5,8,6,2,8,2,2,7,8,2,8}, {8,0,1,8,1,1,9,9,3,8,4,8,2,6,2,8,2,0,1,4,2,7,8,1,9,4,1,3,9,9,4,0,5,6,7,5,8,7,1,5,1,1,7,0,0,9,4,3,9,0}, {3,5,3,9,8,6,6,4,3,7,2,8,2,7,1,1,2,6,5,3,8,2,9,9,8,7,2,4,0,7,8,4,4,7,3,0,5,3,1,9,0,1,0,4,2,9,3,5,8,6}, {8,6,5,1,5,5,0,6,0,0,6,2,9,5,8,6,4,8,6,1,5,3,2,0,7,5,2,7,3,3,7,1,9,5,9,1,9,1,4,2,0,5,1,7,2,5,5,8,2,9}, {7,1,6,9,3,8,8,8,7,0,7,7,1,5,4,6,6,4,9,9,1,1,5,5,9,3,4,8,7,6,0,3,5,3,2,9,2,1,7,1,4,9,7,0,0,5,6,9,3,8}, {5,4,3,7,0,0,7,0,5,7,6,8,2,6,6,8,4,6,2,4,6,2,1,4,9,5,6,5,0,0,7,6,4,7,1,7,8,7,2,9,4,4,3,8,3,7,7,6,0,4}, {5,3,2,8,2,6,5,4,1,0,8,7,5,6,8,2,8,4,4,3,1,9,1,1,9,0,6,3,4,6,9,4,0,3,7,8,5,5,2,1,7,7,7,9,2,9,5,1,4,5}, {3,6,1,2,3,2,7,2,5,2,5,0,0,0,2,9,6,0,7,1,0,7,5,0,8,2,5,6,3,8,1,5,6,5,6,7,1,0,8,8,5,2,5,8,3,5,0,7,2,1}, {4,5,8,7,6,5,7,6,1,7,2,4,1,0,9,7,6,4,4,7,3,3,9,1,1,0,6,0,7,2,1,8,2,6,5,2,3,6,8,7,7,2,2,3,6,3,6,0,4,5}, {1,7,4,2,3,7,0,6,9,0,5,8,5,1,8,6,0,6,6,0,4,4,8,2,0,7,6,2,1,2,0,9,8,1,3,2,8,7,8,6,0,7,3,3,9,6,9,4,1,2}, {8,1,1,4,2,6,6,0,4,1,8,0,8,6,8,3,0,6,1,9,3,2,8,4,6,0,8,1,1,1,9,1,0,6,1,5,5,6,9,4,0,5,1,2,6,8,9,6,9,2}, {5,1,9,3,4,3,2,5,4,5,1,7,2,8,3,8,8,6,4,1,9,1,8,0,4,7,0,4,9,2,9,3,2,1,5,0,5,8,6,4,2,5,6,3,0,4,9,4,8,3}, {6,2,4,6,7,2,2,1,6,4,8,4,3,5,0,7,6,2,0,1,7,2,7,9,1,8,0,3,9,9,4,4,6,9,3,0,0,4,7,3,2,9,5,6,3,4,0,6,9,1}, {1,5,7,3,2,4,4,4,3,8,6,9,0,8,1,2,5,7,9,4,5,1,4,0,8,9,0,5,7,7,0,6,2,2,9,4,2,9,1,9,7,1,0,7,9,2,8,2,0,9}, {5,5,0,3,7,6,8,7,5,2,5,6,7,8,7,7,3,0,9,1,8,6,2,5,4,0,7,4,4,9,6,9,8,4,4,5,0,8,3,3,0,3,9,3,6,8,2,1,2,6}, {1,8,3,3,6,3,8,4,8,2,5,3,3,0,1,5,4,6,8,6,1,9,6,1,2,4,3,4,8,7,6,7,6,8,1,2,9,7,5,3,4,3,7,5,9,4,6,5,1,5}, {8,0,3,8,6,2,8,7,5,9,2,8,7,8,4,9,0,2,0,1,5,2,1,6,8,5,5,5,4,8,2,8,7,1,7,2,0,1,2,1,9,2,5,7,7,6,6,9,5,4}, {7,8,1,8,2,8,3,3,7,5,7,9,9,3,1,0,3,6,1,4,7,4,0,3,5,6,8,5,6,4,4,9,0,9,5,5,2,7,0,9,7,8,6,4,7,9,7,5,8,1}, {1,6,7,2,6,3,2,0,1,0,0,4,3,6,8,9,7,8,4,2,5,5,3,5,3,9,9,2,0,9,3,1,8,3,7,4,4,1,4,9,7,8,0,6,8,6,0,9,8,4}, {4,8,4,0,3,0,9,8,1,2,9,0,7,7,7,9,1,7,9,9,0,8,8,2,1,8,7,9,5,3,2,7,3,6,4,4,7,5,6,7,5,5,9,0,8,4,8,0,3,0}, {8,7,0,8,6,9,8,7,5,5,1,3,9,2,7,1,1,8,5,4,5,1,7,0,7,8,5,4,4,1,6,1,8,5,2,4,2,4,3,2,0,6,9,3,1,5,0,3,3,2}, {5,9,9,5,9,4,0,6,8,9,5,7,5,6,5,3,6,7,8,2,1,0,7,0,7,4,9,2,6,9,6,6,5,3,7,6,7,6,3,2,6,2,3,5,4,4,7,2,1,0}, {6,9,7,9,3,9,5,0,6,7,9,6,5,2,6,9,4,7,4,2,5,9,7,7,0,9,7,3,9,1,6,6,6,9,3,7,6,3,0,4,2,6,3,3,9,8,7,0,8,5}, {4,1,0,5,2,6,8,4,7,0,8,2,9,9,0,8,5,2,1,1,3,9,9,4,2,7,3,6,5,7,3,4,1,1,6,1,8,2,7,6,0,3,1,5,0,0,1,2,7,1}, {6,5,3,7,8,6,0,7,3,6,1,5,0,1,0,8,0,8,5,7,0,0,9,1,4,9,9,3,9,5,1,2,5,5,7,0,2,8,1,9,8,7,4,6,0,0,4,3,7,5}, {3,5,8,2,9,0,3,5,3,1,7,4,3,4,7,1,7,3,2,6,9,3,2,1,2,3,5,7,8,1,5,4,9,8,2,6,2,9,7,4,2,5,5,2,7,3,7,3,0,7}, {9,4,9,5,3,7,5,9,7,6,5,1,0,5,3,0,5,9,4,6,9,6,6,0,6,7,6,8,3,1,5,6,5,7,4,3,7,7,1,6,7,4,0,1,8,7,5,2,7,5}, {8,8,9,0,2,8,0,2,5,7,1,7,3,3,2,2,9,6,1,9,1,7,6,6,6,8,7,1,3,8,1,9,9,3,1,8,1,1,0,4,8,7,7,0,1,9,0,2,7,1}, {2,5,2,6,7,6,8,0,2,7,6,0,7,8,0,0,3,0,1,3,6,7,8,6,8,0,9,9,2,5,2,5,4,6,3,4,0,1,0,6,1,6,3,2,8,6,6,5,2,6}, {3,6,2,7,0,2,1,8,5,4,0,4,9,7,7,0,5,5,8,5,6,2,9,9,4,6,5,8,0,6,3,6,2,3,7,9,9,3,1,4,0,7,4,6,2,5,5,9,6,2}, {2,4,0,7,4,4,8,6,9,0,8,2,3,1,1,7,4,9,7,7,7,9,2,3,6,5,4,6,6,2,5,7,2,4,6,9,2,3,3,2,2,8,1,0,9,1,7,1,4,1}, {9,1,4,3,0,2,8,8,1,9,7,1,0,3,2,8,8,5,9,7,8,0,6,6,6,9,7,6,0,8,9,2,9,3,8,6,3,8,2,8,5,0,2,5,3,3,3,4,0,3}, {3,4,4,1,3,0,6,5,5,7,8,0,1,6,1,2,7,8,1,5,9,2,1,8,1,5,0,0,5,5,6,1,8,6,8,8,3,6,4,6,8,4,2,0,0,9,0,4,7,0}, {2,3,0,5,3,0,8,1,1,7,2,8,1,6,4,3,0,4,8,7,6,2,3,7,9,1,9,6,9,8,4,2,4,8,7,2,5,5,0,3,6,6,3,8,7,8,4,5,8,3}, {1,1,4,8,7,6,9,6,9,3,2,1,5,4,9,0,2,8,1,0,4,2,4,0,2,0,1,3,8,3,3,5,1,2,4,4,6,2,1,8,1,4,4,1,7,7,3,4,7,0}, {6,3,7,8,3,2,9,9,4,9,0,6,3,6,2,5,9,6,6,6,4,9,8,5,8,7,6,1,8,2,2,1,2,2,5,2,2,5,5,1,2,4,8,6,7,6,4,5,3,3}, {6,7,7,2,0,1,8,6,9,7,1,6,9,8,5,4,4,3,1,2,4,1,9,5,7,2,4,0,9,9,1,3,9,5,9,0,0,8,9,5,2,3,1,0,0,5,8,8,2,2}, {9,5,5,4,8,2,5,5,3,0,0,2,6,3,5,2,0,7,8,1,5,3,2,2,9,6,7,9,6,2,4,9,4,8,1,6,4,1,9,5,3,8,6,8,2,1,8,7,7,4}, {7,6,0,8,5,3,2,7,1,3,2,2,8,5,7,2,3,1,1,0,4,2,4,8,0,3,4,5,6,1,2,4,8,6,7,6,9,7,0,6,4,5,0,7,9,9,5,2,3,6}, {3,7,7,7,4,2,4,2,5,3,5,4,1,1,2,9,1,6,8,4,2,7,6,8,6,5,5,3,8,9,2,6,2,0,5,0,2,4,9,1,0,3,2,6,5,7,2,9,6,7}, {2,3,7,0,1,9,1,3,2,7,5,7,2,5,6,7,5,2,8,5,6,5,3,2,4,8,2,5,8,2,6,5,4,6,3,0,9,2,2,0,7,0,5,8,5,9,6,5,2,2}, {2,9,7,9,8,8,6,0,2,7,2,2,5,8,3,3,1,9,1,3,1,2,6,3,7,5,1,4,7,3,4,1,9,9,4,8,8,9,5,3,4,7,6,5,7,4,5,5,0,1}, {1,8,4,9,5,7,0,1,4,5,4,8,7,9,2,8,8,9,8,4,8,5,6,8,2,7,7,2,6,0,7,7,7,1,3,7,2,1,4,0,3,7,9,8,8,7,9,7,1,5}, {3,8,2,9,8,2,0,3,7,8,3,0,3,1,4,7,3,5,2,7,7,2,1,5,8,0,3,4,8,1,4,4,5,1,3,4,9,1,3,7,3,2,2,6,6,5,1,3,8,1}, {3,4,8,2,9,5,4,3,8,2,9,1,9,9,9,1,8,1,8,0,2,7,8,9,1,6,5,2,2,4,3,1,0,2,7,3,9,2,2,5,1,1,2,2,8,6,9,5,3,9}, {4,0,9,5,7,9,5,3,0,6,6,4,0,5,2,3,2,6,3,2,5,3,8,0,4,4,1,0,0,0,5,9,6,5,4,9,3,9,1,5,9,8,7,9,5,9,3,6,3,5}, {2,9,7,4,6,1,5,2,1,8,5,5,0,2,3,7,1,3,0,7,6,4,2,2,5,5,1,2,1,1,8,3,6,9,3,8,0,3,5,8,0,3,8,8,5,8,4,9,0,3}, {4,1,6,9,8,1,1,6,2,2,2,0,7,2,9,7,7,1,8,6,1,5,8,2,3,6,6,7,8,4,2,4,6,8,9,1,5,7,9,9,3,5,3,2,9,6,1,9,2,2}, {6,2,4,6,7,9,5,7,1,9,4,4,0,1,2,6,9,0,4,3,8,7,7,1,0,7,2,7,5,0,4,8,1,0,2,3,9,0,8,9,5,5,2,3,5,9,7,4,5,7}, {2,3,1,8,9,7,0,6,7,7,2,5,4,7,9,1,5,0,6,1,5,0,5,5,0,4,9,5,3,9,2,2,9,7,9,5,3,0,9,0,1,1,2,9,9,6,7,5,1,9}, {8,6,1,8,8,0,8,8,2,2,5,8,7,5,3,1,4,5,2,9,5,8,4,0,9,9,2,5,1,2,0,3,8,2,9,0,0,9,4,0,7,7,7,0,7,7,5,6,7,2}, {1,1,3,0,6,7,3,9,7,0,8,3,0,4,7,2,4,4,8,3,8,1,6,5,3,3,8,7,3,5,0,2,3,4,0,8,4,5,6,4,7,0,5,8,0,7,7,3,0,8}, {8,2,9,5,9,1,7,4,7,6,7,1,4,0,3,6,3,1,9,8,0,0,8,1,8,7,1,2,9,0,1,1,8,7,5,4,9,1,3,1,0,5,4,7,1,2,6,5,8,1}, {9,7,6,2,3,3,3,1,0,4,4,8,1,8,3,8,6,2,6,9,5,1,5,4,5,6,3,3,4,9,2,6,3,6,6,5,7,2,8,9,7,5,6,3,4,0,0,5,0,0}, {4,2,8,4,6,2,8,0,1,8,3,5,1,7,0,7,0,5,2,7,8,3,1,8,3,9,4,2,5,8,8,2,1,4,5,5,2,1,2,2,7,2,5,1,2,5,0,3,2,7}, {5,5,1,2,1,6,0,3,5,4,6,9,8,1,2,0,0,5,8,1,7,6,2,1,6,5,2,1,2,8,2,7,6,5,2,7,5,1,6,9,1,2,9,6,8,9,7,7,8,9}, {3,2,2,3,8,1,9,5,7,3,4,3,2,9,3,3,9,9,4,6,4,3,7,5,0,1,9,0,7,8,3,6,9,4,5,7,6,5,8,8,3,3,5,2,3,9,9,8,8,6}, {7,5,5,0,6,1,6,4,9,6,5,1,8,4,7,7,5,1,8,0,7,3,8,1,6,8,8,3,7,8,6,1,0,9,1,5,2,7,3,5,7,9,2,9,7,0,1,3,3,7}, {6,2,1,7,7,8,4,2,7,5,2,1,9,2,6,2,3,4,0,1,9,4,2,3,9,9,6,3,9,1,6,8,0,4,4,9,8,3,9,9,3,1,7,3,3,1,2,7,3,1}, {3,2,9,2,4,1,8,5,7,0,7,1,4,7,3,4,9,5,6,6,9,1,6,6,7,4,6,8,7,6,3,4,6,6,0,9,1,5,0,3,5,9,1,4,6,7,7,5,0,4}, {9,9,5,1,8,6,7,1,4,3,0,2,3,5,2,1,9,6,2,8,8,9,4,8,9,0,1,0,2,4,2,3,3,2,5,1,1,6,9,1,3,6,1,9,6,2,6,6,2,2}, {7,3,2,6,7,4,6,0,8,0,0,5,9,1,5,4,7,4,7,1,8,3,0,7,9,8,3,9,2,8,6,8,5,3,5,2,0,6,9,4,6,9,4,4,5,4,0,7,2,4}, {7,6,8,4,1,8,2,2,5,2,4,6,7,4,4,1,7,1,6,1,5,1,4,0,3,6,4,2,7,9,8,2,2,7,3,3,4,8,0,5,5,5,5,6,2,1,4,8,1,8}, {9,7,1,4,2,6,1,7,9,1,0,3,4,2,5,9,8,6,4,7,2,0,4,5,1,6,8,9,3,9,8,9,4,2,2,1,7,9,8,2,6,0,8,8,0,7,6,8,5,2}, {8,7,7,8,3,6,4,6,1,8,2,7,9,9,3,4,6,3,1,3,7,6,7,7,5,4,3,0,7,8,0,9,3,6,3,3,3,3,0,1,8,9,8,2,6,4,2,0,9,0}, {1,0,8,4,8,8,0,2,5,2,1,6,7,4,6,7,0,8,8,3,2,1,5,1,2,0,1,8,5,8,8,3,5,4,3,2,2,3,8,1,2,8,7,6,9,5,2,7,8,6}, {7,1,3,2,9,6,1,2,4,7,4,7,8,2,4,6,4,5,3,8,6,3,6,9,9,3,0,0,9,0,4,9,3,1,0,3,6,3,6,1,9,7,6,3,8,7,8,0,3,9}, {6,2,1,8,4,0,7,3,5,7,2,3,9,9,7,9,4,2,2,3,4,0,6,2,3,5,3,9,3,8,0,8,3,3,9,6,5,1,3,2,7,4,0,8,0,1,1,1,1,6}, {6,6,6,2,7,8,9,1,9,8,1,4,8,8,0,8,7,7,9,7,9,4,1,8,7,6,8,7,6,1,4,4,2,3,0,0,3,0,9,8,4,4,9,0,8,5,1,4,1,1}, {6,0,6,6,1,8,2,6,2,9,3,6,8,2,8,3,6,7,6,4,7,4,4,7,7,9,2,3,9,1,8,0,3,3,5,1,1,0,9,8,9,0,6,9,7,9,0,7,1,4}, {8,5,7,8,6,9,4,4,0,8,9,5,5,2,9,9,0,6,5,3,6,4,0,4,4,7,4,2,5,5,7,6,0,8,3,6,5,9,9,7,6,6,4,5,7,9,5,0,9,6}, {6,6,0,2,4,3,9,6,4,0,9,9,0,5,3,8,9,6,0,7,1,2,0,1,9,8,2,1,9,9,7,6,0,4,7,5,9,9,4,9,0,1,9,7,2,3,0,2,9,7}, {6,4,9,1,3,9,8,2,6,8,0,0,3,2,9,7,3,1,5,6,0,3,7,1,2,0,0,4,1,3,7,7,9,0,3,7,8,5,5,6,6,0,8,5,0,8,9,2,5,2}, {1,6,7,3,0,9,3,9,3,1,9,8,7,2,7,5,0,2,7,5,4,6,8,9,0,6,9,0,3,7,0,7,5,3,9,4,1,3,0,4,2,6,5,2,3,1,5,0,1,1}, {9,4,8,0,9,3,7,7,2,4,5,0,4,8,7,9,5,1,5,0,9,5,4,1,0,0,9,2,1,6,4,5,8,6,3,7,5,4,7,1,0,5,9,8,4,3,6,7,9,1}, {7,8,6,3,9,1,6,7,0,2,1,1,8,7,4,9,2,4,3,1,9,9,5,7,0,0,6,4,1,9,1,7,9,6,9,7,7,7,5,9,9,0,2,8,3,0,0,6,9,9}, {1,5,3,6,8,7,1,3,7,1,1,9,3,6,6,1,4,9,5,2,8,1,1,3,0,5,8,7,6,3,8,0,2,7,8,4,1,0,7,5,4,4,4,9,7,3,3,0,7,8}, {4,0,7,8,9,9,2,3,1,1,5,5,3,5,5,6,2,5,6,1,1,4,2,3,2,2,4,2,3,2,5,5,0,3,3,6,8,5,4,4,2,4,8,8,9,1,7,3,5,3}, {4,4,8,8,9,9,1,1,5,0,1,4,4,0,6,4,8,0,2,0,3,6,9,0,6,8,0,6,3,9,6,0,6,7,2,3,2,2,1,9,3,2,0,4,1,4,9,5,3,5}, {4,1,5,0,3,1,2,8,8,8,0,3,3,9,5,3,6,0,5,3,2,9,9,3,4,0,3,6,8,0,0,6,9,7,7,7,1,0,6,5,0,5,6,6,6,3,1,9,5,4}, {8,1,2,3,4,8,8,0,6,7,3,2,1,0,1,4,6,7,3,9,0,5,8,5,6,8,5,5,7,9,3,4,5,8,1,4,0,3,6,2,7,8,2,2,7,0,3,2,8,0}, {8,2,6,1,6,5,7,0,7,7,3,9,4,8,3,2,7,5,9,2,2,3,2,8,4,5,9,4,1,7,0,6,5,2,5,0,9,4,5,1,2,3,2,5,2,3,0,6,0,8}, {2,2,9,1,8,8,0,2,0,5,8,7,7,7,3,1,9,7,1,9,8,3,9,4,5,0,1,8,0,8,8,8,0,7,2,4,2,9,6,6,1,9,8,0,8,1,1,1,9,7}, {7,7,1,5,8,5,4,2,5,0,2,0,1,6,5,4,5,0,9,0,4,1,3,2,4,5,8,0,9,7,8,6,8,8,2,7,7,8,9,4,8,7,2,1,8,5,9,6,1,7}, {7,2,1,0,7,8,3,8,4,3,5,0,6,9,1,8,6,1,5,5,4,3,5,6,6,2,8,8,4,0,6,2,2,5,7,4,7,3,6,9,2,2,8,4,5,0,9,5,1,6}, {2,0,8,4,9,6,0,3,9,8,0,1,3,4,0,0,1,7,2,3,9,3,0,6,7,1,6,6,6,8,2,3,5,5,5,2,4,5,2,5,2,8,0,4,6,0,9,7,2,2}, {5,3,5,0,3,5,3,4,2,2,6,4,7,2,5,2,4,2,5,0,8,7,4,0,5,4,0,7,5,5,9,1,7,8,9,7,8,1,2,6,4,3,3,0,3,3,1,6,9,0} }; label1.Text = AddTheInts(superMegaInt); } private string AddTheInts(int[,] ints) { var result = ""; var total = 0; // the idea is to loop through the last element of each array, and add them together, carry the reminder on to the next to the last. repeat till done for(var j = 49; j &gt;= 0; j--) { for (var i = 0; i &lt; 100; i++) { total += ints[i,j]; } if (j == 0) { result = total.ToString() + result; } else { result = (total % 10).ToString() + result; total = total - (total % 10); total /= 10; } } return result.Substring(0,10); } </code></pre> <p>Now, this works, and I got the correct answer. But I'm 1000% certain there has to be a better way of doing this. And I feel that even if this hadn't taken me 2 hours, if I'd have done this on an interview test, I'd have been laughed at. So, how else should I have accomplished this? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:40:54.903", "Id": "43547", "Score": "0", "body": "http://weblogs.asp.net/psteele/archive/2008/12/19/project-euler-13.aspx or maybe http://www.geekality.net/2009/10/04/project-euler-problem-13/ or even http://www.mathblog.dk/project-euler-13/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T23:27:30.810", "Id": "43549", "Score": "2", "body": "i hope you didn't write down those arrays manually" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T03:36:54.397", "Id": "43559", "Score": "0", "body": "@JustinL. Not completely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T07:58:19.760", "Id": "43568", "Score": "0", "body": "The best refactoring here is to take another language: `str.scan(/\\d{50}/).map(&:to_i).inject(:+).to_s[0...10]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-07T18:41:35.337", "Id": "119172", "Score": "0", "body": "If you have already saved the problem you can create an account at projec euler and submit your solution. Then you are authorized to view the thread for this problem in the restricted project euler forum (the links can be found at tje bottom of the problem 13, but only if you have submitted a valid solution) You acn check the solutions of the other users. Especially the second pos of user rayfil may be interresting if you want to improve your solution: https://projecteuler.net/thread=13" } ]
[ { "body": "<ol>\n<li>Don't hard code the input. Instead, make your program read and parse a text file containing the input, or something like that.</li>\n<li>If you can use <code>BigInteger</code> to represent the numbers, use it. If you think that would be cheating, write your own <code>BigInteger</code> that supports <code>Parse()</code>, <code>ToString()</code> and <code>+</code>.</li>\n<li>You can then use LINQ to sum the numbers. <code>Sum()</code> doesn't work for <code>BigInteger</code>s, but you can use <code>Aggregate()</code>.</li>\n</ol>\n\n<p>With that, your code would look something like this:</p>\n\n<pre><code>string result =\n File.ReadAllLines(\"euler13.txt\")\n .Select(BigInteger.Parse)\n .Aggregate((i1, i2) =&gt; i1 + i2)\n .ToString()\n .Substring(0, 10);\n</code></pre>\n\n<p>This is basically the same code as the one from Nakilon's comment, only in a language that supports names with more than 4 characters :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T12:47:01.047", "Id": "27945", "ParentId": "27931", "Score": "5" } } ]
{ "AcceptedAnswerId": "27945", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T21:23:26.513", "Id": "27931", "Score": "4", "Tags": [ "c#", "project-euler", "programming-challenge" ], "Title": "Project Euler #13 efficiency" }
27931
<p>Are there any potential issues with the following Javascript code:</p> <pre><code>var BobsGarage = BobsGarage || {}; // namespace /** * BobsGarage.Car * @constructor * @returns {BobsGarage.Car} */ BobsGarage.Car = function() { /** * Engine * @constructor * @returns {Engine} */ var Engine = function() { // definition of an engine }; Engine.prototype.constructor = Engine; Engine.prototype.start = function() { console.log('start engine'); }; /** * Tank * @constructor * @returns {Tank} */ var Tank = function() { // definition of a tank }; Tank.prototype.constructor = Tank; Tank.prototype.fill = function() { console.log('fill tank'); }; this.engine = new Engine(); this.tank = new Tank(); }; BobsGarage.Car.prototype.constructor = BobsGarage.Car; /** * BobsGarage.Ferrari * Derived from BobsGarage.Car * @constructor * @returns {BobsGarage.Ferrari} */ BobsGarage.Ferrari = function() { BobsGarage.Car.call(this); }; BobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype); BobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari; BobsGarage.Ferrari.prototype.speedUp = function() { console.log('speed up'); }; // Test it on the road var car = new BobsGarage.Car(); car.tank.fill(); car.engine.start(); var ferrari = new BobsGarage.Ferrari(); ferrari.tank.fill(); ferrari.engine.start(); ferrari.speedUp(); // var engine = new Engine(); // ReferenceError console.log(ferrari); </code></pre> <p>The goal is to have prototype inheritance and nested classes so that classes defined within <code>BobsGarage.Car</code> are not accessible outside the constructor of <code>BobsGarage.Car</code> but instances of them are accessible to derived classes, as shown in the test code.</p> <p>Note: I am referring to the concept of <em>Class</em> in Javascript as defined on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript" rel="nofollow">MDN</a>.</p>
[]
[ { "body": "<p>I don't see any issues with your code.</p>\n\n<p>One suggestion would be to make your code a little DRYer by assigning to your prototype in 1 go and drop the jsdoc ( it adds a lot of lines, for little value ).</p>\n\n<pre><code>//Definition of an engine\nvar Engine = function() {};\n\nEngine.prototype = {\n constructor : Engine,\n start : function() {\n console.log('start engine');\n }\n};\n</code></pre>\n\n<p>Instead of </p>\n\n<pre><code>/**\n * Engine\n * @constructor\n * @returns {Engine}\n */\nvar Engine = function() {\n // definition of an engine\n};\n\nEngine.prototype.constructor = Engine;\nEngine.prototype.start = function() {\n console.log('start engine');\n};\n</code></pre>\n\n<p>Creating <code>ferrari</code> out of <code>car</code> is even more verbose, I would suggest 2 helper functions to keep the code more readable.</p>\n\n<pre><code>BobsGarage.Ferrari.prototype = {\n constructor : BobsGarage.Ferrari,\n speedUp : function() {\n console.log('speed up');\n },\n}\n\nextendPrototype( BobsGarage.Car , BobsGarage.Ferrari );\n\nfunction extendPrototype( base , extension )\n{\n extension.prototype = extend( base.prototype , extension.prototype );\n}\n\nfunction extend( o , extension )\n{\n for( var key in extension )\n o[key] = extension[key];\n return o;\n}\n</code></pre>\n\n<p>Obviously you would keep re-using <code>extend</code> and <code>extendPrototype</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T10:54:39.960", "Id": "64319", "Score": "1", "body": "Vary good suggestion, thanks. The only thing I think needs to be changed is the implementation of `extendPrototype`. The way it is implemented now also extends the base prototype, effectively assigning all extension properties to the base prototype. This can be avoided creating a new temporary object from the base prototype like this: `var klass = function() {}; klass.prototype = new base(); extension.prototype = extend(klass.prototype, extension.prototype);`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T15:10:06.257", "Id": "64349", "Score": "0", "body": "You are right, not sure how that got past my test ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T21:59:44.153", "Id": "37700", "ParentId": "27932", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T23:39:08.840", "Id": "27932", "Score": "2", "Tags": [ "javascript", "object-oriented", "inheritance" ], "Title": "Javascript Nested Classes" }
27932
<p>I basically have a couple of clients built with C#, using System.Net.Sockets TCP connections connecting to a node server backend.</p> <p>I've looked at tons of examples and everyone seems to receive data in a different way. I copied methods I liked and thought would work for me and put together this method.</p> <p>This is the method I use for receiving ALL data from the server. Is this method acceptable? Is there anything I can do better here?</p> <p><strong>ReceiveData Method</strong></p> <pre><code>/// &lt;summary&gt; /// This should be started in it's own thread as it blocks like crazy /// This will keep running while the socket is connected, waiting for /// data to arrive and then handle it (via calling the action you pass) /// &lt;/summary&gt; /// &lt;param name="tcpNetwork"&gt;the tcp connection which contains the open socket and stream reader&lt;/param&gt; /// &lt;param name="handleFunction"&gt;Action in which you want to run to handle your packets received&lt;/param&gt; public static void ReceiveData(TcpNetwork tcpNetwork, Action&lt;Packet&gt; handleFunction) { //grab the streamReader from the tcp object var streamReader = tcpNetwork.GetStreamReader(); //while the socket is still connected while (tcpNetwork.Connected) { try { //Create a new header object which is a static size //(Set Via TcpNetwork) //the server will always send a header packet before any //other packet var header = new char[TcpNetwork.HeaderLength]; //attempt to read the header, this will find data, or //throw an IOException when we timeout (if no data is being sent) //in which case we just hide it and start looking for more data TcpNetwork.ReadWholeArray(streamReader, header); //if we got this far that means we have a header packet (in json form) //convert it to our HeaderPacket object so we can determine the length of the //content packet var headerPacket = JsonConvert.DeserializeObject&lt;HeaderPacket&gt;(new string(header)); //create a new char array for our content packet using the size that was sent //with our header packet var contentPacket = new char[headerPacket.Length]; //attempt to read the whole contentPacket, we will keep reading until we get the right amount of data //or we reach the end of the stream in which case we'll throw an exception cause something bad happened TcpNetwork.ReadWholeArray(streamReader, contentPacket); //convert our character array to a string var json = new string(contentPacket); //make sure the string is json if (Packet.IsJson(json)) { //convert it from json to our packet object var packet = Packet.ConvertFromServerPacket(json); //call the action we passed in to handle all the packets handleFunction(packet); } else { throw new FormatException("Received non-json response from server"); } } catch (IOException ioException) { //natural timeout if we don't receive any messages //keep chugging } catch (ThreadAbortException abortingExcetion) { // -- let it abort } catch (Exception x) { throw x; } } } </code></pre> <p>Relevant parts of <strong>TcpNetwork.cs</strong></p> <pre><code>/// &lt;summary&gt; /// Reads data into a complete array, throwing an EndOfStreamException /// if the stream runs out of data first, or if an IOException /// naturally occurs. /// &lt;/summary&gt; /// &lt;param name="reader"&gt;The stream to read data from&lt;/param&gt; /// &lt;param name="data"&gt;The array to read bytes into. The array /// will be completely filled from the stream, so an appropriate /// size must be given.&lt;/param&gt; public static void ReadWholeArray(StreamReader reader, char[] data) { var offset = 0; var remaining = data.Length; while (remaining &gt; 0) { var read = reader.Read(data, offset, remaining); if (read &lt;= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; } } /// &lt;summary&gt; /// Gets a StreamReader which can be used to read from the connected socket /// &lt;/summary&gt; /// &lt;returns&gt;StreamReader of a network stream&lt;/returns&gt; public StreamReader GetStreamReader() { if (_tcpClient == null) return null; return _streamReader ?? (_streamReader = new StreamReader(_tcpClient.GetStream())); } </code></pre> <p><strong>HeaderPacket.cs</strong></p> <pre><code>public class HeaderPacket { public int Length { get; set; } } </code></pre> <p><strong>Clarifications</strong></p> <ul> <li><code>TcpNetwork</code> is a wrapper class around <code>System.Net.Sockets.TcpClient</code></li> <li>Server is node.js so sending JSON across the wire seemed reasonable. I'm not sure if that's something I should be doing or not.</li> <li>Using Json.net to convert between my POCOs and JSON objects</li> </ul>
[]
[ { "body": "<p>Just one minor issue: You shouldn't rethrow an exception with <code>throw ex;</code>, because this messes up the stack trace. It is recommended to use just <code>throw;</code> instead.</p>\n\n<p>Out of personal preference I wouldn't write that much of comments, actually. Sure, it looks nice, but you are explaining twice what <code>ReadWholeArray</code> does. I think the name is chosen well enough to give an idea what the method does, and for details you have the documentation at the definition of the method (e.g. shown via IntelliSense). Comments shouldn't explain <em>how exactly</em> you are doing something, they should tell the reader <em>what</em> you are doing, and <em>why</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T14:00:39.567", "Id": "43572", "Score": "0", "body": "thanks for pointing that out about the throw. As far as the comments, yeah, i never really comment things that much, but when building it i kept forgetting what things are and how they worked, so i kinda just added them so I could walk through what was happening, but good point" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T13:54:40.803", "Id": "27947", "ParentId": "27946", "Score": "2" } } ]
{ "AcceptedAnswerId": "27947", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T13:24:15.147", "Id": "27946", "Score": "1", "Tags": [ "c#", "networking", "tcp", "json.net" ], "Title": "Receiving data from a network stream" }
27946
<p>The function is entered by the user as a series of coefficients and powers in the form of numerators and denominators. There is a little error somewhere with negative numbers that I'm working on finding. Other than that, I just want to know about the coding style.</p> <p><strong>Class Integration</strong></p> <pre><code>package calculus; import java.util.Scanner; public class Integration { //create various fields to decide the integration method to be used RationalNumbers coeffFraction; RationalNumbers powerFraction; private final int DIRECT = 1; private final int SUBSTITUTION = 2; //private final int TRIGONOMETRIC = 3; //private final int INTEGRATION_BY_PARTS = 4; //private final int LOGARITHMIC = 5; //create fields to store various variables needed during the integration process private double[] coeffX; private double[] powers; private int numberOfVariables; //fields to select integration method private int integrationMethod; private Scanner select; //constructor /**a constructor that prompts the user to select a number that denotes a certain * integration type and matches it to a consequent method that implements the type * of integration that has been selected */ public Integration() { select = new Scanner(System.in); System.out.println("Enter the number denoting the method you want to execute"); System.out.println("1. Direct Integration \n" + "2. Integration by substitution \n" + "3. Integration of trigonometric functions \n" + "4. Integration by parts \n" + "5. Integration of Logarithmic functions \n"); //get input System.out.print("SELECT: "); integrationMethod = select.nextInt(); switch(integrationMethod) { case DIRECT: directIntegration(); break; case SUBSTITUTION: substitutionIntegration(); break; default: System.out.println("Sorry that method is yet to be defined"); } } /** this method is for integrating simple functions directly. * */ public void directIntegration() { select = new Scanner(System.in); System.out.println("Direct Integration Selected\n" + "f(x) = Axa + Bxb + Cxc + Dxd + ... + Nxn"); System.out.println("\nEnter the number of variables in your function: "); numberOfVariables = select.nextInt(); //initialize necessary arrays to hold all the variable coefficients and powers coeffX = new double[numberOfVariables]; powers = new double[numberOfVariables]; //initialize the first prompts as 'A' and 'a' char coPrompt = 'A'; char powPrompt = 'a'; System.out.println("Enter the coefficients and powers"); //control input coefficients System.out.println("COEFFICIENTS"); for(int counter=0; counter&lt;coeffX.length; counter++, coPrompt++) { int numerator; int denominator; System.out.print(coPrompt + ": \n" + "\tnumerator = "); numerator = select.nextInt(); System.out.print("\tdenominator = "); denominator = select.nextInt(); double coefficient = (double)numerator / denominator; coeffX[counter] = coefficient; } //control input powers System.out.println("POWERS"); for(int counter=0; counter&lt;powers.length; counter++, powPrompt++) { int numerator; int denominator; System.out.print(powPrompt + ": \n" + "\tnumerator = "); numerator = select.nextInt(); System.out.print("\tdenominator = "); denominator = select.nextInt(); double power = (double)numerator / denominator; powers[counter] = power; } //new powers and coefficients after integration System.out.print("\nIntegrating ... \n F(x) = "); for(int counter = 0; counter&lt;powers.length &amp;&amp; counter&lt;coeffX.length; counter++) { powers[counter] = powers[counter] + 1; coeffX[counter] = coeffX[counter] / powers[counter]; powerFraction = new RationalNumbers(powers[counter]); coeffFraction = new RationalNumbers(coeffX[counter]); //code to output if (counter == (coeffX.length - 1) &amp;&amp; counter == (powers.length - 1)) { System.out.print(coeffFraction.rationalize() + "x" + powerFraction.rationalize()); } else { System.out.print(coeffFraction.rationalize() + "x" + powerFraction.rationalize() + " + "); } } } /** this method utilizes substitution to integrate functions. * */ public void substitutionIntegration() { System.out.println("You have selected substitution integration lakini \nbado sijaitengeneza"); } } </code></pre> <p><strong>Class RationalNumbers</strong></p> <pre><code>package calculus; import helper.GreatestCommonDivisor; public class RationalNumbers { GreatestCommonDivisor helper; private String stringValue; private double decimalValue; private int numerator; private int denominator; private boolean recurring = false; public RationalNumbers(double value) { decimalValue = value; stringValue = String.valueOf(Math.abs(decimalValue)); checkRecurrence(); } //ADDITIONAL CODE //method to check whether the value passed is recurring or not public void checkRecurrence() { if(stringValue.length() &gt; 4) { if(stringValue.charAt(3) == stringValue.charAt(4)) { recurring = true; } } } public void ratios() { int countDecimalPlaces = 0; //code to extract recurring numbers and add their behavior if(recurring) { int firstValue = (int)(100 * decimalValue); int secondValue = (int)(1000 * decimalValue); denominator = 900; numerator = secondValue - firstValue; } else { for(int counter = 2; counter&lt;stringValue.length(); counter++) { countDecimalPlaces++; } denominator = (int)(Math.pow(10, countDecimalPlaces)); if(decimalValue &gt;= 1) //setting of numerator for improper fractions { numerator = (int)(decimalValue * denominator); } else { numerator = Integer.parseInt(stringValue.substring(2)); } } } public String rationalize() { int[] rations = new int[2]; String fraction; ratios(); helper = new GreatestCommonDivisor(numerator, denominator); if(decimalValue&lt;0) //cater for decimal numbers inputed { rations[0] = (numerator / helper.gcd()) * (-1); } else { rations[0] = numerator / helper.gcd(); } rations[1] = denominator / helper.gcd(); if(rations[1] == 1) { fraction = String.valueOf(rations[0]); } else { fraction = (rations[0] + "/" + rations[1]); } return fraction; } } </code></pre> <p><strong>Class GreatestCommonDivisor</strong></p> <pre><code>package helper; /**This class has a constructor that accepts two values and * then implements the gcd() method to find the greatest common * divisor of the values*/ public class GreatestCommonDivisor { private int numerator; private int denominator; private int gcd = 1; public GreatestCommonDivisor(int value1, int value2) { numerator = value1; denominator = value2; } public int gcd() { int dividend = 2; //check here for the problem when you are freshazamiz while(dividend &lt;= Math.min(numerator, denominator)) { while(numerator % dividend == 0 &amp;&amp; denominator % dividend == 0) { numerator = numerator / dividend; denominator = denominator / dividend; gcd = gcd * dividend; } dividend++; } return gcd; } } </code></pre>
[]
[ { "body": "<p>Why do you have commented out code? If you do need it please throw it away. Leaving it commented out does not help.</p>\n\n<p>I'd also replace all these constants with an <code>Enum</code> to improve readability and maintainability of the code. With the <code>Enum</code> you can also rely on the compiler to check that you use a valid value.</p>\n\n<pre><code>private final int DIRECT = 1;\nprivate final int SUBSTITUTION = 2;\nprivate final int TRIGONOMETRIC = 3;\nprivate final int INTEGRATION_BY_PARTS = 4;\nprivate final int LOGARITHMIC = 5;\n</code></pre>\n\n<p>In order to have a more object oriented solution, I'd replace the <code>switch</code> that you use to choose the integration method with <a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"nofollow\">polymorphism</a> or with a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a>.</p>\n\n<p>I'd also avoid mixing methods that handle input/output and methods that does the computation of the result. Consider having I/O in a separate class that the one actually doing the integration.</p>\n\n<p>Is your <code>RationalNumbers</code> class representing a single number or a set of number? If it has to represent a single number please call it <code>RationalNumber</code>.</p>\n\n<p>I'd introduce a <code>Fraction</code> data type and use it to introduce the output of the <code>rationalize</code> method. Why should it return a <code>String</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T18:46:08.670", "Id": "43580", "Score": "0", "body": "Fraction data type? I do not think i am familiar with that. i will rectify the code appropriately however I just want to point out that for proper output, I needed to the rationalize method to return a string rather than an array(because it has to return 2 values)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T18:48:34.637", "Id": "43581", "Score": "0", "body": "I was suggesting you to create a new `Fraction` class to represent mathematical fractions. It should have two attributes (The numerator and the dividend) and it should solve cleanly the issue you have returning two values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T18:53:05.710", "Id": "43582", "Score": "0", "body": "Thank you. Polymorphism vs switch, I/O vs Computation, Naming Conventions & style (I cant beleive I missed this) and Fraction class. Thank you Mario for your pointers and help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T06:48:19.363", "Id": "43626", "Score": "0", "body": "@mariosangiorgio No need for a `Fraction` type. `RationalNumber` is OP's fraction type. `rationalize` is just a bad name for `toString`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T18:41:13.407", "Id": "27950", "ParentId": "27949", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T18:23:54.843", "Id": "27949", "Score": "1", "Tags": [ "java" ], "Title": "Critiques for program that integrates functions" }
27949
<p>In my project (which is a discussion system) there are approved and unapproved comments. There's a class that tells if unapproved comments should be shown. But I cannot think of a good name for this class. Right now it's named <code>ShowUnapproved</code> but doesn't that sound like a <code>Boolean</code>? (Rather than a configuration setting.)</p> <p><strong>Is the name <code>ShowUnapproved</code> clear to you? Or can you think of a better name?</strong></p> <p>Here is the class:</p> <pre><code>sealed abstract class ShowUnapproved { def shallShow(post: Post): Boolean // a "post" is e.g. a comment } object ShowUnapproved { case object None extends ShowUnapproved { override def shallShow(post: Post) = post.someVersionApproved } case object All extends ShowUnapproved { override def shallShow(post: Post) = true } case class WrittenByUser(userId: String) extends ShowUnapproved { override def shallShow(post: Post) = post.userId == userId } } </code></pre> <p>Here're two examples of how to use it:</p> <pre><code>PageReneder.renderPage(page, ShowUnapproved.All) PageReneder.renderPage(page, ShowUnapproved.WrittenByUser(userId)) </code></pre> <p>And what would you call instances of this <code>ShowUnapproved</code> class?</p> <p>I'm currently naming them <code>showUnapproved</code> which definitively sounds like a <code>Boolean</code> to me, and might be confusing:</p> <pre><code>val showUnapproved = ... // sounds like a Boolean but it is not val anyPendingApprovalText: NodeSeq = if (showUnapproved.shallShow(post)) makePendingApprovalText(post) else Nil // does `showUnapproved.shallShow` above sound good to you? </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T08:53:16.807", "Id": "43591", "Score": "1", "body": "``ShowUnapproved`` looks like some kind of action because it starts with a verb. You should rename it to something that sounds like a noun. Another thing is that it sounds like complete overkill to write a whole class to represent something that sounds like a simple boolean value, but I'm not sure if that is relevant in this context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T08:59:13.923", "Id": "43592", "Score": "0", "body": "@MichaelZedeler It does sound like an action, perhaps even more than like a boolean, I didn't think about that. — It's not intended as a simple boolean value though, because of the 3rd form that takes an ID. So I don't think it's overkill with a case class. — If one would use a boolean, then that would have to be combined with passing 2 arguments: bool + user-ID. And the user-ID would mean nothing if the bool was true. I don't like params that sometimes mean nothing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T09:01:58.853", "Id": "43593", "Score": "0", "body": "@MichaelZedeler Okay now I've come up with a name, but it's rather long. `VisibilityOfUnapprovedThings`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T09:41:42.147", "Id": "43594", "Score": "0", "body": "Yep. Its long :) I guess we're still not quite there..." } ]
[ { "body": "<p>What about something like this:</p>\n\n<pre><code>sealed abstract class CommentVisibility {\n def shallShow(comment: Comment): Boolean\n}\n\nobject CommentVisibility {\n case object HideUnapproved\n case object ShowUnapproved\n case class ShowAllByUser(userId)\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>renderPage(page, CommentVisibility.ShowUnapproved)\n</code></pre>\n\n<p>That's easy to understand :-) And can be amended to include e.g. showing/hiding comments with too many flags. (One would add another case class, perhaps using the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow\">Composite design pattern</a>)</p>\n\n<p>And reminds of CSS I think: \"visibility: hidden / visible\"</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T09:32:46.737", "Id": "27961", "ParentId": "27953", "Score": "1" } } ]
{ "AcceptedAnswerId": "27961", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T02:05:30.783", "Id": "27953", "Score": "1", "Tags": [ "scala" ], "Title": "Showing unapproved comments in a discussion system" }
27953
<p>I'm writing this game server for my small 2D MMO game.</p> <p>So here are my questions:</p> <ol> <li>What do you think about the Thread-Safety of the code?</li> <li>Please explain how can it be made thread-safe / show example/ fix the thing if its not thread safe already.</li> </ol> <pre><code>using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; public class Constanti { public const int CLASS_DARKELF_MAGICIAN = 1; public const int CLASS_HUMAN_MAGICIAN = 2; public const int CLASS_WARRIOR = 3; public const int CLASS_MODERN_GUNMAN = 4; public const int SUIT_1 = 1; public const int SUIT_2 = 2; public const int SUIT_3 = 3; public const int SUIT_4 = 4; public const int SUIT_Admin = 5; //MAX/MIN public const int MAX_LEVEL = 100; public const int MAX_SKILL_LEVEL = 1000; //SERVER MAX/MIN public const int MAX_CONNECTIONS = 300; public const int MAX_CONNECTIONS_IP = 54; } // State object for reading client data asynchronously public class Player { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); //Player-Info public int PlayerStats_Health = 0; public int PlayerStats_Energy = 0; public int PlayerInfo_Class = 0; public int PlayerInfo_Suit = 0; public int PlayerInfo_Level = 0; public int PlayerInfo_SkillLevel = 0; public void SetDefaults() { PlayerStats_Health = 100; PlayerStats_Energy = 200; PlayerInfo_Class = Constanti.CLASS_DARKELF_MAGICIAN; PlayerInfo_Suit = Constanti.SUIT_1; PlayerInfo_Level = 1; PlayerInfo_SkillLevel = 1; } public Player() { } public String pIPAddress; } public class GameObjectLists { public static List&lt;Player&gt; PlayersList = new List&lt;Player&gt;(); } public class AsynchronousSocketListener { // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); public static int PlayersOnline = 0; public AsynchronousSocketListener() {} public static void InitializeMySQL() { //TODO MySQLI/MySQL Connection } public static void MysqlUpdateQuery() { //Mysql UPDATE, no return stmt } public static String MySQLSelect() { //TODO MySQL Select String retdata="test"; return retdata; } public static void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. // The DNS name of the computer /* IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0];*/ IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 86); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); listener.Blocking = false; // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(50); Console.WriteLine("Server Started, waiting for connections..."); while (true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. // is there DOS vulnerability here ? listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } //Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } public static void AcceptCallback(IAsyncResult ar) { // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket clientsocket = listener.EndAccept(ar); // Signal the main thread to continue. allDone.Set(); clientsocket.Blocking = false; //set to non-blocking // Create the state object. Player PlayerInfo = new Player(); PlayerInfo.workSocket = clientsocket; IPEndPoint thisIpEndPoint = PlayerInfo.workSocket.RemoteEndPoint as IPEndPoint; //Get Local Ip Address PlayerInfo.pIPAddress = thisIpEndPoint.Address.ToString(); GameObjectLists.PlayersList.Add(PlayerInfo); PlayersOnline++; int numconnsofip = 0; GameObjectLists.PlayersList.ForEach(delegate(Player PlayerInfoCheck) { //Console.WriteLine(name); if (PlayerInfoCheck.pIPAddress == PlayerInfo.pIPAddress) { numconnsofip++; } }); if (PlayersOnline &gt; Constanti.MAX_CONNECTIONS || numconnsofip &gt; Constanti.MAX_CONNECTIONS_IP) { Disconnect(clientsocket, PlayerInfo); } else { Console.WriteLine("Player with IP:[{0}] has [{1}] Connections", thisIpEndPoint.Address.ToString(), numconnsofip); PlayerInfo.SetDefaults(); //clientsocket.LingerState = new LingerOption(true, 2); // give it up to 2 seconds for send Console.WriteLine("New Connection Total:[{0}]", PlayersOnline); clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback), PlayerInfo); } } public static void ProtocolCore(Player PlayerInfo, String data) { Console.WriteLine("Procesing Packet:{0}",data); //if data == bla bla then send something to everyone: //Is this thread-safe? GameObjectLists.PlayersList.ForEach(delegate(Player ObjPlayerInfo) { ObjPlayerInfo.PlayerStats_Health += 1; //thread safe? how? Send(data,ObjPlayerInfo); }); } public static void ReadCallback(IAsyncResult ar) { // TEST #1 - IF WE HANG HERE, THERE WILL BE STILL OTHER CONNECTIONS COMING HERE, BUT NO MULTI THREADING?? // Retrieve the state object and the clientsocket socket // from the asynchronous state object. Player PlayerInfo = (Player)ar.AsyncState; Socket clientsocket = PlayerInfo.workSocket; try { String content = String.Empty; //content buffer // Read data from the client socket. // IF THIS FAILS, WE CATCH / ASSUMING THAT: // THE CLIENT FORCE-CLOSED THE CONNECTION OR OTHER REASON. int bytesRead = clientsocket.EndReceive(ar); if (bytesRead &gt; 0) { // There might be more data, so store the data received so far. PlayerInfo.sb.Append(Encoding.ASCII.GetString( PlayerInfo.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = PlayerInfo.sb.ToString(); int eofindex = content.IndexOf("&lt;EOF&gt;"); if (eofindex &gt; -1) { // All the data has been read from the // client. Display it on the console. content = content.Substring(0,eofindex); //remove THE &lt;EOF&gt; Console.WriteLine("Read {0} bytes from socket. Data : {1}",content.Length, content); //PROCESS THE PACKET/DATA (PROTOCOL CORE) ProtocolCore(PlayerInfo, content); //Echo the data back to the client. Send(content, PlayerInfo); // CLEAR THE BUFFERS PlayerInfo.sb.Remove(0, PlayerInfo.sb.Length); Array.Clear(PlayerInfo.buffer, 0, PlayerInfo.buffer.Length); // GO TO LISTEN FOR NEW DATA clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback), PlayerInfo); } else { // Not all data received. Get more. clientsocket.BeginReceive(PlayerInfo.buffer, 0, Player.BufferSize, 0, new AsyncCallback(ReadCallback), PlayerInfo); } } else { //ASSUMING WE RECEIVED 0 SIZED PACKET or CLIENT DISCONNECT / THEREFORE CLOSE THE CONNECTION Disconnect(clientsocket, PlayerInfo); } } catch (Exception e) { Console.WriteLine(e.ToString()); Disconnect(clientsocket, PlayerInfo); } } private static void Send(String data,Player PlayerInfo) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); try { // Begin sending the data to the remote device. PlayerInfo.workSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), PlayerInfo); } catch (Exception e) { Console.WriteLine(e.ToString()); Disconnect(PlayerInfo.workSocket, PlayerInfo); } } private static void Disconnect(Socket clientsocket, Player PlayerInfo) { try { PlayersOnline--; //Is this Thread-Safe also? Console.WriteLine("Socket Disconnected, PlayerObjects:[{0}]", GameObjectLists.PlayersList.Count); GameObjectLists.PlayersList.Remove(PlayerInfo); clientsocket.Shutdown(SocketShutdown.Both); clientsocket.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void SendCallback(IAsyncResult ar) { // Retrieve the socket from the state object. Player PlayerInfo = (Player)ar.AsyncState; Socket clientsocket = PlayerInfo.workSocket; try { // Complete sending the data to the remote device. int bytesSent = clientsocket.EndSend(ar); Console.WriteLine("Sent {0} bytes to client.", bytesSent); } catch (Exception e) { Console.WriteLine(e.ToString()); Disconnect(clientsocket, PlayerInfo); } } public static int Main(String[] args) { InitializeMySQL(); StartListening(); return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T11:45:49.010", "Id": "43596", "Score": "0", "body": "Have you tested your code? Does it seem to work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:29:31.797", "Id": "43701", "Score": "0", "body": "Hmmm... You should restrict code to those specific sections you have questions about. For instance, `Contanti` probably isn't related to your threading question (you've put too many unrelated things inside it, anyways - learn to use Enums). I seriously doubt that your sockets should know about your DB, period. Stuff like `ObjPlayerInfo.PlayerStats_Health += 1;` is threadsafe unless there are explicit serialization guards - which you seem to lack. You shouldn't be outputting to `Console` directly - inject the relevant output stream." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T20:04:15.087", "Id": "114068", "Score": "0", "body": "\"small\" \"MMO\" pick one :p" } ]
[ { "body": "<p>Couple of things</p>\n\n<ol>\n<li><p>Magic Number #1</p>\n\n<pre><code>// Data buffer for incoming data.\nbyte[] bytes = new Byte[1024];\n</code></pre>\n\n<p>This could be something like </p>\n\n<pre><code>const int BUFFER_SIZE = 1024;\nbyte[] bytes = new byte[BUFFER_SIZE];\n</code></pre>\n\n<p>You already have something like this set up in the Player Class</p>\n\n<p>upon further inspection we see that this byte array isn't even used in the containing method, we should just get rid of it.</p></li>\n<li><p>Magic Number #2</p>\n\n<pre><code>listener.Listen(50);\n</code></pre>\n\n<p>you should call this number something like</p>\n\n<pre><code>const int LISTEN_TIME = 50;\n</code></pre>\n\n<p>and call the listen method like this</p>\n\n<pre><code>listener.Listen(LISTEN_TIME);\n</code></pre></li>\n<li><p>In the <code>StartListening</code> method's catch statement you probably want to dispose the socket so that it isn't bound up the next time you call the method.</p></li>\n<li><p>Naming for variables should be camelCase not PascalCase\nYou have some that are PascalCase</p>\n\n<pre><code>Player ObjPlayerInfo\n</code></pre>\n\n<p>Some that are all lowercase</p>\n\n<pre><code>Socket clientsocket = PlayerInfo.workSocket;\n</code></pre>\n\n<p>Be Consistent</p></li>\n<li><p>Return something more meaningful in your exceptions, these probably shouldn't be shown to the user, you could also log these errors as well.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T20:04:49.457", "Id": "114069", "Score": "1", "body": "To add to this, don't explicitly declare empty default constructors." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T19:12:32.423", "Id": "62561", "ParentId": "27954", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T04:39:01.820", "Id": "27954", "Score": "5", "Tags": [ "c#", "beginner", "multithreading", "asynchronous" ], "Title": "Asynchronous Server Sockets - Thread-Safety/Performance (MMO Gaming)" }
27954
<p>I wrote a simple parser for input-output operators. What is wrong with this code and how could it be better?</p> <pre><code>#ifndef PARSER_H_ #define PARSER_H_ #include &lt;string&gt; class parser { public: typedef std::string::const_iterator const_iterator; private: static const_iterator start_position(bool b, const std::string&amp; str); static const_iterator begin_it(const parser&amp; p); static const_iterator end_it(const parser&amp; p); static const_iterator current_it(const parser&amp; p); const_iterator begin; const_iterator end; const_iterator it; public: parser(): begin(NULL), end(NULL), it(NULL) {}; parser ( const std::string&amp; str_to_parse, bool start_from_the_end ): begin(str_to_parse.begin()), end (str_to_parse.end()), it (start_position(start_from_the_end, str_to_parse)) {}; //Give another string to parser: void str(const std::string&amp;); void set_to_begin(); void set_to_end(); parser&amp; operator = (const parser&amp;); bool eof_str() const; char get(); //move forward char rget(); //move backward char peek() const; //watch current symbol //pass an all symbols beginning from current: void pass(char); //moving forward void rpass(char); //moving backward //pass an all symbols beginning from //current which satisfy to condition: void pass(bool (*)(char)); //moving forward void rpass(bool (*)(char)); //moving backward //return iterator: const_iterator current_it() const; }; //This function is used in constructor: //it helps to set iterator of parser //to beginning or to the end of string. inline parser::const_iterator parser::start_position(bool b, const std::string&amp; str) { if (b) return str.end(); return str.begin(); } //This functions are used in operator=. //I decided to do not writing analogous //const-functions for better encapsulation. inline parser::const_iterator parser::begin_it(const parser&amp; p) {return p.begin;} inline parser::const_iterator parser::end_it(const parser&amp; p) {return p.end;} inline parser::const_iterator parser::current_it(const parser&amp; p) {return p.it;} inline void parser::str(const std::string&amp; str_to_parse) { begin = str_to_parse.begin(); end = str_to_parse.end(); it = str_to_parse.begin(); } inline void parser::set_to_begin() {it = begin;} inline void parser::set_to_end() {it = end;} inline parser&amp; parser::operator = (const parser&amp; p) { begin = begin_it(p); end = end_it(p); it = current_it(p); return *this; } inline bool parser::eof_str() const {return it &gt;= end;} inline char parser::get() {return *(it++);} inline char parser::rget() {return *(it--);} inline char parser::peek() const {return *it;} inline void parser::pass(char chr) { while (*it == chr) ++it; } inline void parser::rpass(char chr) { while (*it == chr) --it; } inline void parser::pass(bool (*cond)(char)) { while (cond(*it)) ++it; } inline void parser::rpass(bool (*cond)(char)) { while (cond(*it)) --it; } inline parser::const_iterator parser::current_it() const {return it;} #endif /* PARSER_H_ */ </code></pre> <p><strong>Example:</strong></p> <pre><code>#include "parser.h" #include &lt;string&gt; bool digit(char chr) { return (chr &gt;= '0' &amp;&amp; chr &lt;= '9'); } std::string cut_number(parser&amp; p, bool&amp; error) { error = false; //Check on that the first //symbol is a digit: if (!digit(p.peek())) { error = true; return ""; } parser::const_iterator begin = p.current_it(); //Check on that it is //correct number: if (p.get() == '0') { if (digit(p.peek())) { error = true; return ""; } } p.pass(digit); //In the code below could not be //if (p.get() == '.') //because next char after *p.it //must be checked only if *p.it == '.' if (p.peek() == '.') { p.get(); //Check on that it is //correct float pointing number: if (!digit(p.peek())) { error = true; return ""; } else p.pass(digit); } parser::const_iterator end = p.current_it(); return std::string(begin, end); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T06:10:01.443", "Id": "43725", "Score": "0", "body": "I don't understand what you are trying to achieve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T14:16:43.873", "Id": "43740", "Score": "0", "body": "I want write a class which offers an interface to working with strings without using of iterators or [] operators. What is wrong with this code and how to do it better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:33:30.900", "Id": "43743", "Score": "0", "body": "OK. You are aware of the `std::stream` interface. You can use it via strings with the class `std::stringstream`." } ]
[ { "body": "<p>It seems fine.</p>\n\n<p>Not sure the interface buys you anything over a normal iterator. </p>\n\n<p>The only error I see is:</p>\n\n<pre><code>inline\nbool parser::eof_str() const {return it &gt;= end;}\n</code></pre>\n\n<p>if <code>it</code> > <code>end</code> then technically the comparison is not valid. You may want to add code to protect yourself from moving beyond the end of the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:55:46.073", "Id": "28040", "ParentId": "27957", "Score": "3" } }, { "body": "<p>I see a few things I'd change (not really errors, but still open to improvement, IMO).</p>\n\n<p>First, I'd change the default ctor to use <code>nulltptr</code> instead of <code>NULL</code>:</p>\n\n<pre><code>parser() : begin(nullptr), end(nullptr), it(nullptr) {}\n</code></pre>\n\n<p>As shown, I'd also remove the extraneous <code>;</code> from the end of each definition, as above.</p>\n\n<p>I'd also change this constructor:</p>\n\n<pre><code>parser\n(\n const std::string&amp; str_to_parse,\n bool start_from_the_end\n):\n</code></pre>\n\n<p>... to take an enumeration instead of a bool:</p>\n\n<pre><code>enum direction {FORWARD, REVERSE};\n\nparser(std::string const &amp;input, enum direction d) { // ...\n</code></pre>\n\n<p>Alternative, I'd consider taking a pair of iterators, so the client code could pass forward iterators or reverse iterators as needed.</p>\n\n<p>For:</p>\n\n<pre><code>void pass(bool (*)(char)); //moving forward\nvoid rpass(bool (*)(char)); //moving backward\n</code></pre>\n\n<p>I think I'd rather see function templates, with the predicate type passed as a template parameter:</p>\n\n<pre><code>template &lt;class F&gt;\nvoid pass(F f);\n</code></pre>\n\n<p>With this, the user could pass a pointer to a function as is currently allowed, but could also pass a function object instead. The possible shortcoming is that passing an incorrect parameter type might easily produce a less readable error message.</p>\n\n<pre><code>inline\nparser::const_iterator parser::start_position(bool b, const std::string&amp; str) {\n\n if (b)\n return str.end();\n\n return str.begin();\n}\n</code></pre>\n\n<p>Again, I'd use the enumerated type from above instead of a Boolean (and, again, consider using iterators instead).</p>\n\n<p>This assignment operator:</p>\n\n<pre><code>inline\nparser&amp; parser::operator = (const parser&amp; p) {\n begin = begin_it(p);\n end = end_it(p);\n it = current_it(p);\n return *this;\n}\n</code></pre>\n\n<p>...looks like it's only doing what the compiler-generated operator would do if you didn't write one (in which case, I'd generally prefer to let the compiler do the job).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T05:11:44.400", "Id": "28187", "ParentId": "27957", "Score": "4" } } ]
{ "AcceptedAnswerId": "28187", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T07:28:06.550", "Id": "27957", "Score": "5", "Tags": [ "c++", "parsing" ], "Title": "Simple Parser, C++" }
27957
<p>I am reading space separated integers, removing redundant ones and then sorting them. The following code works.</p> <p>I was thinking whether this is the fastest way to do that or can it be optimized more?</p> <pre><code>import sys def p(): #Reads space seperated integers #Removes redundant #Then sorts them nums = set(map(int,next(sys.stdin).split())) nums = [i for i in nums] - nums.sort() print nums </code></pre> <p>EDIT:</p> <p>tobia_k's suggestion is better performance-wise. Just 1 sentence instead of 3 and better in time-efficiency.</p> <pre><code>nums = sorted([int(i) for i in set(next(sys.stdin).split())]) </code></pre>
[]
[ { "body": "<pre><code>inpt = raw_input(\"Enter a string of numbers: \")\nnumbers = sorted(set(map(int, inpt.split())))\nprint numbers\n</code></pre>\n\n<ul>\n<li>I would recommend separating the input-reading from the integer-extraction part.</li>\n<li>Using <code>raw_input</code> (Python 2.x) or <code>input</code> (Python 3) is more usual for reading user inputs.</li>\n<li>You can do it all in one line using <code>sorted</code> instead of <code>sort</code>.</li>\n<li>Performance-wise it <em>might</em> be better to apply <code>set</code> first, and then <code>map</code>, so <code>int</code> has to be applied to fewer elements, but I don't think it makes much of a difference, if at all.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T12:58:33.317", "Id": "43599", "Score": "0", "body": "I am working with online judging so performance matters a lot. I merged the reading and extraction part because they have slight overheads(not much but there are overheads). `raw_input` and `input` are very slow compared to this method. http://stackoverflow.com/questions/17023170/what-are-other-options-for-faster-io-in-python-2-7. Applying set first was better" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T12:32:21.360", "Id": "27963", "ParentId": "27962", "Score": "1" } } ]
{ "AcceptedAnswerId": "27963", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T10:12:25.497", "Id": "27962", "Score": "1", "Tags": [ "python" ], "Title": "Optimizing reading integers directly into a set without a list comprehension in Python" }
27962
<p>I found an interview question which requires us to print the elements of the matrix in a spiral order starting from the top left. I need some pointers on how to improve my code:</p> <pre><code>#include &lt;stdio.h&gt; //function that prints a row from startx,starty to endy void printRow(int arr[][4],int startx,int starty,int endy) { int yCtr; for(yCtr = starty; yCtr &lt;= endy ; yCtr ++) printf("%d ",arr[startx][yCtr]); } //function that prints a row from startx,starty to endy (decreasing columns) void printRowBackward(int arr[][4],int startx,int starty,int endy) { int yCtr; for(yCtr = starty; yCtr &gt;= endy ; yCtr --) printf("%d ",arr[startx][yCtr]); } //function that prints a column from startx,starty to endx void printColumnBackward(int arr[][4],int startx,int starty,int endx) { int xCtr; for(xCtr = startx; xCtr &gt;= endx; xCtr --) printf("%d ",arr[xCtr][starty]); } // column backwards void printColumn(int arr[][4],int startx,int starty,int endx) { int xCtr; for(xCtr = startx; xCtr &lt;= endx; xCtr ++) printf(" %d ",arr[xCtr][starty]); } // prints a section of the spiral void printSpiralSection(int arr[][4],int startx,int starty,int size) { printRow(arr,startx,starty,size - 1); printColumn(arr,startx + 1 ,size - 1 ,size -1); printRowBackward(arr,size - 1,size - 2,starty); printColumnBackward(arr,size - 2,starty,startx + 1); } int main() { int array[4][4] = { 22 ,323,2342,222, 2,234,243,333, 21,13,23,444, 223,234,231,234}; int startx =0, starty = 0, size = 4; // prints each section of the spiral ... while(size &gt;=1) { printSpiralSection(array,startx,starty,size); size --; startx++; starty++; } getchar(); return 0; } </code></pre>
[]
[ { "body": "<p>I would test it with a bigger array. Since I created one to test it, I might as well post it here. I put the numbers in the order I expected them to be printed, which makes checking easier.</p>\n\n<pre><code>const int array[][ARR_SIZE] = {\n { 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n { 32, 33, 34, 35, 36, 37, 38, 39, 10 },\n { 31, 56, 57, 58, 59, 60, 61, 40, 11 },\n { 30, 55, 72, 73, 74, 75, 62, 41, 12 },\n { 29, 54, 71, 80, 81, 76, 63, 42, 13 },\n { 28, 53, 70, 79, 78, 77, 64, 43, 14 },\n { 27, 52, 69, 68, 67, 66, 65, 44, 15 },\n { 26, 51, 50, 49, 48, 47, 46, 45, 16 },\n { 25, 24, 23, 22, 21, 20, 19, 18, 17 },\n};\n</code></pre>\n\n<p>Define <code>ARR_SIZE</code> at the top to 9 and replace each explicit <code>4</code> (apart from those in the array of course) with ARR_SIZE. Make each function <code>static</code> and each array parameter <code>const</code>.</p>\n\n<p>Having done this I found that it really does work :-)</p>\n\n<hr>\n\n<p>Each of your for-loops would be better written:</p>\n\n<pre><code>for (int y = starty; y &lt;= endy; y ++) {\n printf(\"%d \", arr[startx][y]);\n}\n</code></pre>\n\n<p>Notice that I defind the loop variable within the loop and called it <code>y</code>\ninstead of <code>yCtr</code> (the <code>Ctr</code> was just noise) and added some spaces. Note that it is normal to put a space after a comma (applies everywhere in your code - your use of spaces is occasionally inconsistent). I prefer <code>start_x</code> to <code>startx</code> and <code>print_row</code> to <code>printRow</code>, but that it just personal preference. </p>\n\n<p>Also, a minor point, as the functions are named <code>printRow</code> and <code>printColumn</code> etc, it might be more natural to express the parameters in terms of rows and columns instead of x and y:</p>\n\n<pre><code>static void printRow(const int arr[][ARR_SIZE], int row, int col, int end_col)\n{\n for (; col &lt;= end_col ; ++col) {\n printf(\"%d \", arr[row][col]);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The main loop would normally be expressed as a for-loop</p>\n\n<pre><code>int startx = 0;\nint starty = 0;\nfor (int size = ARR_SIZE; size &gt;= 1; --size) {...\n</code></pre>\n\n<p>Note that I defined the two start variables on separate line - again this is considered best practice.</p>\n\n<p>Final point, your comments are mostly noise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T15:38:55.857", "Id": "43603", "Score": "0", "body": "Thanks. Whats the benefit of making the functions static ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T15:43:00.710", "Id": "43605", "Score": "0", "body": "None at all in a single-file program. It is just best to get into the habit of making all local functions (those that are not used outside of the file) `static`. For bigger programs spanning many files, static functions offer better encapsulation and more chance for compiler optimisation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T15:34:11.663", "Id": "27970", "ParentId": "27965", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T12:46:49.697", "Id": "27965", "Score": "2", "Tags": [ "c", "interview-questions", "matrix" ], "Title": "Program to display a matrix in a spiral form" }
27965
<p>I have been looking for a Cross-browser solution for <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList" rel="nofollow noreferrer"><code>DOMTokenList</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/element.classList?redirectlocale=en-US&amp;redirectslug=DOM/element.classList" rel="nofollow noreferrer"><code>element.classList</code></a>. I wasn't able to find much for <code>DOMTokenList</code> and the polyfills that I found for <code>element.classList</code> were mostly limited to IE8+ as they relied on modifying the DOM Element prototype. There are of course some other stand alone functions/methods that perform <code>element.classList</code>, as can be found in <kbd><a href="https://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript?lq=1">Change an element's CSS class with JavaScript</a></kbd>. Anyway, I thought I'd create my own solution and as generically as possible. The code that follows is working, but unfortunately I am unable to test on any Microsoft browsers. So, I'm looking for any edge cases where the code may fail or suggestions for improvement, before I make it publicly available on GitHub or GIST (probably GIST would be best for such a project?).</p> <p>Javascript</p> <pre><code>/*jslint maxerr: 50, indent: 4, browser: true, bitwise: true, white: true */ /* DOMTokenList v1.2 * * home: http://code.google.com/p/domtokenlist// * * This type represents a set of space-separated tokens. * Commonly returned by HTMLElement.classList, HTMLLinkElement.relList, * HTMLAnchorElement.relList or HTMLAreaElement.relList. * It is indexed beginning with 0 as with JavaScript arrays. * DOMTokenList is always case-sensitive. Written with cross-browser compatibility in mind and * does not require any external libraries. */ var tokenList = (function (undef) { "use strict"; /* The space characters, for the purposes of this specification, * are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), * U+000C FORM FEED (FF), and U+000D CARRIAGE RETURN (CR). * * The White_Space characters are those that have the Unicode property "White_Space" * in the Unicode PropList.txt data file. * * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character */ var whiteSpaces = " \\t\\n\\f\\r", wsSplitRX = new RegExp("[" + whiteSpaces + "]+"), wsTrimRX = new RegExp("^[" + whiteSpaces + "]+|[" + whiteSpaces + "]+$", "g"), CtrBoolean = true.constructor, CtrNumber = (0).constructor, CtrString = "".constructor, toStringFn = {}.toString; function isValid(object) { return object !== undef &amp;&amp; object !== null; } function toObject(object) { if (!isValid(object)) { throw new TypeError("Cannot convert " + object + " to object"); } switch (typeof object) { case "boolean": return new CtrBoolean(object); case "number": return new CtrNumber(object); case "string": return new CtrString(object); default: } return object; } function toString(string) { if (!isValid(string)) { string = toStringFn.call(string); } return toObject(string).toString().replace(wsTrimRX, ""); } function errorIfEmpty(string) { if (!string) { throw new SyntaxError("Can not be an empty string."); } } function validTokenString(string) { errorIfEmpty(string); if (string.search(wsSplitRX) !== -1) { throw new SyntaxError("May not contain \"White_Space\" characters."); } return string; } function isValidIndex(index) { return (index &gt;&gt;&gt; 0) === index &amp;&amp; index &lt;= 4294967294; } function isValidIndexRange(index) { if (!isValidIndex(index)) { throw new RangeError("Index is not of valid range."); } return index; } function isValidLength(length) { if ((length &gt;&gt;&gt; 0) !== length || length &gt; 4294967295) { throw new RangeError("Length is not of valid range."); } return length; } function push(array, object) { var index = isValidIndexRange(array.length); array[index] = object; index += 1; array.length = index; } function elementToString(element) { if (isValid(element)) { return element.toString(); } return ""; } function indexOf(array, searchElement) { var length = isValidLength(array.length), key = 0; while (key &lt; length) { if (array.hasOwnProperty(key) &amp;&amp; searchElement === array[key]) { return key; } key += 1; } return -1; } function augmentToken(token) { return validTokenString(toString(token)); } /* This type represents a set of space-separated tokens. * Commonly returned by HTMLElement.classList, HTMLLinkElement.relList, * HTMLAnchorElement.relList or HTMLAreaElement.relList. * It is indexed beginning with 0 as with JavaScript arrays. * DOMTokenList is always case-sensitive. * * https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList?redirectlocale=en-US&amp;redirectslug=DOM%2FDOMTokenList */ function DOMTokenList(string) { if (string === DOMTokenList.prototype.inheritAPI) { return; } this.set(string); } DOMTokenList.prototype = { inheritAPI: {}, set: function (string) { var array = toString(string).split(wsSplitRX), length = isValidLength(array.length), element, i; for (i in this) { if (this.hasOwnProperty(i) &amp;&amp; isValidIndex(i)) { delete this[i]; } } i = 0; this.length = 0; while (i &lt; length) { element = array[i]; if (element) { push(this, element); } i += 1; } }, toString: function () { var length = isValidLength(this.length), result = elementToString(this[0]), k = 1; while (k &lt; length) { result += (" " + elementToString(this[k])); k += 1; } return result; }, /* Properties * * length (read-only integer) * for cross-browser purposes 'this.length' is read/write * */ length: 0, /* Methods * * item ( idx ) - returns an item in the list by its index (or undefined if the number is greater than or equal to the length of the list, prior to Gecko 7.0 returned null) * contains ( token ) - return true if the underlying string contains token, otherwise false * add ( token ) - adds token to the underlying string * remove ( token ) - remove token from the underlying string * toggle ( token ) - removes token from string and returns false. If token doesn't exist it's added and the function returns true * */ item: function item(position) { if (this.hasOwnProperty(position) &amp;&amp; isValidIndex(position)) { return this[position]; } return undef; }, contains: function (token) { return indexOf(this, augmentToken(token)) !== -1; }, add: function (token) { token = augmentToken(token); if (!this.contains(token)) { push(this, token); } }, remove: function (token) { token = augmentToken(token); if (this.contains(token)) { var index = indexOf(this, token), length, k, from; while (index &gt; -1) { length = this.length; this.length -= 1; if (index &lt; length) { k = index; } else { k = length; } while (k &lt; this.length) { from = (k + 1); if (this.hasOwnProperty(from)) { this[k] = this[from]; } else { delete this[k]; } k += 1; } k = length; while (k &gt; this.length) { delete this[k - 1]; k -= 1; } index = indexOf(this, token); } } }, toggle: function (token) { token = augmentToken(token); if (this.contains(token)) { this.remove(token); return false; } this.add(token); return true; } }; function TokenList(object, property) { if (object === DOMTokenList.prototype.inheritAPI) { return; } this.setProperty = function () { object[property] = DOMTokenList.prototype.toString.call(this); }; this.update = function () { DOMTokenList.prototype.set.call(this, object[property]); }; this.update(); } TokenList.prototype = (function () { var prototype = new DOMTokenList(DOMTokenList.prototype.inheritAPI), overwrite = { toString: function () { this.update(); return DOMTokenList.prototype.toString.call(this); }, item: function (position) { this.update(); return DOMTokenList.prototype.item.call(this, position); }, contains: function (string) { this.update(); return DOMTokenList.prototype.contains.call(this, string); }, add: function ( /* token1, ..., tokenN */ ) { var length = arguments.length, i = 0; this.update(); while (i &lt; length) { DOMTokenList.prototype.add.call(this, arguments[i]); this.setProperty(); i += 1; } }, remove: function ( /* token1, ..., tokenN */ ) { var length = arguments.length, i = 0; this.update(); while (i &lt; length) { DOMTokenList.prototype.remove.call(this, arguments[i]); this.setProperty(); i += 1; } }, toggle: function (token) { this.update(); var state = DOMTokenList.prototype.toggle.call(this, token); this.setProperty(); return state; } }, i; for (i in overwrite) { if (overwrite.hasOwnProperty(i)) { prototype[i] = overwrite[i]; } } return prototype; }()); function addTokenList(object, property, name) { object = toObject(object); property = toString(property); name = toString(name); errorIfEmpty(property); errorIfEmpty(name); if (object.hasOwnProperty(name)) { throw new Error("object already has a property named \"" + name + "\""); } object[name] = new TokenList(object, property); } return { "DOMTokenList": DOMTokenList, "TokenList": TokenList, "addTokenList": addTokenList }; }()); </code></pre> <p>I have also a <kbd><a href="http://jsfiddle.net/Xotic750/bav7e/" rel="nofollow noreferrer">jsfiddle</a></kbd> that demonstrates it in use on a DOM Element and on a plain Object.</p> <p>HTML</p> <pre><code>&lt;div id="test" class="test1 ok ok test2 test3"&gt;test&lt;/test&gt; </code></pre> <p>Javascript</p> <pre><code>tokenList.addTokenList(test, "className", "testClassList"); tokenList.addTokenList(test2, "myTokenString", "myTokenList"); test.classList.remove("ok"); test.testClassList.update(); console.log(test.testClassList); console.log(test.className); test.testClassList.add("test4", "test5"); test.testClassList.remove("test2", "test3"); console.log(test.testClassList.toggle("test1")); console.log(test.testClassList.toggle("test6")); test.testClassList.remove("test6", "test7"); console.log(test.className); console.log(test.testClassList.item(1)); console.log(test.testClassList, test2.myTokenList); test2.myTokenList.toggle("ok"); test2.myTokenList.toggle("ok2"); console.log(test2); console.log(test2.myTokenList); </code></pre> <p>I have also created a <kbd><a href="http://jsperf.com/cross-broswer-classlist-vs-native/2" rel="nofollow noreferrer">jsperf</a></kbd> to compare the native <code>classList</code> of modern browsers vs this solution vs jquery. </p> <p><strong><em>Note:</strong> I added the jquery tests just for a comparison, though you can not really compare this solution and that of jquery as this solution tries to fully emulate <code>DOMTokenList</code> and provides greater flexibility and generality in POJS and doesn't harness any modern methods. The same code path executes on all browsers.</em></p> <p><strong>Update:</strong> I have now created a project on <kbd><a href="http://code.google.com/p/domtokenlist/" rel="nofollow noreferrer">Google Code</a></kbd> and have updated my <kbd><a href="http://code.google.com/p/more-or-less/" rel="nofollow noreferrer">more-or-less</a></kbd> project to use it. A demonstration of which can be found on <kbd><a href="http://jsfiddle.net/Xotic750/uu9Rk/" rel="nofollow noreferrer">jsfiddle</a></kbd>.</p>
[]
[ { "body": "<p>From top to bottom, my 2 cents:</p>\n\n<pre><code>function isValid(object) {\n return object !== undef &amp;&amp; object !== null;\n}\n</code></pre>\n\n<p>object parameter should be more aptly named ( value? ) since you will check non objects with this that are valid.</p>\n\n<pre><code>if (!isValid(string)) {\n string = toStringFn.call(string);\n}\n</code></pre>\n\n<p>Seems wrong, why not</p>\n\n<pre><code>if( typeof string === \"function\" ){\n string = toStringFn.call(string);\n}\n</code></pre>\n\n<p>You error out in both <code>errorIfEmpty</code> and <code>validTokenString</code>, but only the first function mentions that in the function name. I would expect then that <code>validTokenString</code> would not throw an error, and that it would return a boolean, not the the string I passed.</p>\n\n<p><code>4294967294</code> is magic number, you should at least comment how you got there</p>\n\n<p>Same goes for <code>isValidIndexRange</code>, functions with isXXX should return booleans, and not throw errors.</p>\n\n<p><code>4294967295</code> is a magic number as well. <code>isValidLength</code> is not consistent with they way you wrote <code>isValidIndex</code> and <code>isValidIndexRange</code>.</p>\n\n<p>function <code>push()</code> is odd, why do you not use the built-in push of Array after you check the validIndexRange? If there is a difference, you should comment it.</p>\n\n<p>for indexOf, I would first check whether the browser has it built in, and use that if possible. Also consider something like </p>\n\n<pre><code>function indexOf(array, searchElement) {\n var pointer = array.length;\n\n while (pointer--) {\n if (searchElement === array[pointer]) {\n return pointer;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>Personally, for short functions, I tend to drop the curlies:</p>\n\n<pre><code>function indexOf(array, searchElement)\n{\n var pointer = array.length;\n\n while (pointer--)\n if (searchElement === array[pointer])\n return pointer;\n\n return -1;\n}\n</code></pre>\n\n<p>Trinary could help for elementToString</p>\n\n<pre><code>function elementToString(element) {\n return isValid(element)?element.toString():\"\"\n}\n</code></pre>\n\n<p>it could also help for determining k \n <code>k = (index &lt; length)?index:length;</code></p>\n\n<p>For loops could also make your code easier to parse, less sprinkled with housekeeping.</p>\n\n<pre><code>var i = 0;\nthis.update();\nwhile (i &lt; length) {\n DOMTokenList.prototype.remove.call(this, arguments[i]);\n this.setProperty();\n i += 1;\n}\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>this.update();\nfor (var i = 0 ; i &lt; length ;i++) {\n DOMTokenList.prototype.remove.call(this, arguments[i]);\n this.setProperty();\n}\n</code></pre>\n\n<p>Having to call <code>this.update();</code> in every function of <code>TokenList</code> is a code smell to me, I am not sure what to recommend instead, but it sure does not look good.</p>\n\n<p>Finally, I think this could a tad more commenting ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T11:40:50.653", "Id": "60144", "Score": "0", "body": "Thanks or the feedback, I had noted some of those points myself but have been too busy to revisit and fix things up a little more.\n\nMagic numbers are javacript limits of number of entries in arrays (32 bit).\n\nPush was to overcome a bug in some older browser that I was reading about at the time.\n\nConverting the whiles to fors was something that I had thought about doing. At the time I was doing some testing on while loops and so that pattern was in my head.\n\nThe reason for not polyfilling some routines was so that all browsers use the same code path." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T11:42:15.860", "Id": "60145", "Score": "0", "body": "I never drop curlys due to linting practices, I also never drop semicolons. Just a style thing.\nThe this.Update was a necessaary evil, tried object watch and other event listeners but support was just not there cross browser, and all other solutions that I tried had there own problems. This was the best that I could come up with, and it still has it's own problems.\nComments - well yeah :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T15:25:26.743", "Id": "60348", "Score": "0", "body": "I would remove the check, 4 billion DOM elements seems a tad excessive." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-03T17:07:47.840", "Id": "36590", "ParentId": "27968", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T14:53:18.663", "Id": "27968", "Score": "4", "Tags": [ "javascript", "html", "array", "inheritance" ], "Title": "Cross-browser DOMTokenList object and wrapper function. Failures and improvements?" }
27968
<p>I am trying to do a randomize function. It randomly selects one person (from two) to insert something into the console. The second person goes next, and then they keep alternating until the loop ends.</p> <pre><code> randomize(); RandomTurn := random(2)+1; while (1) do begin if RandomTurn = 1 then PersonTurn((NumberOfMoves mod 2)+1) else PersonTurn(round(2/((NumberOfMoves mod 2)+1))); NumberOfMoves := NumberOfMoves + 1; end; </code></pre> <p>What do you think? How could this function be improved based on number of moves/user inputs?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T09:32:57.467", "Id": "44090", "Score": "0", "body": "What's the argument to `PersonTurn()` and why do you need it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-24T20:19:56.583", "Id": "45564", "Score": "0", "body": "There are two persons who are changing in their turn like in chess or any other game, so I wanted to do a fnction which will always turn another person BUT at the begining it chooses randomly on of them ..." } ]
[ { "body": "<h3>Randomness</h3>\n\n<p><a href=\"https://stackoverflow.com/questions/3946869/how-reliable-is-the-random-function-in-delphi\">This answer</a> suggests that <code>Random(2)</code> would be okay for most uses. If you want more randomness, you could for example use an implementation of <a href=\"http://en.wikipedia.org/wiki/Mersenne_twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a>. <a href=\"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/PASCAL/pascal.html\" rel=\"nofollow noreferrer\">This page</a> lists a few options for Pascal/Delphi, for example <a href=\"http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/PASCAL/nicholls.txt\" rel=\"nofollow noreferrer\">this implementation</a>.</p>\n\n<h3>Alternating values</h3>\n\n<p>Now that I know what you are looking for, I would write the code like this:</p>\n\n<pre><code>// If Value is divisible by 2 then return 1, otherwise return 2\nprocedure AlternateValue(Value) : ShortInt;\nbegin\n if Value mod 2 = 0 then Result := 1 else Result := 2\nend;\n\n// Your code\nrandomize();\nRandomTurn := random(2)+1;\nNumberOfMoves := RandomTurn\n\nwhile (1) do\nbegin\n PersonTurn(AlternateValue(NumberOfMoves))\n NumberOfMoves := NumberOfMoves + 1;\nend;\n</code></pre>\n\n<p>You should swap the two lines in the <code>while</code> loop if you want to start with the same number as <code>Random</code> gives. From what I gather, it should not matter much, however.</p>\n\n<p>(I have never written any Pascal or Delphi before, so the code and/or syntax may not be perfect or correct.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T11:51:05.707", "Id": "43885", "Score": "0", "body": "Yes I need to randomize first input to be randomly 1 or 2 and after that changing 1 - 2 - 1 - 2 etc. So only first number will be random and then others will always change, does this code of yours do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:29:47.220", "Id": "43910", "Score": "2", "body": "@Byakugan: To switch between `1` and `2`, you could just do `NewValue := 3 - OldValue`: `3 - 1` -> `2`, `3 - 2` -> `1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T19:21:21.920", "Id": "43923", "Score": "0", "body": "Yes, the code I posted would do that. I have revised my answer, however, to indicate how I would write it now that I understand what you are after. You could also do as @AndriyM suggests, but I think my example is cleaner and more readable, because it states exactly what the intent of the code is. Does this answer your question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T10:22:51.403", "Id": "43954", "Score": "0", "body": "My snippet had a bug, because I forgot to do `mod 2`. That is fixed now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T09:29:08.217", "Id": "44089", "Score": "0", "body": "@AndriyM Or `Result := Value mod 2 + 1;`. It would be cleaner to use `0` and `1` rather than `1` and `2`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:06:17.553", "Id": "44103", "Score": "0", "body": "@ThijsvanDien: Indeed, and I like your suggestion better than mine. As for whether it would be cleaner to use 0 & 1 instead of 1 & 2 in this particular case, I'm not sure. To switch between the former, you would do `Result := (Value + 1) mod 2;` – not much difference from the formula you've suggested for 1 & 2. (Although I'd agree that in most cases 0-based indices are easiest to work with.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T20:05:22.590", "Id": "44127", "Score": "0", "body": "@AndriyM The whole point of my suggestion is that `i mod 2` alternates between `0` and `1` for increasing `i`. So `Result := Value mod 2;`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T11:11:20.567", "Id": "28124", "ParentId": "27974", "Score": "3" } }, { "body": "<p>I would improve the readability a bit by using:</p>\n\n<pre><code>PersonToPlay := RandomInitial();\nFor i:=MoveIndex := 1 to TotalNumberOfMoves do begin\n PersonTurn(PersonToPlay);\n PersonToPlay := 3 - PersonToPlay;\nend;\n</code></pre>\n\n<p>To make it even more readable:</p>\n\n<pre><code>PersonToPlay := RandomInitial();\nFor i:=MoveIndex := 1 to TotalNumberOfMoves do begin\n PersonTurn(PersonToPlay);\n PersonToPlay := TheOtherPlayer(PersonToPlay);\nend;\n....\n\nFunction TheOtherPlayer (aPlayer : TPlayer) : TPlayer;\nBegin\n if aPlayer := ThisPlayer then \n Result := ThatPlayer\n else\n Result := ThisPlayer;\nEnd;\n</code></pre>\n\n<p>Rate Readability over Speed (usually). Make your code comment itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T08:22:05.613", "Id": "32020", "ParentId": "27974", "Score": "0" } } ]
{ "AcceptedAnswerId": "28124", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T17:48:52.733", "Id": "27974", "Score": "2", "Tags": [ "optimization", "delphi" ], "Title": "Improve randomization function (from 1 to 2)" }
27974
<p>I am creating a file uploader, and one function of the uploader will parse the file name to make sure that it is in the correct format. </p> <p>This is the proper format of the file name: FILENAME_USERNAME_<strong>YYYYMMDD</strong>.csv, where FILENAME and USERNAME are any chars of any length.</p> <p>Specifically, I must extract the <strong>date</strong> from the file name and compare it to a date given in the .csv file content. (comparing to a date: <strong>MM/DD/YYYY</strong>).</p> <p>Below is the way that I have approached the problem: but if the user happens to input a file with a random, arbitrary file name, it's very possible for the method to throw a null pointer exception.. Hoping for a suggestion for a more elegant solution.</p> <pre><code>public boolean compareDate(File file, String cellDate) { String date; String tempDate; String year, month, day; int startIndex = file.getName().lastIndexOf("_"); int lastIndex = file.getName().lastIndexOf("."); if (startIndex &gt; 0 &amp;&amp; lastIndex &gt; 0) { tempDate = file.getName().substring(startIndex+1, lastIndex); if (tempDate.length() &lt; 8) // 8 == chars in date return false; } year = tempDate.substring(0,4); month = tempDate.substring(4,6); day = tempDate.substring(6,8); date = month + "/" + day + "/" + year; if (date.equals(cellDate) || date.contains(cellDate)) // (ex. 01/25/2013 == 1/25/2013 return true; else return false; } </code></pre>
[]
[ { "body": "<p>My version:</p>\n\n<pre><code>public class CodeReview_27975 {\n // match everything between the last \"_\" and \".\" [explanation in the notes!]\n private final static Pattern FILENAME_DATE_PATTERN = Pattern.compile(\".*_(.*?)\\\\..*\");\n\n // apply the pattern to extract date from file name\n private String extractDateFromFilename(String filename) {\n Matcher m = FILENAME_DATE_PATTERN.matcher(filename);\n if (!m.matches()) {\n throw new IllegalArgumentException(\n \"Filename doesn't match expected format: \" + filename);\n }\n\n return m.group(1);\n }\n\n private boolean compareDate(String fileName, String cellDateString) {\n SimpleDateFormat fileDateParser = new SimpleDateFormat(\"yyyyMMdd\");\n SimpleDateFormat cellDateParser = new SimpleDateFormat(\"MM/dd/yyyy\");\n\n Date d1, d2;\n try {\n d1 = fileDateParser.parse(extractDateFromFilename(fileName));\n d2 = cellDateParser.parse(cellDateString);\n } catch (ParseException e) {\n throw new IllegalArgumentException(\n \"One of the input dates failed to be parsed:\" + fileName\n + \", \" + cellDateString);\n }\n\n return d1.equals(d2);\n }\n\n // this is the only public method, but it delegates to private utility functions\n public boolean compareDate(File file, String cellDate) {\n return compareDate(file.getName(), cellDate);\n }\n\n public static void main(String[] args) {\n CodeReview_27975 app = new CodeReview_27975();\n // easy to test\n System.out.println(app.compareDate(\"file_user_20130125.csv\", \"1/25/2013\"));\n System.out.println(app.compareDate(\"file_user_20130125.csv\", \"01/25/2013\"));\n System.out.println(app.compareDate(\"file_user_20130101.csv\", \"1/1/2013\"));\n }\n}\n</code></pre>\n\n<ul>\n<li>split the single method into smaller, easier to test, chunks.</li>\n<li>each function deals with a single concern (most of the code deals with strings, no need to pass the <code>File</code> object further down the stack). This makes it easier to test</li>\n<li>regular expressions are useful when dealing with patterns in strings. Extracting date from file is much more robust this way (you'll most likely getting the <code>NullPointerException</code> for non-standard input; the current expression doesn't solve this problem but at least it reports it correctly, making it easier to create a fix)</li>\n<li>comparing dates as strings is just wrong; your <em>equals-or-contains</em> trick would fail when comparing <code>1/1/2013</code> and <code>01/01/2013</code>. Creating a <code>Date</code> object is a small price to pay for correctness.</li>\n<li>the class could be visually longer but I believe it's easier to understand this way; most of the new code comes from exception handling - if you decided to simply make the caller handle checked exceptions, you could remove most of that.</li>\n</ul>\n\n<p>Also, <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare(T,%20T)\" rel=\"nofollow noreferrer\">convention</a> for <code>compare</code> functions is to return an integer: &lt;0 if first argument is smaller, 0 if both are equal and >1 if the first argument if bigger. This would make the method more flexible and potentially useful for the caller. Changing the name to <code>areDatesSame</code> or something like that would be another option.</p>\n\n<hr>\n\n<p><strong>edit:</strong>\n<code>\".*_(.*?)\\\\..*\"</code> pattern dissected:</p>\n\n<pre><code>.* any character, zero or more of them at the start\n_ an underscore\n(.*?) capture a group (after underscore, before the dot)\n\\. dot character (has to be escaped into \"\\\\.\" if inside a String)\n.* any character, any number of them at the end\n</code></pre>\n\n<p>Regular expressions are a broad subject but knowing the basics (and where/how to look for more detailed information) will always pay off. You can start by having a look at the <a href=\"http://docs.oracle.com/javase/tutorial/essential/regex/\" rel=\"nofollow noreferrer\">Java Tutorial on Regex</a></p>\n\n<p>The expression could be changed to only accept exactly 8 digits in the group (rather than ANY string between \"_\" and \".\"), making it a bit more complicated but more specific. </p>\n\n<p>Visualisation from debuggex.com:</p>\n\n<p><img src=\"https://www.debuggex.com/i/Kn1Z80wILHp6Frrl.png\" alt=\"Regular expression image\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T22:32:52.027", "Id": "43620", "Score": "0", "body": "This is great, exactly what I was hoping for. I'm not skilled at all in regex, although I knew the solution would involve it.\n\n\"Pattern.compile(\".*_(.*?)\\\\..*\")\"\n\nIf it's not too much trouble, can you explain the various symbols in that statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T22:54:18.727", "Id": "43621", "Score": "0", "body": "Great, thank you! Yes, I know realize how important and efficient it is to learn proper regex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T22:54:42.727", "Id": "43622", "Score": "1", "body": "Added some explanation, hopefully it will clear things up... And as a bonus: the 8-digits group regex I mentioned would look something like this: `\".*_(\\\\d{8})\\\\..*\"` [(Edit/test live on Debuggex)](http://www.debuggex.com/r/XygSVl9uik4HGVYv)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T22:19:43.890", "Id": "27976", "ParentId": "27975", "Score": "5" } } ]
{ "AcceptedAnswerId": "27976", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T20:50:49.520", "Id": "27975", "Score": "2", "Tags": [ "java", "strings", "parsing" ], "Title": "A better approach to parsing this file name in Java?" }
27975
<p>I have been working on a bash script for a while now to organize my movie files. I can do it by hand, but at the time I was taking a bash scripting class and thought I would like to use it to create this project. I don't know if there is a better way of doing it or not, but I would like you to take a look at my script and give me feedback on it. I believe it works, but I haven't put it through the paces yet.</p> <pre><code>#!/bin/bash MovieList="points to .txt file with name of files" DirList="points to a .txt file with the name to use to create the directory" dest_Dir="where to put the files " src_Dir="where to look for the files" CreateLogFile="log file of directory created" MoveLogFile="log file of move files" # Will read in a list of movies and make the directories for them createDirectory() { while read -r line do if [ ! -d $dest_Dir"$line" ] then mkdir -v $dest_Dir"$line" &gt;&gt; $CreateLogFile else : fi done &lt; "$DirList" } # end createDirectory # After directories have been created will go and find those movies and move # them to their proper directory movieMovies() { while read -r line do find $src_Dir -type f \( -iname "$line" ! -iname ".*" \) | xargs -I '{}' mv -v {} $dest_Dir"$line" &gt;&gt; $MoveLogFile done &lt; "$MovieList" } # end of moveMovies # Time to tidy up by going back and seeing if there is any empty directory # and if so removing said directory DirectoryEmpty() { while read -r line do if [ $(ls -A $dest_Dir"$line" | wc -l) -eq 0 ] then rmdir $dest_Dir"$line" else : fi done &lt; "$DirList" } # end of DirectoryEmpty # ---------------------------------Main--------------------------------------- createDirectory moveMovies DirectoryEmpty # ----------------------------------End--------------------------------------- </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T23:18:36.933", "Id": "43624", "Score": "0", "body": "If you don’t know of a problem, try [CodeReview.SE] instead." } ]
[ { "body": "<h3>errors</h3>\n\n<ul>\n<li>typo: function named <code>movieMovie</code>, invoked as <code>moveMovie</code></li>\n</ul>\n\n<h3>potential errors</h3>\n\n<ol>\n<li>use of <code>$dest_Dir\"$line\"</code>\n<ul>\n<li>you expect dest_Dir to end with a slash, but that's not validated anywhere</li>\n<li>use <code>\"$dest_Dir/$line\"</code> instead (it's OK to have multiple slashes)</li>\n</ul></li>\n<li><p><a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow\">don't use <code>ls</code></a> to verify the presence/absence of files:</p>\n\n<pre><code>removeEmptyDirectory() {\n dir=\"$1\"\n shopt -s globstar nullglob dotglob\n files=(\"$dir\"/*) # an array holding all the filenames\n if (( ${#files[@]} == 0 )); then\n # the directory is empty\n rmdir \"$dir\"\n else\n echo \"warning: directory not empty: $dir\" &gt;&amp;2\n fi\n}\n</code></pre>\n\n<p>Even better, use <code>find</code>:</p>\n\n<pre><code>removeEmptyDirectories() {\n while read -r line; do\n find \"$dest_Dir/$line\" -depth 0 -empty -exec rmdir '{}' \\;\n done &lt; \"$DirList\"\n}\n</code></pre></li>\n<li><p>Double quote all your variables, everywhere, unless you have a specific reason not to.</p></li>\n</ol>\n\n<h3>style</h3>\n\n<ol>\n<li>clean up your indentation. It is idiomatic to put <code>then</code> and <code>do</code> at the end of the same line as <code>if</code> and <code>while</code> (see <code>removeEmptyDirectories()</code> example above).</li>\n<li>use a consistent naming convention\n<ul>\n<li>variables <code>DirList</code>, <code>src_Dir</code> -- use camelcase or underscores, but both?</li>\n</ul></li>\n<li>don't need the <code>else :</code> branch</li>\n<li>\"line\" is not a descriptive variable name.</li>\n<li>use <code>find -exec</code> instead of piping to <code>xargs</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T19:27:00.887", "Id": "28047", "ParentId": "27977", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T23:14:47.467", "Id": "27977", "Score": "2", "Tags": [ "bash" ], "Title": "bash script to organize files and cleanup files" }
27977
<p>I've written a double-linked list library for another program I'm working on. I want to be particular about this library because I will be using it in another library, which will be used the program I'm currently working on.</p> <p>I'm including the header file, source file, and a test <code>main</code> file (and its output). As far as I can tell, everything works fine. But I can run additional testing, if there's a reason to do so.</p> <p>Any sort of feedback would be great. I don't mind criticism.</p> <p>The source file is large-ish, so I can remove the <code>main</code> and test results if nobody thinks that it's necessary.</p> <pre><code>#ifndef LIST_H #define LIST_H /* * list.h * * A simple library for using double linked lists * * Written by Taylor Holberton * During June 2013 */ typedef enum { list_null, list_single, list_front, list_back, list_middle } list_nodetype; struct list_node { void * data, * next, * last; }; /* Notes: * * 'after' and 'before' { * * The words after and before indicate which way * the list is shifting after list size modification * * ie: (1) - (2) - (3) * * putafter(2) = (1) - (2) - (n) - (3) * * putbefore (2) = (1) - (n) - (2) - (3) * } * * 'backwards' and 'forwards' { * * The words 'backwards' and 'forwards' refer * to the order of traversal the function will take. * 'Backwards' doesn't include the current node in the * traversal and 'forwards' does. * } */ struct list_node * list_createnode (unsigned int size); void list_setnode (struct list_node *, void * data, unsigned int size); struct list_node * list_get (struct list_node *, int offset); struct list_node * list_getfront (struct list_node *); struct list_node * list_getback (struct list_node *); struct list_node * list_putbefore (struct list_node *, unsigned int size); struct list_node * list_putafter (struct list_node *, unsigned int size); struct list_node * list_splitbefore (struct list_node *); struct list_node * list_splitafter (struct list_node *); struct list_node * list_freeforwards (struct list_node *); void list_freebackwards (struct list_node *); void list_free (struct list_node *); void list_remove (struct list_node *); unsigned int list_size (struct list_node *); unsigned int list_countbackwards (struct list_node *); unsigned int list_countforwards (struct list_node *); // returns the node at which the traversal stopped (may be null) struct list_node * list_traverse (struct list_node *, int (*callback)(void *)); struct list_node * list_traversebackwards (struct list_node *, int (*callback)(void *)); struct list_node * list_traverseforwards (struct list_node *, int (*callback)(void *)); struct list_node * list_pop (struct list_node *); struct list_node * list_popback (struct list_node *); struct list_node * list_popfront (struct list_node *); struct list_node * list_pushback (struct list_node *, unsigned int size); struct list_node * list_pushfront (struct list_node *, unsigned int size); list_nodetype list_getnodetype (struct list_node * node); #endif </code></pre> <p>Source file:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "list.h" struct list_node * list_createnode (unsigned int size){ size += sizeof (struct list_node); struct list_node * newnode = calloc (1, size); if (size) newnode-&gt;data = newnode + sizeof (struct list_node); return newnode; } void list_setnode (struct list_node * node, void * data, unsigned int size){ if (node &amp;&amp; node-&gt;data) memcpy (node-&gt;data, data, size); } struct list_node * list_get (struct list_node * node, int offset){ switch (list_getnodetype (node)){ case list_null: return 0; case list_back: if (offset &gt; 0) return 0; break; case list_front: if (offset &lt; 0) return 0; break; } if (offset &gt; 0) while (node &amp;&amp; offset){ node = node-&gt;next; offset--; } if (offset &lt; 0) while (node &amp;&amp; offset){ node = node-&gt;last; offset++; } return node; } struct list_node * list_getfront (struct list_node * node){ if (node) while (node-&gt;last) node = node-&gt;last; return node; } struct list_node * list_getback (struct list_node * node){ if (node) while (node-&gt;next) node = node-&gt;next; return node; } struct list_node * list_putbefore (struct list_node * node, unsigned int size){ struct list_node * newnode = 0, * last = 0; switch (list_getnodetype (node)){ case list_null: break; default: if (newnode = list_createnode (size)){ last = node-&gt;last; newnode-&gt;next = node; newnode-&gt;last = node-&gt;last; node-&gt;last = newnode; if (last) last-&gt;next = newnode; } break; } return newnode; } struct list_node * list_putafter (struct list_node * node, unsigned int size){ struct list_node * newnode = 0, * next = 0; switch (list_getnodetype (node)){ case list_null: break; default: if (newnode = list_createnode (size)){ next = node-&gt;next; newnode-&gt;last = node; newnode-&gt;next = next; if (next) next-&gt;last = newnode; node-&gt;next = newnode; } break; } return newnode; } struct list_node * list_splitbefore (struct list_node * node){ struct list_node * last = 0; switch (list_getnodetype (node)){ case list_middle: case list_back: last = node-&gt;last; last-&gt;next = 0; node-&gt;last = 0; last = list_getfront (last); break; } return last; } struct list_node * list_splitafter (struct list_node * node){ struct list_node * next = 0; switch (list_getnodetype (node)){ case list_middle: case list_front: next = node-&gt;next; next-&gt;last = 0; node-&gt;next = 0; } return next; } struct list_node * list_freeforwards (struct list_node * node){ struct list_node * temp = 0, * last = 0; switch (list_getnodetype (node)){ case list_middle: case list_back: last = node-&gt;last; } while (node){ temp = node-&gt;next; free (node); node = temp; } return last; } void list_freebackwards (struct list_node * node){ struct list_node * temp = 0; switch (list_getnodetype (node)){ case list_middle: case list_back: node = node-&gt;last; while (node){ temp = node-&gt;last; free (node); node = temp; } break; } } void list_free (struct list_node * node){ switch (list_getnodetype (node)){ case list_null: return; case list_front: list_freeforwards (node); break; case list_middle: list_freebackwards (node); // the order of this list_freeforwards (node); // is important break; case list_back: list_freebackwards (node); free (node); break; case list_single: free (node); break; } } void list_remove (struct list_node * node){ node = list_pop (node); if (node) free (node); } unsigned int list_size (struct list_node * node){ unsigned int count = 0; switch (list_getnodetype (node)){ case list_null: return 0; case list_single: return 1; default: count = list_countforwards (node) + list_countbackwards (node); break; } return count; } unsigned int list_countbackwards (struct list_node * node){ unsigned int count = 0; switch (list_getnodetype (node)){ case list_null: case list_front: break; case list_single: return 1; default: while (node = node-&gt;last) count++; break; } return count; } unsigned int list_countforwards (struct list_node * node){ unsigned int count = 0; switch (list_getnodetype (node)){ case list_null: case list_back: break; case list_single: return 1; default: while (node){ count++; node = node-&gt;next; } break; } return count; } struct list_node * list_traverse (struct list_node * node, int (*callback)(void * data)){ if (!callback || !node) return node; node = list_getfront (node); while (node){ if (callback (node-&gt;data)) break; node = node-&gt;next; } return node; } struct list_node * list_traverseforwards (struct list_node * node, int (*callback)(void * data)){ if (!callback) return node; switch (list_getnodetype (node)){ case list_null: break; default: while (node){ if (callback (node-&gt;data)) break; node = node-&gt;next; } } return node; } struct list_node * list_traversebackwards (struct list_node * node, int (*callback)(void * data)){ if (!callback) return node; switch (list_getnodetype (node)){ case list_null: break; default: node = node-&gt;last; while (node){ if (callback (node-&gt;data)) break; node = node-&gt;last; } break; } return node; } struct list_node * list_pop (struct list_node * node){ struct list_node * next = 0, * last = 0; if (!node) return; next = node-&gt;next; last = node-&gt;last; if (next) next-&gt;last = last; if (last) last-&gt;next = next; node-&gt;next = 0; node-&gt;last = 0; return node; } struct list_node * list_popback (struct list_node * node){ return list_pop (list_getback (node)); } struct list_node * list_popfront (struct list_node * node){ return list_pop (list_getfront (node)); } struct list_node * list_pushback (struct list_node * node, unsigned int size){ return list_putafter (list_getback (node), size); // already error-checked } struct list_node * list_pushfront (struct list_node * node, unsigned int size){ return list_putbefore (list_getfront (node), size); } list_nodetype list_getnodetype (struct list_node * node){ list_nodetype type; if (!node) type = list_null; else if ( node-&gt;next &amp;&amp; !node-&gt;last) type = list_front; else if ( node-&gt;last &amp;&amp; !node-&gt;next) type = list_back; else if (!node-&gt;last &amp;&amp; !node-&gt;next) type = list_single; else type = list_middle; return type; } </code></pre> <p>Example implementation:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include "list.h" #define strpsize(value) value, sizeof (value) #define nodesize 5 int callback (void * data){ if (data) printf ("found data\n"); else printf ("found empty node\n"); return 0; } int callback2 (void * data){ if (data) printf ("found data traversing backwards!\n"); else printf ("found empty data traversing backwards!\n"); return 0; } int callback3 (void * data){ if (data) printf ("found data traversing forwards\n"); else printf ("found empty data traversing forwards!\n"); return 0; } int callback4 (void * data){ if (!data){ printf ("found empty slot. stopping loop now.\n"); return -1; } return 0; } int callback5 (void * data){ char * str = data; if (data &amp;&amp; str[0]){ printf ("found: %s\n", str); return -1; } else printf ("null\n"); return 0; } int main (){ struct list_node * head = list_createnode (nodesize), * middle = 0, * tail = 0, * error = 0; list_pushback (head, nodesize); list_pushback (head, 0); if (!head){ printf ("head is null\n"); list_free (head); return -1; } middle = list_get (head, 1); if (!middle){ printf ("middle node is null\n"); list_free (head); return -1; } middle = list_putafter (middle, nodesize); list_putbefore (middle, nodesize); list_pushfront (middle, nodesize); head = list_getfront (middle); printf ("size of list is %d\n", list_size (head)); printf ("size after head is %d\n", list_countforwards (head)); tail = list_getback (middle); printf ("size before tail is %d\n", list_countbackwards (tail)); printf ("size after middle is %d\n", list_countforwards (middle)); printf ("size before middle is %d\n", list_countbackwards (middle)); list_traverse (head, callback); list_traversebackwards (head, callback2); list_traverseforwards (head, callback3); list_traverse (head, callback4); middle = list_putafter (middle, sizeof ("node message")); list_setnode (middle, strpsize ("node message")); error = list_traverse (head, callback5); printf ("removing text node..\n"); list_remove (error); printf ("checking again..\n"); list_traverse (head, callback5); printf ("freeing memory\n"); list_free (head); printf ("exiting\n"); return 0; } </code></pre> <p>Results:</p> <pre><code>size of list is 6 size after head is 6 size before tail is 5 size after middle is 2 size before middle is 4 found data found data found data found data found data found data found data traversing forwards found data traversing forwards found data traversing forwards found data traversing forwards found data traversing forwards found data traversing forwards null null null null null found: node message removing text node.. checking again.. null null null null null null freeing memory exiting </code></pre> <p>Running this with <code>valgrind</code> the output is a little different and I get a lot of <em>invalid reads</em> (still working on that), but no memory leaks. I'm not asking anyone to figure that out, though - just a general review. </p> <p><strong>Additional notes:</strong></p> <p>The library was written so that any node within the list can be used for operations. This is advantageous when it comes to successive calls to similar areas within the list.</p> <p>For example:</p> <p>Instead of calling <code>list_pushback (head, size)</code> multiple times, like this:</p> <pre><code> list_pushback (head, size); list_pushback (head, size); list_pushback (head, size); </code></pre> <p>The calls could be made like this:</p> <pre><code> tail = list_pushback (head, size); tail = list_pushback (tail, size); tail = list_pushback (tail, size); </code></pre> <p>Which completely eliminates the need for traversal within the function - which greatly improves the speed in loops. This might help review the code, just so you know what I was "going for". </p>
[]
[ { "body": "<p>I'll post some more comments later, but to start with, you should let the compiler guide you. If you compile this with <code>-Wall</code> (<code>gcc</code> or <code>clang</code>) you will get many warnings and one error.</p>\n\n<ul>\n<li><p>Some warnings are caused by expressions such as</p>\n\n<pre><code>if (newnode = list_createnode (size)){ ...\n</code></pre>\n\n<p>which should hve an extra set of brackets to show that you intended the assignment:</p>\n\n<pre><code>if ((newnode = list_createnode (size))){ ...\n</code></pre>\n\n<p>Some coding standards will object to this too and prefer to see:</p>\n\n<pre><code>if ((newnode = list_createnode (size)) != NULL){ ...\n</code></pre></li>\n<li><p>Another source of warnings comes from your switch statements that do not\ninclude a case for each possibility</p></li>\n<li><p>Warnings also come from your test callbacks that should be 'static'. </p></li>\n<li><p>The error is in <code>list_pop</code> where you return without supplying a value</p></li>\n</ul>\n\n<p><strong>EDIT</strong></p>\n\n<hr>\n\n<p>Ok here's some further comments.</p>\n\n<p>In the header file I'd probably define the enum constants as upper-case (although I actually think they are unnecessary, as is the function that returns them and the switches that depend upon them). The list_node would more normally be expressed as:</p>\n\n<pre><code>struct list_node {\n void *data;\n struct list_node *next;\n struct list_node *prev;\n};\ntypedef struct list_node list_node;\n</code></pre>\n\n<p>I'm surprised that <code>list_node</code> doesn't hold the data size, as each of your\nnodes can differ in size. I'd re-name <code>last</code> to <code>prev</code> (previous) as it is\nnot ambiguous ('last' could mean the last in the list). Note that it is\ncommon to typedef the struct so that you don't have to type 'struct'\neverywhere:</p>\n\n<p>Well done for putting a meaningful explanation of terms in a comment.</p>\n\n<p>I see no <code>const</code> parameters - I'm sure some of those functions don't modify\ntheir input list.</p>\n\n<hr>\n\n<p>Some general comments on the implementation.</p>\n\n<p>I have never seen a list implementation that doesn't expect the user to keep a\npointer to the head of the list. Your list functions work with a pointer to\nanywhere in the list, which is interesting. But is there a need for this\nbehaviour? Why does your application need this?</p>\n\n<p>It is normal in C to start functions with the { in column 0. Although to be\nhonest, nobody else seems bothered about this.</p>\n\n<p>Sizes are often represented using <code>size_t</code> rather than <code>unsigned int</code>\n(although it comes to much the same thing). If <code>unsigned int</code> is used\ninstead, there is no need to include a system header to get <code>size_t</code>. But\nmost of the time that is not a concern and (although I am cautious in using\nunsigned types) I would use <code>size_t</code>.</p>\n\n<p>Use of braces even when strictly unnecessary is considered best\npractice. One-liners are generally not used much:</p>\n\n<pre><code>if (node &amp;&amp; node-&gt;data) {\n memcpy(node-&gt;data, data, size);\n}\n</code></pre>\n\n<p>Define only one variable per line and don't use commas to continue to another\nline.</p>\n\n<p>You are using switch statements where a simple if-then-else would be better.\nFor example in <code>list_putbefore</code></p>\n\n<pre><code>switch (list_getnodetype (node)){\n\ncase list_null:\n break;\n\ndefault:\n ...\n</code></pre>\n\n<p>is better stated as:</p>\n\n<pre><code>if (list_getnodetype(node) != list_null) {...}\n</code></pre>\n\n<p>Define variables where they are needed rather than at the start of the function. This makes their use clearer by reducing their scope.</p>\n\n<p>Your <code>list_getnodetype</code> is unnecessary.</p>\n\n<p><hr>\nIn <code>list_createnode</code> and <code>list_setnode</code>:</p>\n\n<p>The <code>if (size)</code> is redundant. You know that <code>sizeof (struct list_node)</code>\nis non-zero... unless you wanted to test the original size passed as a\nparameter, which is no longer available.</p>\n\n<p>Also, there is no check for <code>calloc</code> failure.</p>\n\n<p>Separating create and set functions might be reasonable, but I'd expect to see\nthe <code>set</code> function checking that the size is ok (which requires the node to\nhave a size field). Or, perhaps better, you could combine create/set so that the data is passed and copied when the node is allocated.</p>\n\n<hr>\n\n<p>In <code>list_get</code>:</p>\n\n<p>Much too complicated. Why not use the obvious:</p>\n\n<pre><code>while (offset &amp;&amp; node) {\n if (offset &lt; 0) {\n node = node-&gt;last;\n ++offset;\n }\n else {\n node = node-&gt;next;\n --offset;\n }\n}\nreturn node;\n</code></pre>\n\n<p>Also <code>node</code> could be <code>const</code> (true in many functions and not mentioned again)</p>\n\n<p><hr>\n<code>list_getfront</code> and <code>list_getback</code> should be written out normally, not\ncompressed vertically. Also consider a for-loop.</p>\n\n<pre><code>if (node) {\n for (; node-&gt;last; node = node-&gt;last) {\n /* nothing */\n }\n}\nreturn node;\n</code></pre>\n\n<hr>\n\n<p>In <code>list_putbefore</code> and <code>list_putafter</code>, you don't need to call\n<code>list_getnodetype</code> to tell that the list is empty. Also it would be\nreasonable to expect these functions to add the first element to the list\ninstead of failing if the list is empty.</p>\n\n<p><hr>\nIn <code>list_splitbefore</code> and <code>list_splitafter</code> you don't need to call\n<code>list_getnodetype</code> - you can just inspect <code>node</code> and <code>node-&gt;last/next</code></p>\n\n<pre><code>if (node &amp;&amp; node-&gt;last) {\n struct list_node *last = node-&gt;last;\n last-&gt;next = 0;\n node-&gt;last = 0;\n return list_getfront (last);\n}\nreturn NULL;\n</code></pre>\n\n<hr>\n\n<p>Your <code>list_free*</code> functions seem redundant. I'd expect a <code>list_free</code> to free\neverything from the given node forwards. If a caller really wants to free a\nlist using a pointer to somewhere other than the beginning of the list, she\ncan do:</p>\n\n<pre><code>list_free(list_getfront(list));\n</code></pre>\n\n<p>Similarly if the caller wants to free a list backwards from a pointer to\nsomewhere other than the beginning of the list, she can do:</p>\n\n<pre><code>list_free(list_splitbefore(list));\n</code></pre>\n\n<p>Similarly, your counting and traversal functions have some redundancy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:55:50.867", "Id": "43674", "Score": "0", "body": "Wow, I can't believe I didn't check compiler warnings. I'll fix that up, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:16:09.610", "Id": "43679", "Score": "0", "body": "thanks, I will be following up on all your comments. One thing though - I don't see why *getnodetype* isn't justified by its use throughout the library (but maybe it will be after I follow up on your other points). Thanks again, I enjoyed reading your points and will be re-writing accordingly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:46:06.327", "Id": "43686", "Score": "0", "body": "I don't think there is any point where you use `getnodetype` where you couldn't just check for NULL or test the next/prev pointers and be simpler/clearer. Hence I think the function is not needed :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T13:26:42.033", "Id": "27995", "ParentId": "27979", "Score": "4" } } ]
{ "AcceptedAnswerId": "27995", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T05:13:17.397", "Id": "27979", "Score": "1", "Tags": [ "c", "linked-list" ], "Title": "Double Linked List Implementation Review" }
27979
<p>The entire flow depends on parameters. It's all in the same method with an <code>if</code>/<code>else</code>, but I want to make the code a bit more clear. How can I functionally decompose this method into many?</p> <pre><code>private void BindTreeView(IEnumerable&lt;Opcion&gt; OptionList, TreeNode parentNode) { var nodes = OptionList.Where(x =&gt; parentNode == null ? x.ParentID == 0 : x.ParentID == int.Parse(parentNode.Value)); if (_pagemode != BoPage.PageMode.View) { foreach (Opcion node in nodes) { TreeNode newNode = new TreeNode(); newNode.Text = (node.ParentID == 0) ? string.Format(@"&lt;span class=""Tema"" id=""Tema{0}""&gt;{1}&lt;/span&gt;", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@"&lt;span class=""SubTema""&gt;{1}&lt;/span&gt;", node.ParentID.ToString(), node.Descripcion.ToString()); newNode.Value = node.OpcionID.ToString(); newNode.ToolTip = node.Descripcion.ToString(); if (parentNode == null) { TreeViewPalabrasClaveOpciones.Nodes.Add(newNode); } else { if (node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0) { newNode.Checked = true; parentNode.Expand(); } parentNode.ChildNodes.Add(newNode); } BindTreeView(OptionList, newNode); } } else { foreach (Opcion node in nodes) { if (ExistKeyWord(node)) { TreeNode newNode = new TreeNode(); newNode.Text = (node.ParentID == 0) ? string.Format(@"&lt;span class=""Tema"" id=""Tema{0}""&gt;{1}&lt;/span&gt;", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@"&lt;span class=""SubTema""&gt;{1}&lt;/span&gt;", node.ParentID.ToString(), node.Descripcion.ToString()); newNode.Value = node.OpcionID.ToString(); newNode.ToolTip = node.Descripcion.ToString(); if (parentNode == null ) { TreeViewPalabrasClaveOpciones.Nodes.Add(newNode); } else { if (node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0) { newNode.Checked = true; parentNode.Expand(); } if (node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0) { parentNode.ChildNodes.Add(newNode); } } BindTreeView(OptionList, newNode); } } } } </code></pre>
[]
[ { "body": "<blockquote>\n <p>I want to make the code a bit more clear</p>\n</blockquote>\n\n<p>I would start by removing one of the <code>if</code> branches and customize the loop to do the job according to the parameters because both loop are nearly identical.</p>\n\n<p>You can create two helper variables for the conditions and act appropriately:</p>\n\n<pre><code>var canAddTreeNote = _pagemode != BoPage.PageMode.View || ExistKeyWord(node);\n\nif (!canAddTreeNote)\n{\n continue;\n}\n</code></pre>\n\n<p>and for adding child nodes something like this:</p>\n\n<pre><code>var canAddChildNote = \n _pagemode == BoPage.PageMode.View \n &amp;&amp; ExistKeyWord(node)\n &amp;&amp; node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0;\n\nif (canAddChildNote) \n{\n parentNode.ChildNodes.Add(newNode);\n}\n</code></pre>\n\n<p>by <em>their powers combined</em> you'll get:</p>\n\n<pre><code>private void BindTreeView(IEnumerable&lt;Opcion&gt; OptionList, TreeNode parentNode)\n{\n var nodes = OptionList.Where(x =&gt; parentNode == null ? x.ParentID == 0 : x.ParentID == int.Parse(parentNode.Value));\n\n\n foreach (Opcion node in nodes)\n {\n\n var canAddTreeNote = _pagemode != BoPage.PageMode.View || ExistKeyWord(node);\n\n if (!canAddTreeNote)\n {\n continue;\n }\n\n TreeNode newNode = new TreeNode();\n newNode.Text = (node.ParentID == 0) ? string.Format(@\"&lt;span class=\"\"Tema\"\" id=\"\"Tema{0}\"\"&gt;{1}&lt;/span&gt;\", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@\"&lt;span class=\"\"SubTema\"\"&gt;{1}&lt;/span&gt;\", node.ParentID.ToString(), node.Descripcion.ToString()); \n newNode.Value = node.OpcionID.ToString();\n newNode.ToolTip = node.Descripcion.ToString();\n\n if (parentNode == null)\n {\n TreeViewPalabrasClaveOpciones.Nodes.Add(newNode);\n }\n else\n {\n if (node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0)\n {\n newNode.Checked = true;\n parentNode.Expand();\n }\n\n var canAddChildNote = \n _pagemode == BoPage.PageMode.View \n &amp;&amp; ExistKeyWord(node)\n &amp;&amp; node.PalabrasClaveOpciones.Where(c =&gt; c.KeywordID == _idKeyWord).Count() &gt; 0;\n\n if (canAddChildNote) \n {\n parentNode.ChildNodes.Add(newNode);\n }\n }\n BindTreeView(OptionList, newNode); \n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>How can I functionally decompose this method into many?</p>\n</blockquote>\n\n<p>When you apply the above refactoring I think it's no longer necessary to create more methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-24T20:25:21.603", "Id": "108621", "ParentId": "27983", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T07:30:31.447", "Id": "27983", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Binding data to a TreeView" }
27983
<p>I am studying for a degree in "Bachelor of Engineering in Information and Communication Technologies." I am currently on vacation, just after we started learning C++ at the end of the semester. I wanted to be ahead of the next semester, so I decided to try to use these classes and to make a text-based game.</p> <p>I would like to know what I could do better. Should I remove or add some class functions? Should I do something differently, maybe not even related to classes?</p> <p><strong>Main.cpp</strong></p> <pre><code>#include "MobClass.h" #include "Player.h" #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace std; player battle(player account); player calcEXP(player account,classMob monster); player levelUp(player account); void death(); int main() { string name; int option1; cout &lt;&lt; "Welcome, please enter your name\n"; cin &gt;&gt; name; string location[4] = {"in a hole","in a cave","in the mauntains","in a castle"}; player account(name,location[0],1,0); cout &lt;&lt;"\nWelcome "&lt;&lt;account.getName() &lt;&lt; " you find your self " &lt;&lt; account.getArea() &lt;&lt; "\nand you are not sure how you ended up here\n"; while (1) { Sleep(500); cout &lt;&lt;"write 1 to walk forward or 2 to walk left or 3 to walk right\n"; cin &gt;&gt; option1; if (option1 &gt;=1 &amp;&amp; option1 &lt;=3) { Sleep(50*(option1)); srand(time(NULL)); if (rand() %3 == option1-1){ account = battle(account); } } else{ cout &lt;&lt; "\n#@#Error#@# Please enter a number between 1 and 3\n\n"; cin.clear(); cin.ignore(); } } return 0; } player battle(player account) { string option; string location[4] = {"in a hole","in a cave","in the mauntains","in a castle"}; string monsters[5][3] = {{"worm","lizard","snake"},{"rat","snake","trolls"},{"Dragon","Dragon","Dragon"},{"Evil knight","The mad king","Joffrey Baratheon"}}; Sleep(20); srand(time(NULL)); int ranM = (rand() % 3); //random monster int ranD = (rand() % 5)+1; //random diff classMob monster(monsters[account.getLevel()-1][ranM],account.getLevel(),account.getArea(),ranD); cout &lt;&lt;"Suddently you meet a "&lt;&lt; monster.getName() &lt;&lt;", be ready for battle" &lt;&lt; "\n"; Sleep(2000); do { cout &lt;&lt; "\n\n\n ######################################\nHP:"&lt;&lt; account.getHealth() &lt;&lt; " "&lt;&lt; monster.getName()&lt;&lt;"HP:"&lt;&lt;monster.getHealth()&lt;&lt;" difficulty:"&lt;&lt;monster.getDifficulty() &lt;&lt; "\n"; cout &lt;&lt; "Write A for attack or R for retreat" &lt;&lt; "\n"; cin &gt;&gt; option; srand(time(NULL)); if (option == "R" || option == "r") { if ((rand() % 2) == 1){ cout &lt;&lt; "retreat sucessfull" &lt;&lt; "\n"; monster.setHealth(0); } else{ cout &lt;&lt; "retreat failed, the monster get a free attack and you lose 5 health\n"; account.setHealth(account.getHealth()-5); option ="A"; } } if (option == "A" || option == "a") { int attack =rand()%(account.getDamage()); srand(time(NULL)); int mobAttack = rand()%(monster.getDamage()); monster.setHealth(monster.getHealth()-attack); account.setHealth(account.getHealth()-mobAttack); cout &lt;&lt; "you attack the monster for " &lt;&lt; attack &lt;&lt; " damage\n"; Sleep(500); cout &lt;&lt; "the monster counter attacks for " &lt;&lt; mobAttack &lt;&lt; " damage\n"; Sleep(500); } } while (monster.getHealth() &gt;0 &amp;&amp; account.getHealth() &gt; 0); cout &lt;&lt; "\n\n\n ######################################\nHP:"&lt;&lt; account.getHealth() &lt;&lt; " "&lt;&lt; monster.getName()&lt;&lt;"HP:"&lt;&lt;monster.getHealth()&lt;&lt;" difficulty:"&lt;&lt;monster.getDifficulty() &lt;&lt; "\n"; if (account.getHealth() &lt;= 0) { death(); exit(0); } account = calcEXP(account,monster); return account; } void death() { cout &lt;&lt; "Sorry you failed your epic quest\n"; } player calcEXP(player account,classMob monster) { cout &lt;&lt; "#########\ncalculating EXP\n#########\n"; Sleep(500); account.setEXP(account.getEXP() + monster.getEXP()); cout &lt;&lt; "EXP: " &lt;&lt;account.getEXP() &lt;&lt; "/" &lt;&lt; account.getEXPReq() &lt;&lt; "\n"; if (account.getEXP() &gt;= account.getEXPReq()) { levelUp(account); } return account; } player levelUp(player account) { account.setLevel(account.getLevel()+1); account.setEXPReq(); account.setMaxHealth(); account.setHealth(account.getMaxHealth()); cout &lt;&lt; "Level up! you are now level: " &lt;&lt; account.getLevel() &lt;&lt; "!\n"; return account; } </code></pre> <p><strong>Player.h</strong></p> <pre><code>#include &lt;string&gt; class player { public: player(std::string,std::string,int,int); void setName(std::string); void setArea(std::string); void setLevel(int); void setEXP(double); void setHealth(double); void setMaxHealth(); void setDamage(); std::string getName(); std::string getArea(); int getLevel(); double getHealth(); double getMaxHealth(); int getDamage(); int getEXP(); void setEXP(int); int getEXPReq(); void setEXPReq(); private: std::string playerName; std::string playerArea; int playerLevel; double playerHealth; double playerMaxHealth; int playerDamage; int EXP; int EXPReq; }; </code></pre> <p><strong>player.cpp</strong></p> <pre><code>#include &lt;string&gt; #include "Player.h" player::player(std::string name,std::string area,int level = 1,int EXP = 0) { setName(name); setArea(area); setLevel(level); setEXP(EXP); setMaxHealth(); setHealth(playerMaxHealth); setDamage(); setEXPReq(); } void player::setName(std::string name) { playerName = name; } void player::setArea(std::string area) { playerArea = area; } void player::setLevel(int level) { playerLevel = level; } void player::setHealth(double health) { playerHealth = health; } void player::setMaxHealth() { playerMaxHealth = (100 * getLevel()); } void player::setDamage() { playerDamage = (30 * getLevel()); } std::string player::getName() { return playerName; } std::string player::getArea() { return playerArea; } int player::getLevel() { return playerLevel; } double player::getHealth() { return playerHealth; } double player::getMaxHealth() { return playerMaxHealth; } int player::getDamage() { return playerDamage; } int player::getEXP() { return EXP; } void player::setEXP(int _EXP) { EXP = _EXP; } int player::getEXPReq() { return EXPReq; } void player::setEXPReq() { EXPReq = 70+((getLevel()*getLevel())*35); } </code></pre> <p><strong>mobclass.h</strong></p> <pre><code>#include &lt;string&gt; class classMob { public: classMob(std::string,int,std::string,int); // name,lvl,area,difficulty void setName(std::string); void setLevel(int); void setArea(std::string); void setDamage(); void setHealth(double); void setMaxHealth(); void setDifficulty(int); std::string getName(); int getLevel(); std::string getArea(); int getDamage(); double getHealth(); double getMaxHealth(); int getDifficulty(); int getEXP(); void setEXP(); private: std::string mobName; std::string mobArea; int mobLevel; int mobDamage; double mobHealth; double mobMaxHealth; int mobDifficulty; int EXP; }; </code></pre> <p><strong>mobclass.cpp</strong></p> <pre><code>#include &lt;string&gt; #include "MobClass.h" classMob::classMob(std::string name,int lvl,std::string area,int difficulty) { setName(name); setLevel(lvl); setArea(area); setDifficulty(difficulty); setDamage(); setMaxHealth(); setHealth(mobMaxHealth); setEXP(); } void classMob::setName(std::string name) { mobName = name; } void classMob::setLevel(int level) { mobLevel = level; } void classMob::setArea(std::string area) { mobArea = area; } void classMob::setDifficulty(int difficulty) { mobDifficulty = difficulty; } void classMob::setDamage() { mobDamage = (3 *( getLevel())+((getDifficulty()*getLevel())/2)); } void classMob::setHealth(double health) { mobHealth = health; } void classMob::setMaxHealth() { mobMaxHealth = (15 *(getDifficulty() + getLevel())); } std::string classMob::getName() { return mobName; } int classMob::getLevel() { return mobLevel; } std::string classMob::getArea() { return mobArea; } int classMob::getDifficulty() { return mobDifficulty; } int classMob::getDamage() { return mobDamage; } double classMob::getHealth() { return mobHealth; } double classMob::getMaxHealth() { return mobMaxHealth; } int classMob::getEXP() { return EXP; } void classMob::setEXP() { EXP = (getLevel() * 35); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T11:40:02.227", "Id": "43650", "Score": "1", "body": "Without commenting the code (yet), the first paragraph would read more easily as \"I am studying for a degree of \"Bachelor of Engineering in Information and Communication Technologies\", currently on vacation, just after we started learning C++ at the end of the semester. I wanted to be ahead of the next semester so I decided to try to use these classes and to made a text based game.\" (Yet SE does not let me perform this edit?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T14:49:05.373", "Id": "43655", "Score": "0", "body": "Ok, yea it sounds better / properly is more correct that way. Changed it! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T04:52:30.173", "Id": "43724", "Score": "0", "body": "Initializing srand(): http://stackoverflow.com/a/322995/14065" } ]
[ { "body": "<p>For the classes, the get functions could have a const keyword in their prototype since they aren't supposed to change any value. That will just make it impossible for them to do so and will make it possible to use them in other const functions.</p>\n\n<p>In the .h</p>\n\n<pre><code>int getDamage() const;\n</code></pre>\n\n<p>In the .cpp</p>\n\n<pre><code>int player::getDamage() const {...}\n</code></pre>\n\n<p>Also, the get and maybe even set functions could be declared inline, placed at the end of the .h file, to avoid function calls. Inline functions are not compiled as functions. Instead, the body of the function kind of replaces the function call when compiled, similar to Macros. This way, on runtime, there's no actual function call. It's perfect when returning values.</p>\n\n<p>In the class declaration:</p>\n\n<pre><code>class player\n{\npublic:\n int getDamage() const;\n}\n</code></pre>\n\n<p>In the .h after the class declaration:</p>\n\n<pre><code>inline int player::getDamage() const {return damage;}\n</code></pre>\n\n<p>For the constructor, instead of calling the set functions, you could add the values before the function body:</p>\n\n<pre><code>classMob::classMob(std::string name,int lvl,std::string area,int difficulty)\n: mobName(name), mobLevel(lvl), mobArea(area), mobDifficulty(difficulty)\n{\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T14:59:21.350", "Id": "43657", "Score": "0", "body": "Ok I changed the get functions to have a const keyword in their prototype. I changed the get and set functions to be declared inline, witch results in I can clear almost all of my player.cpp file and my Mobclass.cpp file. I just want to be sure I am doing it the right way: \nvoid setEXP(){EXP = (getLevel() * 35);}; \nand\nconst int getLevel(){return mobLevel;};\nSo was it like that you ment?\nFinaly I changed the constructors and I didnt know you could do that, but i didn't change all of it as i still needed some of the functions(setDamage,setMaxHealth,etc) as those doesnt take a parameter right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T15:01:41.830", "Id": "43658", "Score": "0", "body": "also thank you so much for the feedback! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T16:02:18.450", "Id": "43665", "Score": "0", "body": "The const keyword has to go at the end of the prototype to declare a function as const, otherwise you declare that the return type will be a const. As for the inline, it's like a function with the inline keyword at the beginning of the prototype, but instead of being placed in the .cpp, it's placed in the .h, outside of the class scope. Finally, I said you could almost even put the set functions inline because I think some of them have only a single operation. If you have getLevel() * 35, you have more than one operation in the line." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T13:42:26.713", "Id": "27996", "ParentId": "27986", "Score": "3" } }, { "body": "<ul>\n<li><p>Try not to get in the habit of using <code>using namespace std</code>. Read <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a> for more information.</p></li>\n<li><p>For clarity, have your <code>#include</code>s organized. Read <a href=\"http://blog.knatten.org/2010/07/01/the-order-of-include-directives-matter/\" rel=\"nofollow noreferrer\">this blog post</a> or <a href=\"https://stackoverflow.com/questions/2762568/c-c-include-file-order-best-practices\">this answer</a> for more information.</p></li>\n<li><p>Add a newline between each section of code. For instance, separate all user input and loops. For variables, it's best to initialize them late as late as possible in case the function needs to terminate prematurely. Again, keep them with the corresponding code.</p></li>\n<li><p><code>mobclass.h</code> already includes <code>&lt;string&gt;</code>, so you don't need to include it again in the .cpp file.</p></li>\n<li><p>You have a lot of accessors and mutators. Since these are short one-line implementations, you can define them in the header like this:</p>\n\n<pre><code>void setEXP() {EXP = (getlevel() * 35;}\nint getEXP() const {return EXP;}\n</code></pre>\n\n<p>As such, you will no longer need to implement these in the .cpp file. When they're in the header, they'll automatically be <code>inline</code>. It should also make it easier if you ever need to implement newer functions. In the header, you could also keep the accessors and mutators together for clarity.</p></li>\n<li><p>I like what @Kaivo Anastetiks said about <code>classMob</code>'s constructor, but I would like to add on that a bit. You have a few options for this:</p>\n\n<ol>\n<li>keep it in the .cpp file (with those changes)</li>\n<li>put it in the header (with the <code>classMob::</code> part removed)</li>\n<li>put it under the class declaration in the same file</li>\n</ol></li>\n<li><p>It's better to use <code>getline()</code> instead of <code>cin</code> for getting an <code>std::string</code> value from the user:</p>\n\n<pre><code>getline(std::cin, name);\n</code></pre></li>\n<li><p><code>srand()</code> should ONLY be called ONCE in the program, preferably at the top of <code>main()</code>. If you keep it as is, <code>rand()</code> will be \"not-so-random\" because the seed will keep resetting to 0.</p></li>\n<li><p>That really long output line in <code>battle()</code>'s do-while loop could be wrapped so that it doesn't extend out that far.</p></li>\n<li><p>For <code>death()</code>: there's no need to have a function <em>just</em> output a message. Either have it do something else relevant, or just remove it.</p></li>\n<li><p>For the player's death (in general): I would prefer the function to fall back to <code>main()</code> instead of explicitly exiting. This is because:</p>\n\n<ol>\n<li>it's clearer to let <code>main()</code> terminate the program whenever possible</li>\n<li>it could be hard to tell where the player's death is determined</li>\n</ol>\n\n<p>You would then need to change <code>main()</code>'s loop to handle this. You could even have <code>battle()</code> return a <code>bool</code> to indicate the battle outcome (the player has won or has lost). Try this at the end:</p>\n\n<pre><code>account = calcEXP(account, monster);\n\nif (account.getHealth() &lt;= 0)\n return false;\n\nreturn true;\n</code></pre>\n\n<p>You could even create a <code>bool</code> member function for determining if the player's health was depleted:</p>\n\n<pre><code>bool healthDepleted() const {return playerHealth &lt;= 0;}\n</code></pre></li>\n<li><p>If you're just mutating data members in <code>calcEXP()</code> and <code>levelUp()</code>, they don't need to return anything. Just make those functions <code>void</code>.</p></li>\n<li><p>Your \"saving\" problem is due to your functions receiving the objects <em>by value</em>. It should be received <em>by reference</em> instead. You were only passing in a copy and modifying it, only to have those changes discarded each time those functions ended. This change will allow you to modify the original objects:</p>\n\n<pre><code>bool battle(player &amp;account);\nvoid calcEXP(player &amp;account, classMob &amp;monster);\n</code></pre></li>\n<li><p>After looking at <code>mobClass</code>'s definition, it appears that you may not need those mutators. You should consider a <code>mobClass</code> instance as an <em>individual</em> monster, just as a <code>player</code> is just <em>one</em> player. As such, you just need to construct each <code>mobClass</code> once with the default stats. The accessors are still okay.</p></li>\n<li><p>Once again, I forgot about this: create a <code>Game</code> class. Since the human player doesn't need to know how the game's internal mechanisms work, you would no longer need those extra functions in the driver. Instead, <code>main()</code> will create a <code>Game</code> and the class will handle the rest. Here's (roughly) what <code>main()</code> could look like:</p>\n\n<pre><code>int main()\n{\n std::srand(std::time(NULL));\n\n Game game;\n game.play();\n}\n</code></pre>\n\n<p>That may be <em>too</em> little for <code>main()</code>, but the idea is that <code>Game</code> will handle everything. Every function in <code>Game</code>, except for <code>play()</code>, should be <code>private</code>. <code>Game</code> should contain a <code>player</code> as a data member and instantiated in <code>Game</code>'s constructor. If you end up implementing your map idea (or anything similar), that would be instantiated in the constructor as well. You may still keep those extra driver functions, but they should be called in <code>play()</code> instead.</p>\n\n<p>As for <code>classMob</code>, you could create an <code>std::vector</code> of objects (you cannot predict how many monsters will \"spawn\" before the player dies). New monsters would be added and, when killed by the player, removed. If you maintain a counter, you could even track the number of monsters killed before defeat.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:36:58.883", "Id": "43669", "Score": "7", "body": "\"[K]eep all variable initializations at the top of the function\" -- I disagree. Variables should be declared as late as possible. This avoids unnecessary instantiation in case of exceptions or `return`s, and keeps them closer to the relevant context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:41:30.390", "Id": "43670", "Score": "3", "body": "Regarding `#include` order: The recommended order is **1.** Include yourself (i.e. corresponding `.hpp` file from a `.cpp` file). **2.** Include other headers you have created yourself. **3a.** Include other `\"\"`-style headers. **3b.** Include non-std-lib `<>`-headers. **4.** Include standard library headers. Each section should be in alphabetical order. See [this blog post](http://blog.knatten.org/2010/07/01/the-order-of-include-directives-matter/) for an explanation, or [this answer](http://stackoverflow.com/questions/2762568/c-c-include-file-order-best-practices)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:45:07.113", "Id": "43671", "Score": "0", "body": "What do you mean by \"It should also make it easier if you ever need to implement longer functions\"? Then you would have to move them back to the implementation file. Or am I misunderstanding something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:52:33.443", "Id": "43672", "Score": "0", "body": "I meant for new functions (not the same assessors and mutators). I'll clarify that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:53:47.527", "Id": "43673", "Score": "0", "body": "I'll clarify the variable thing as well. You are right, but I was going back to the separation thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:56:29.230", "Id": "43675", "Score": "1", "body": "The rest looks good. I think you mean \"`srand()` should only be **called** once\", by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:21:17.377", "Id": "43680", "Score": "0", "body": "Oh alright, this line: void setEXP() const {EXP = (getlevel() * 35}; was I just told wouldnt be that smart to do(because it has more then one operation), also changed it to be inline instead(as requested below as it seems to be smarter :) ).I was wondering why i got so unrandom mobs, but it works alot better after i removed those srand() so now its only in main. The reason to i have return values on calcEXP and levelUp() is to \"save the information(I tried earlier to have it as a void function but it wouldnt save the new XP, it is the same for the function battle, as it just returns account." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:26:31.943", "Id": "43682", "Score": "0", "body": "Great feedback though, alot to work on. I got one question though. In my code i have this line \"if (option1 >=1 && option1 <=3)\" \nbut if i type something like the charter A it obviously gives an error to the cin function. If this happends(if it is not between 1 and 3) then it clears the cin function but this does not seem to work as it doesnt wait on an input from the user but just keep spamming :\"write 1 to walk forward or 2 to walk left or 3 to walk right\\n\" Can you tell me why this is ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:27:13.983", "Id": "43683", "Score": "0", "body": "I added an extra note about `inline` in the header. As for the account, it should be \"saved\" into the program as long as you're properly updating the data members AND using the same objects. That's just a part of using classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:30:50.890", "Id": "43684", "Score": "0", "body": "That is because the `std::cin` is expecting an `int`, but receives a `char` instead. `std::cin` is not safe for dealing with such input because it is not designed to handle exceptions. You would then need to call `std::cin.ignore()` each time to disregard that `char` for the next input. Either way, it just puts unnecessary data into the stream." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:40:53.060", "Id": "43685", "Score": "0", "body": "Oh I will try with getline() instead and see how that works. also you write void setEXP() const {EXP = (getlevel() * 35;} but should there be a const there ? as the function does change a value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:49:08.473", "Id": "43687", "Score": "0", "body": "Oh yes, you're right. I thought through this too quickly. `Const` is not for mutators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:55:31.897", "Id": "43689", "Score": "0", "body": "Also does it mean that i can call the function battle with no argument? as it should know it out from the object or should i still have it as a parameter? oh yea I have seen the button but i just try to get as much input as possible, will choose the best answer tomorrow(right now yours is the best yea :) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:00:14.770", "Id": "43690", "Score": "1", "body": "It would still need the `player` object as an argument. Speaking of which, I found your \"saving\" problem. I'll update this answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:23:58.303", "Id": "43691", "Score": "0", "body": "Ah yea forgot it only made a copy, thanks! I removed the death function and made battle to bool now and made it like this in main instead\n\"if (battle(account) == true)\n{\n std::cout<<\"You died\\n\";\n return 0;}\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:34:38.090", "Id": "43692", "Score": "0", "body": "Just to nit-pick a bit: I'd rename the `player` object as \"player1\" or something like that. The object is already sort of an \"account\" for the player, so it doesn't need to be named like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:35:20.470", "Id": "43693", "Score": "0", "body": "Oh one question not related that much to the code, but why is it that the command Sleep has to start with a capital S, I thought as standard programming you stated fuctions and variables with a lower case first letter? There might not be a reason I am just curious" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:36:40.257", "Id": "43694", "Score": "0", "body": "Oh when you say player you mean account don't you ? as it is the class with the name player? \n\nBecause yes it does make more sence to call it account1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:43:07.237", "Id": "43696", "Score": "1", "body": "The name `player` for the `class` describes the properties of an _instance_ of said class, which is your object. In this game, you only have one player. Yes, you could still say `account1`, but the naming really is up to you. I'm just trying to relate this to an actual video game (like Zelda). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:49:03.283", "Id": "43697", "Score": "1", "body": "That's just how it's defined in the STL under `Windows`. Not everything in there is written under common naming conventions (at least the way it's taught to us), but I'm sure there are reasons for that. With the `string` class, for instance, I assume it's lowercase because it's written as a user-defined data type (native data types, such as `int`, are always lowercase)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:35:25.637", "Id": "43702", "Score": "0", "body": "I was thinking about maybe adding a map as the next thing to the game maybe as a 3 dimensional array(or maybe 4: 1th for the map area,2nd for the x,3th for y, and 4th for the name of the map) but would this be the smartest way? i was thinking about maybe adding something to the class player or maybe a whole new class for the map but not sure if that would be \"smart\" ?\nThanks for all your help up till now so I gave you the accepted answer, hope you will keep helping me a bit more :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:43:54.773", "Id": "43703", "Score": "1", "body": "I'm honestly not sure how to go about this myself. If you don't get any more answer here, you can attempt this and then post another question if you want it reviewed (as long as you're not reporting on errors). I will say this in general: the STL is your friend. If you can implement this without using C-style arrays, more power to you. Moreover, I'll add more to this answer if I can. Again, you're welcome to start another post after you've made all of your changes and/or want feedback for something more specific." } ], "meta_data": { "CommentCount": "22", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:21:26.967", "Id": "28000", "ParentId": "27986", "Score": "16" } }, { "body": "<p>Your classes are designed badly:</p>\n<pre><code>class player\n{\npublic:\n player(std::string,std::string,int,int);\n void setName(std::string);\n void setArea(std::string);\n void setLevel(int);\n void setEXP(double);\n void setHealth(double);\n void setMaxHealth();\n void setDamage();\n std::string getName();\n std::string getArea();\n int getLevel();\n double getHealth();\n double getMaxHealth();\n int getDamage();\n int getEXP();\n void setEXP(int);\n int getEXPReq();\n void setEXPReq();\nprivate:\n std::string playerName;\n std::string playerArea;\n int playerLevel;\n double playerHealth;\n double playerMaxHealth;\n int playerDamage;\n int EXP;\n int EXPReq;\n};\n</code></pre>\n<p>You are exposing all the internal members (they just happen to be behind shallow get/set functions). But you are tightly coupling your class to the actual types you use for storage. This tight coupling makes your code very brittle; any change is going to ripple through your code requiring any code that uses your class to also change.</p>\n<p>Your class methods should be &quot;VERBS&quot; that describe actions that happen on your obeject (thus not exposing the internal types).</p>\n<p>Example Leveling up:<br />\nThe only reason you have a bunch of these getters is so that an external function can get update then update the value.</p>\n<pre><code>player levelUp(player account)\n{\n account.setLevel(account.getLevel()+1);\n account.setEXPReq();\n account.setMaxHealth();\n account.setHealth(account.getMaxHealth());\n cout &lt;&lt; &quot;Level up! you are now level: &quot; &lt;&lt; account.getLevel() &lt;&lt; &quot;!\\n&quot;;\n return account;\n}\n</code></pre>\n<p>The problem here is that you loose control of leveling up. With this technique anybody can write an alternative way of leveling up. Then if things change you need to find and modify all the techniques when you change how leveling up is done.</p>\n<p>This should all be part of the player class that way leveling up is controlled as part of the player. It is done in one place (and only one place):</p>\n<pre><code>player Player::levelUp()\n{\n playerLevel++;\n EXPReq = 70 + (playerLevel * playerLevel) * 35;\n playerMaxHealth = 100 * playerLevel;\n playerHealth = playerMaxHealth;\n\n cout &lt;&lt; &quot;Level up! you are now level: &quot; &lt;&lt; account.getLevel() &lt;&lt; &quot;!\\n&quot;;\n}\n</code></pre>\n<p>You can basically remove all the getter/setter methods and put in methods that actual manipulate the object.</p>\n<h3>Edit Based on Comment:</h3>\n<blockquote>\n<p>hm I am getting one problem though, so in the function calcEXP I am using monster.getEXP(); and i know that in the function battle I use some of the get functions to get information about the classMob class. How can i acess this without the use of get functions ?</p>\n</blockquote>\n<p>Couple of ways. But I think the simplest is to make a common base class that handles this stuff:</p>\n<pre><code> class LifeForm\n {\n // Traits that are common to both players and monsters.\n int EXP;\n int EXPReq;\n\n void levelUp() {}\n public:\n void hasKilled(LifeForm const&amp; deadLifeForm)\n {\n // Absorb the experience of the foe.\n EXP += deadLifeForm.EXP;\n\n if (EXP &gt;= EXPReq)\n {\n levelUp();\n }\n }\n \n \n };\n\n class Person: public LifeForm\n {\n };\n\n class Monster: public LifeForm\n {\n };\n</code></pre>\n<p>The <code>LifeForm</code> class understands the concept of experience (maybe other stuff) and handles the interaction between two lifeforms. Since an object has access to the private members of other objects of the same class it works fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T10:53:37.393", "Id": "43731", "Score": "0", "body": "Ah I see, I will start changing this. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T11:12:52.547", "Id": "43732", "Score": "0", "body": "ehm I am getting one problem though, so in the function calcEXP I am using monster.getEXP(); and i know that in the function battle I use some of the get functions to get information about the classMob class. How can i acess this without the use of get functions ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:25:42.243", "Id": "43741", "Score": "0", "body": "@Sumsar1812: See update" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:30:36.493", "Id": "43742", "Score": "0", "body": "@LokiAstari: Thank you for posting this update before I had the slightest idea of mentioning `friend`. I really need to learn how to use inheritance in my own code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:34:36.750", "Id": "43744", "Score": "0", "body": "@Jamal: friend is another valid technique." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:38:35.353", "Id": "43745", "Score": "0", "body": "@LokiAstari: I keep hearing things about `friend` like 1.) it's bad for encapsulation and 2.) it should only be used when absolutely necessary. I'm still using it in my code, but it feels... too easy to use. What are the pros/cons of inheritance and `friend`? You may just point me to a good post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:32:14.270", "Id": "43749", "Score": "1", "body": "@Jamal: If used incorrectly any functionality is bad. But used correctly `friend` increases (ie is good for) encapsulation (at the cost of tight coupling). See http://programmers.stackexchange.com/a/99595/12917" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:49:44.760", "Id": "43751", "Score": "0", "body": "@LokiAstari: I may eventually post a snippet of another program pertaining to this very issue. It uses a Game `class`, and I've never had such a `class` reviewed before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T21:39:39.973", "Id": "43755", "Score": "0", "body": "I must be honest this is very confusing. so is this called \"inheritance \" ? If so,it might take some time before i fully understand it(as I have never worked with inheritance before ) and come back with feedback(properly first tomorrow)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T21:55:11.813", "Id": "43756", "Score": "0", "body": "Hmm now it might just be me not understanding this right but shouldn't \"void hasKilled(LifeForm const& deadLifeForm)\" not be with the monster class instead of the LifeForm class? as another thing to make it a bit easier for my self I changed the EXP names to be playerEXP and PlayerEXPReq and mobEXP" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T23:25:30.083", "Id": "43765", "Score": "0", "body": "@Sumsar1812: Don't monsters gain experience from killing players?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T23:25:49.740", "Id": "43766", "Score": "0", "body": "@Sumsar1812: Yes this is inheritance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T23:26:47.247", "Id": "43767", "Score": "0", "body": "@Sumsar1812: Its not the only way of doing it just a suggestion of one way. friendship would be another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T00:14:42.390", "Id": "43770", "Score": "0", "body": "@LokiAstari No monsters does not get experience from killing players ;) And no I kinda want to use this methode as I have to learn to use it one way or another" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T05:29:48.147", "Id": "28025", "ParentId": "27986", "Score": "8" } }, { "body": "<p>First off, decide whether, and to what degree, you want object orientedness.</p>\n\n<p>If you want to keep the current design, you may want to use structs rather than classes. At the moment this isn't very object-oriented at all, and getting rid of the need for getters and setters for everyfreakingthing would reduce the amount of code by like 2/3. Making something private and adding a getter and setter that just blindly set the variable...that's not encapsulation. That's busywork. You're not really protecting anything, you end up having to declare and define the getter/setter, and you turn <code>player.health -= 10;</code> into <code>player.setHealth(player.getHealth() - 10);</code>, which is harder to read. :P</p>\n\n<p>If you want to be more object-oriented about all this, the first thing to do is let the classes take more responsibility for their own internal state. As many as possible of the actions that involve modifying player attributes, should be in the <code>player</code> class. Same with monster attributes and <code>classMob</code>, of course.</p>\n\n<p>Consider your current fight logic:</p>\n\n<pre><code>player battle(player account) {\n ...\n do {\n ...\n if (option == \"A\" || option == \"a\")\n {\n int attack =rand()%(account.getDamage());\n srand(time(NULL));\n int mobAttack = rand()%(monster.getDamage());\n monster.setHealth(monster.getHealth()-attack);\n account.setHealth(account.getHealth()-mobAttack);\n cout &lt;&lt; \"you attack the monster for \" &lt;&lt; attack &lt;&lt; \" damage\\n\";\n Sleep(500);\n cout &lt;&lt; \"the monster counter attacks for \" &lt;&lt; mobAttack &lt;&lt; \" damage\\n\";\n Sleep(500);\n }\n } while (monster.getHealth() &gt;0 &amp;&amp; account.getHealth() &gt; 0);\n\n ...\n\n if (account.getHealth() &lt;= 0)\n {\n death();\n exit(0);\n }\n\n ...\n\n return account;\n}\n</code></pre>\n\n<p>A huge amount of this is stuff that <code>classMob</code> and <code>player</code> could be handling. You could easily have something like </p>\n\n<pre><code>int player::attack(classMob&amp; mob) {\n int attack = rand() % damage;\n mob.takeDamage(attack);\n return attack;\n}\n\nvoid player::takeDamage(int damage) {\n health -= damage;\n if (health &lt; 0) health = 0;\n}\n\nbool player::isAlive() { return health &gt; 0; }\n\n\n\nint classMob::attack(player&amp; p) {\n int attack = rand() % damage;\n p.takeDamage(attack);\n return attack;\n}\n\nvoid classMob::takeDamage(int damage) {\n health -= damage;\n if (health &lt; 0) { health = 0; }\n}\n\nbool classMob::isAlive() { return health &gt; 0; }\n</code></pre>\n\n<p>Now your player and mob can attack each other, and the above main-manages-the-attack code turns into</p>\n\n<pre><code>player battle(player account) {\n ...\n do {\n ...\n if (option == \"A\" || option == \"a\")\n {\n int attack = account.attack(monster);\n cout &lt;&lt; \"you attack the monster for \" &lt;&lt; attack &lt;&lt; \" damage\\n\";\n Sleep(500);\n\n int mobAttack = monster.attack(account);\n cout &lt;&lt; \"the monster counter attacks for \" &lt;&lt; mobAttack &lt;&lt; \" damage\\n\";\n Sleep(500);\n }\n } while (monster.isAlive() &amp;&amp; account.isAlive());\n\n ... show status lines again ...\n\n if ( !account.isAlive() )\n {\n death();\n exit(0);\n }\n\n ...\n}\n</code></pre>\n\n<p>(By the way, if we take a look, we will see that monsters and players attack each other in the same way. In fact, they share a whole lot of the same attributes. It's starting to look like <code>classMob</code> and <code>player</code> should have a common ancestor, at least.)</p>\n\n<p>It might not look that much better, and as of yet, it's still not great. But you gain a few things by giving players and mobs some autonomy:</p>\n\n<ul>\n<li><p>Clarity. When you want a mob to attack, you don't have to set the player's health to some lower amount determined by the mob's damage. You just <em>tell it to attack</em>. The resulting code is much more self-descriptive, which makes it much easier to follow.</p></li>\n<li><p>Scalability. Eventually, you're going to want to add features -- like, say, health potions. Or spiffy weapons that increase the damage dealt. Or debuffs that occasionally make you or the mob miss a turn. If you leave the classes dumb and keep <code>main</code> doing all the manipulation, there will be a point where it's too painful to add more stuff.</p>\n\n<p>With OOP done right, on the other hand, you get stuff done by telling an object to do something -- which often causes it to give orders to another object, which causes that other object to send messages to a bunch of others, and so on. The work's spread out, much more granular, and thanks to polymorphism, hot-swappable -- you can change the program's behavior on the fly by simply replacing some object with a compatible one that does things the way you want it to.</p></li>\n</ul>\n\n<hr>\n\n<p>As far as the game goes, you might want to change how fleeing works. Right now, if i run away from a fight, the monster dies? And i get as much EXP as if i had stayed and killed it? Something's not right about that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T01:16:03.277", "Id": "28065", "ParentId": "27986", "Score": "7" } } ]
{ "AcceptedAnswerId": "28000", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T10:46:25.100", "Id": "27986", "Score": "12", "Tags": [ "c++", "game", "classes", "adventure-game" ], "Title": "Text-based RPG game using classes" }
27986
<p>I've written the following Python class that fetches <em>iptables</em> rules using basic string processing in Linux. Am I doing this in the correct manner? I've tested the code and it's running fine.</p> <p>I'm ultimately going to use this class in a GUI app that I'm going to write using Python + GObject.</p> <pre><code>#!/usr/bin/python import sys, subprocess class Fwall: currchain="" dichains={'INPUT':[],'OUTPUT':[],'FORWARD':[]} dipolicy=dict(INPUT=True,OUTPUT=True,FORWARD=True) dicolumns={} def __init__(self): self.getrules() self.printrules() print "class initialized." def getrules(self): s = subprocess.check_output("iptables --list --verbose",shell=True,stderr=subprocess.STDOUT)#.split('\n') print s for line in s.splitlines(): if len(line)&gt;0: self.parseline(line) def parseline(self,line): line=line.strip() if line.startswith("Chain"): #this is the primary header line. self.currchain=line.split(' ')[1] allowed=not line.split('policy ')[1].startswith('DROP') self.dipolicy[self.currchain]=allowed #print "curr chain set to " + self.currchain else: items=line.split() if line.strip().startswith('pkts'): #this is the secondary header line, so fetch columns. if len(self.dicolumns)==0: for i,item in enumerate(items): if len(item)&gt;0: self.dicolumns.setdefault(item,i) #print self.dicolumns else: return else: ditemp={} #print line self.dichains[self.currchain].append(ditemp) for k,v in self.dicolumns.iteritems(): #idx= self.dicolumns[item]#,items[item] ditemp.setdefault(k,items[v]) #print line #print k,v #print k,items[v]#,idx def printrules(self): for k,v in self.dichains.iteritems(): print k litemp=self.dichains[k] for item in litemp: print item if __name__=="__main__": f=Fwall() </code></pre>
[]
[ { "body": "<p>This is not maybe a place for such suggestions, but why are you reinventing the wheel? There is already the library intended to do that:\n<a href=\"http://ldx.github.io/python-iptables/\" rel=\"nofollow\">python-iptables</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:05:52.773", "Id": "43700", "Score": "0", "body": "Sometimes, for learning something new, we have to reinvent the wheel!! If you think about it, almost everything you can think of is already coded someplace. I intend to gain mastery over python by these exercises." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T08:30:44.110", "Id": "43786", "Score": "0", "body": "There are better ways to improve your Pythonistas skills, and I think that parsing the output of `iptables` commands isn't worth taking it onto the board. It will learn you bad, unsecure habits in programming, that should be avoided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:05:52.573", "Id": "43816", "Score": "0", "body": "I want to create a router-cum-firewall type of app (such as ufw), Is python-iptables module flexible enough to handle that?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:47:20.743", "Id": "28008", "ParentId": "27987", "Score": "2" } }, { "body": "<p>There are violations of <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP-8</a> throughout and there are no <a href=\"http://www.python.org/dev/peps/pep-0257/\">PEP-257 docstrings</a>. It sounds petty, but these mean the difference between an easy read and a hard one.</p>\n\n<p>The class name <code>Fwall</code> is terrible, if you mean <code>Firewall</code> call it that. If you mean that it is a container of <code>FirewallRules</code> then say so. Names are extremely important.</p>\n\n<p>If <code>getrules()</code> is not part of the public class interface, convention suggests naming it <code>_getrules</code> which tells the reader that it is expected to be used only by the class itself. Having <code>print</code> statements is fine for debugging, but a well behaved library should assume that there is no stdout and return lists of strings in production code.</p>\n\n<p>Long lines are hard to read, especially on StackExchange. Fortunately, splitting within parenthesis is natural and preferred, thus:</p>\n\n<pre><code>s = subprocess.check_output(\"iptables --list --verbose\",\n shell=True, stderr=subprocess.STDOUT)\n</code></pre>\n\n<p>but sticking a comment marker in code will certainly cause misreadings. Where you have</p>\n\n<pre><code>s = subprocess.check_output(...)#.split('\\n')\n</code></pre>\n\n<p>you should drop the <code>#.split('\\n')</code>. Also, following PEP-8, put spaces after argument separating commas.</p>\n\n<p>You use <code>iteritems()</code> unnecessarily as the standard iteration behavior of a dictionary is now assumed. Where you have <code>for k,v in self.dicolumns.iteritems():</code> the line</p>\n\n<pre><code>for k, v in self.dicolumns:\n</code></pre>\n\n<p>is equivalent. To bang on the \"names are important\" drum, every dictionary has <code>k</code> and <code>v</code>, using more descriptive names would tell me what the meaning of the keys and values are. For that matter I have no idea was a <code>dipolicy</code> or <code>dicolumns</code> are, they might be related or parallel lists but I don't know. You tend to use <code>if len(item)==0</code> when <code>if item</code> means the same thing.</p>\n\n<p>I had to edit your entry because the class methods were not properly indented; this usually means that you are using a mix of tabs and spaces. Tell your editor to forget that the TAB character exists and to use only spaces, there are instructions for most editors on how to make it pretend that the TAB key behaves like you expect without putting literal <code>\\t</code> characters in your source code.</p>\n\n<p>The structure of <code>parseline()</code> is so deeply nested and has so many return points and un-elsed ifs that I really can't follow the logic of it. Read <a href=\"http://www.python.org/dev/peps/pep-0020/\">The Zen of Python</a> and keep it wholly.</p>\n\n<p>Finally, iptables is notoriously hairy. I strongly suggest that you use <a href=\"http://ldx.github.io/python-iptables/\">python-iptables</a> or at least study its class structure. You might also want to look at <a href=\"http://en.wikipedia.org/wiki/Uncomplicated_Firewall\">Uncomplicated Firewall</a> as it is designed to abstract iptables into something most humans can understand. It doesn't handle all possible uses, but it makes the typical cases comprehensible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:23:27.163", "Id": "28009", "ParentId": "27987", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T10:59:21.073", "Id": "27987", "Score": "2", "Tags": [ "python", "linux", "iptables" ], "Title": "Python class to abstract the iptables Linux firewall" }
27987
<p>Consider the following code.</p> <pre><code>public async void Connect() { bool success = await ConnectAsync(); if (success) NotifyUserOfSuccess(); } public async Task&lt;bool&gt; ConnectAsync() { var t = await Task.Run(()=&gt; try { ConnectSynchronously(); } catch (Exception e) { return false; } return true; ); } </code></pre> <p>When analyzing this code, I come to the conclusion that I potentially am kicking off three threads. Assume that both <code>await</code>'s will not already be completed when called, then the first thread is kicked off by the <code>await ConnectAsync();</code> which in turn kicks off the <code>await Task</code>, and the <code>Task.Run</code> will kick off the function inside in a third thread. I really only need one thread, namely the one in <code>Connect()</code>.</p> <p>How can I improve the design?</p> <p>As <code>Connect()</code> contains the <code>await</code> keyword, shouldn't it really be called <code>ConnectAsync()</code> regardless of its return value?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:07:27.903", "Id": "43642", "Score": "4", "body": "This question appears to be off-topic because it is asking for a Code Review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:10:11.540", "Id": "43643", "Score": "7", "body": "How can I demonstrate the problem without posting some code?!" } ]
[ { "body": "<p>Your code will still run synchronously. In <code>ConnectAsync()</code> you await the Task.Run in effectively you are running it in sync with the rest. </p>\n\n<p>Since you are already awaiting <code>ConnectAsync</code> you should return the task in <code>ConnectAsync()</code> and don't mark the function as async:</p>\n\n<pre><code>public async void Connect()\n{\n bool success = await ConnectAsync();\n if (success) NotifyUserOfSuccess();\n}\n\npublic Task&lt;bool&gt; ConnectAsync()\n{\n return Task.Run(()=&gt;\n try {\n ConnectSynchronously();\n } catch (Exception e)\n {\n return false;\n }\n return true;\n );\n}\n</code></pre>\n\n<p>Now you run the anonymous function in async because it is wrapped in a task. You then can await this task to be completed as you do in <code>Connect</code>.</p>\n\n<hr>\n\n<p>To answer your comment about function naming:</p>\n\n<p>Because you have <code>Connect()</code>, <code>ConnectAsync()</code> and <code>ConnectSynchronously()</code>. I would rewrite your code to make the <code>ConnectAync</code> disapear and rename <code>Connect</code> to <code>TryConnect</code> to remove some confusion. But this is my take, it is always up to your own programming style.</p>\n\n<pre><code>public async void TryConnect()\n{\n bool success = await Task.Run(()=&gt;\n {\n try {\n ConnectSynchronously();\n } catch (Exception e)\n {\n return false;\n }\n return true;\n });\n if (success) NotifyUserOfSuccess();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Update:</strong></p>\n\n<p><code>obj.ToString()</code> also doesn't block the thread. But should it be called <code>obj.ToStringAsync()</code>? But you bring a somewhat valid point. You could rename it as <code>ConnectAsync()</code> but I called it <code>TryConnect</code> because it not only connects, but it also responded to the user if successful. Hence, you try to connect. But again, it is you personal flavor. Just as long as the method name makes sence. TryConnect reflects well what the method does, as does ConnectAsync. As long as you dont call it <code>DoStuff()</code> because that doesnt reflect what the method does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:13:44.230", "Id": "43644", "Score": "0", "body": "Isn't there still two thread involved? The one started by `await` and the one by `Task.Run(..)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:16:13.823", "Id": "43645", "Score": "1", "body": "in total there will be 2 threads, 1, the main thread. and the other the task.run. async and await is used to make sure the main thread isn't frozen for the duration of the task. What in your case contains the long running `ConnectSynchronously()`. Because the use of async and await `ConnectSynchronously()` is executed in a different thread and the main thread isn't frozen in the mean time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:19:31.003", "Id": "43646", "Score": "0", "body": "Ok. I get it. What is your take on the naming of the methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:47:52.240", "Id": "43647", "Score": "0", "body": "Shouldn't the method reflect that calling it will not block the calling thread? I.e. `TryConnect` should be renamed `TryConnectAsync`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:53:06.353", "Id": "43648", "Score": "0", "body": "@lejon, see update" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:09:56.237", "Id": "27990", "ParentId": "27989", "Score": "6" } }, { "body": "<p>You have a wrong assumption here. <code>await</code> never starts a new thread! Strictly speaking even <code>Task.Run</code> might not start a <strong>new</strong> thread since it uses the thread pool.</p>\n\n<p>See this answer for more details on <code>await</code>: <a href=\"https://stackoverflow.com/questions/16978904/async-programming-control-flow/16980183#16980183\">https://stackoverflow.com/questions/16978904/async-programming-control-flow/16980183#16980183</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:18:44.173", "Id": "43649", "Score": "0", "body": "I see. I was reading http://blog.stephencleary.com/2012/02/async-and-await.html and I guess I was confused by the statement: \"If \"await\" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method.\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:15:42.420", "Id": "27991", "ParentId": "27989", "Score": "11" } }, { "body": "<p>There are currently two threads used: one for <code>Task.Run</code> and one for everything else.</p>\n\n<p>To improve the code, get rid of <code>ConnectSynchronously</code> and replace it with whatever truly-asynchronous connection mechanism you have, e.g.:</p>\n\n<pre><code>public Task ConnectAsync()\n{\n return Task.Factory.FromAsync(BeginConnect, EndConnect, null); // or whatever\n}\n\npublic async Task&lt;bool&gt; TryConnectAsync()\n{\n try\n {\n await ConnectAsync();\n return true;\n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n\n<p>Then you only have one thread.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T10:24:17.497", "Id": "27992", "ParentId": "27989", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T09:04:41.610", "Id": "27989", "Score": "7", "Tags": [ "c#", ".net" ], "Title": "Thread overkill with async/await" }
27989
<p>I want to toggle button visibility based on values a user selects within a group of checkboxes. </p> <p>For example, the user may be given a group of checkboxes with colors:</p> <pre><code>&lt;input type="checkbox" value="red"&gt;Redbr&gt; &lt;input type="checkbox" value="blue"&gt;Blue&lt;br&gt; &lt;input type="checkbox" value="green"&gt;Green </code></pre> <p>And the available vehicles would be visible based on the colors selected:</p> <pre><code>&lt;button class="choice-button" data-attributes= "red,blue" type="button"&gt;Truck&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "green" type="button"&gt;Car&lt;/button&gt;&lt;br&gt; </code></pre> <p><a href="http://jsfiddle.net/hPgyn/" rel="nofollow">I have code that works</a>, but I do not believe it is optimized:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://code.jquery.com/jquery-1.8.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; //http://stackoverflow.com/questions/1181575/javascript-determine-whether-an-array-contains-a-value var indexOf = function(needle) { if(typeof Array.prototype.indexOf === 'function') { indexOf = Array.prototype.indexOf; } else { indexOf = function(needle) { var i = -1, index; for(i = 0; i &lt; this.length; i++) { if(this[i] === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle); }; function doTheMagic() { //Re-initialize buttons by showing all of them $('.choice-button').show(); //Find out which buttons are checked and store their value into an array var buttonRequirements = new Array(); $('#myform :checkbox').each(function(){ if($(this).is(':checked')) buttonRequirements.push($(this).val()); }); //Loop through each of the available "choice buttons" and hide ones that do not fit the checked criteria (e.g. buttonRequirements) $('.choice-button').each(function(){ buttonAttributes = $(this).data('attributes'); buttonArray = buttonAttributes.toString().split(','); for (var i = 0; i &lt; buttonRequirements.length; i++) { //If the button does not contain the checked attribute, hide it index = indexOf.call(buttonArray, buttonRequirements[i]); if (index&lt;0) $(this).hide(); } }); } $(document).ready(function() { //Every time a checkbox value changes, call the function to show/hide the appropriate button $('#myform :checkbox').click(function() { doTheMagic(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="myform"&gt; &lt;h3&gt;Filter choices based on attributes:&lt;/h3&gt; &lt;input type="checkbox" value="1"&gt;Attribute 1&lt;br&gt; &lt;input type="checkbox" value="2"&gt;Attribute 2&lt;br&gt; &lt;input type="checkbox" value="3"&gt;Attribute 3&lt;br&gt; &lt;input type="checkbox" value="4"&gt;Attribute 4&lt;br&gt; &lt;input type="checkbox" value="5"&gt;Attribute 5&lt;br&gt; &lt;h3&gt;Available choices&lt;/h3&gt; &lt;button class="choice-button" data-attributes="1,3,4,5" type="button"&gt;Choice 1&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes="2,3,4,5" type="button"&gt;Choice 2&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "1,2,3,4" type="button"&gt;Choice 3&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "1" type="button"&gt;Choice 4&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "2" type="button"&gt;Choice 5&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "3" type="button"&gt;Choice 6&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "4" type="button"&gt;Choice 7&lt;/button&gt;&lt;br&gt; &lt;button class="choice-button" data-attributes= "5,2" type="button"&gt;Choice 8&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>For my particular Use Case, I am pulling both the “choices” and “attributes” from a database. This form will be created dynamically every time and I want all data loaded up front in the UI.</p> <p>There are currently 130 “choice buttons” and 78 “attributes”.</p> <p>Throughout the lifetime of this application, this list will not change much. It would be a very rare scenario to grow even 20% over the next five years. </p> <p>I thought about using bit comparison but that looks to be out of the question since I have more than 32 options to choose from.</p> <p>I would like to steer away from the loops and minimize the code if possible.</p> <p>How can I make this faster?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T15:02:00.930", "Id": "43659", "Score": "0", "body": "A function with `magic` in its name is usually pretty bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T15:15:10.763", "Id": "43660", "Score": "0", "body": "@FlorianMargaine It's an example; not production code." } ]
[ { "body": "<p>One thing, there is no reason to loop through to determine if the checkbox is checked</p>\n\n<pre><code>$('#myform :checkbox').each(function(){\n if($(this).is(':checked'))\n buttonRequirements.push($(this).val());\n}); \n</code></pre>\n\n<p>do it with the selector. </p>\n\n<pre><code>$('#myform :checkbox:checked')....\n</code></pre>\n\n<p>You can also use map instead of pushing so you can avoid the each</p>\n\n<pre><code>var buttonRequirements = $(\":checkbox:checked\").map( \n function () { \n return this.value; \n }).get();\n</code></pre>\n\n<p>And if you used a class instead of a data attribute you could shrink the code </p>\n\n<pre><code>var colors = $(\":checkbox:checked\").map( function(){ return this.value; }).get();\nvar goodClasses = colors.join(\",\");\n$(\".item\").hide().filter(goodClasses).show();\n</code></pre>\n\n<p>JSFiddle: <a href=\"http://jsfiddle.net/Kmc65/\" rel=\"nofollow\">http://jsfiddle.net/Kmc65/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T21:01:20.140", "Id": "28011", "ParentId": "27998", "Score": "2" } } ]
{ "AcceptedAnswerId": "28011", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T14:47:12.467", "Id": "27998", "Score": "1", "Tags": [ "javascript", "jquery", "html5" ], "Title": "Toggle HTML elements' visbility based on selected checkbox(es)" }
27998
<p>I hope I've asked this in the right area. I'm writing a program that deals with enqueueing a class on STL <code>queue</code> in C++. Initially it queues initializations of the class. Then while the queue is not empty, it performs some operations on the class and then checking if an inequality works it either pops the queue or passes the class into function that creates more versions of the class and then queues the extra versions. It then pops the original initialization.</p> <p>I'm trying to change this so it suits the format, I've also changed the title. At this stage I'm looking to minimize memory footprint mainly and maximize speed as a secondary. I'm basically looking for advice on lines I can remove or where it's inefficient. <code>int main()</code> would also include code to initially queue <code>Subcube</code>s. I hope this is more what you're looking for but if not just let me know.</p> <pre><code>Vec map(const Vec &amp;g,const int &amp;p); \\I haven't added these as I dont think theyre massicaly important double pnorm(const Vec &amp;s,const int &amp;p); typedef vector&lt;double&gt; Vec; typedef vector&lt;Vec&gt; Mat; typedef queue&lt; Subcube&gt; SUBQUEUE; void subdivide(Subcube &amp;nw, const Subcube &amp;f ,const Vec &amp;t) { // cout &lt;&lt; "running subdivide" &lt;&lt; endl; Vec v = t; v.insert(v.begin() + f.k, 0); int n = f.e.size(); nw.e.assign(n,0); //just to avoid runtime error nw.hside = (f.hside/2); nw.k= f.k; for(int j=0;j&lt;n;j++) { nw.e.at(j) = f.e.at(j) +(f.hside/2)*v.at(j); } } int main(){ while(!q.empty()) { double upperb=0; upperb = 2*pow(double(n),0.25)*q.front().hside; Vec radmap = map(q.front().e,p); // taking the vector from front subcube and maping it radially from the l-infy to the l4 unit ball double temp = pnorm(a*radmap,p); // taking a nomrm of matrix a multiplied by radmap if(temp&gt;M) {M=temp; final = radmap;} // to see what vector maximised it at the end if(temp&gt;= M*(1+e)*(1-(((p-1)/2)*pow(upperb,2)))){ int tr = pow(2,n-1); for(int j =0;j&lt;tr;j++) { q.push(subdivide(q.front(),set.at(j))); // splits subcube into 2^n-1 subcubes } counter++; //counts related to number of subcubes created } q.pop();} } class Subcube { public: Subcube(); void printvector(const int&amp; n); void Subcubeset(const int&amp; i,const int&amp; n); vector&lt;double&gt; e; double hside; char k; virtual ~Subcube(); protected: private: }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T16:15:06.540", "Id": "43666", "Score": "3", "body": "This question might be better suited for StackOverflow. In either case, you should provide some code so others can see what the problem might be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T18:02:01.433", "Id": "43677", "Score": "0", "body": "How much code should I put up? There's quite a lot of it :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T19:41:28.010", "Id": "43695", "Score": "0", "body": "How are you measuring memory usage? Are you expecting the memory to be returned to the system when you program frees it? That depends upon the memory allocator, but I would not be at all surprised if freeing memory had no effect on the memory usage of the process (from the OS perspective) - the allocator just keeps the memory for later use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T23:29:08.910", "Id": "43707", "Score": "0", "body": "I was using System Monitor. Okay that might make sense. Is there anyway to measure it within the program or return it to the system? There's millions initializations of the class and uses up all my ram before crashing if I try to solve something difficult" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:55:15.947", "Id": "43717", "Score": "0", "body": "To answer \"How much code should I put up?\": [It should be SSCCE](http://sscce.org)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T12:34:04.940", "Id": "43735", "Score": "0", "body": "@James I think this question is salvageable now, and I have voted to reopen it. That is assuming the code actually works. It still needs some work, though: 1. Clean up the code formatting / indenting. 2. Make the code compilable if possible (potentially by making stub function calls, or mocks). 3. Try to write a more clear explanation, preferably with shorter sentences." } ]
[ { "body": "<p>As @Lstor mentions in the comments, clean up your formatting and indentation. There should be plenty of resources online, and you can also look at other highly-developed code for ideas. Above all, keep it <em>clear</em> and <em>consistent</em>.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li><p>This isn't a very descriptive <code>typedef</code>:</p>\n\n<pre><code>typedef vector&lt;double&gt; Vec;\n</code></pre>\n\n<p>There's no point in using a <code>typedef</code> here if you're just going to name it what it already it. Name it based on how this <em>type</em> is used in your program, otherwise don't bother renaming it.</p></li>\n<li><p>Why is this all uppercase?</p>\n\n<pre><code>typedef queue&lt; Subcube&gt; SUBQUEUE;\n</code></pre>\n\n<p>It's a type, not a macro. Just like you have with <code>Vec</code>, have it start with an uppercase, but don't use <em>all</em> uppercase.</p></li>\n</ul>\n\n<p><strong>Functions</strong></p>\n\n<ul>\n<li><p>I'm not sure what this is:</p>\n\n<pre><code>for(int j=0;j&lt;n;j++)\n{\n nw.e.at(j) = f.e.at(j) +(f.hside/2)*v.at(j);\n }\n }\n</code></pre>\n\n<p>For one thing, the second closing curly brace is for the function. But the poor indentation makes it appear to belong to the loop.</p>\n\n<p>Put some whitespace between the operators and operands within the loop statement. This should be done everywhere for clarity.</p>\n\n<p>Consider adding comments explaining what the loop is doing. I'm not even sure what is going on inside. Even if something seems obvious to you, it won't be obvious for everyone. Now, if something is <em>too</em> obvious, then it doesn't warrant commenting. But this does.</p></li>\n<li><p>Many things from <code>main()</code> and below is very unclear. Not only should everything inside <code>main()</code> be indented, but it appears that you're missing a closing brace (the one above <code>class</code> looks like it belongs to the <code>while</code> loop).</p>\n\n<p>That's an odd place to declare the class. It should be put into a separate header file, with this file including the header. If you're going to have <code>main()</code> defined after everything else (which is good), make sure it <em>is</em> the last thing in the file.</p></li>\n</ul>\n\n<p><strong><code>Subcube</code></strong></p>\n\n<ul>\n<li><p>I'm not sure if you already have the implementation elsewhere and haven't included it here, but make sure you have something for it. It would be helpful to see how those data members are used and how those member functions perform.</p></li>\n<li><p>Everything is crammed into <code>public</code>, and there are some things that shouldn't be there. The data members (<code>k</code>, <code>hside</code>, and <code>e</code>) should be under <code>private</code>. The functions and constructor should stay <code>public</code>, unless some shouldn't be used by outside code. If you're not using <code>protected</code>, just get rid of it. It doesn't need to be there for nothing.</p></li>\n<li><p>In <code>printvector()</code> and <code>Subcubeset()</code>, you don't need to pass the <code>int</code>s by <code>const&amp;</code>. Passing an <code>int</code> is relatively cheap, so just pass them by value.</p></li>\n<li><p><code>printvector()</code> should be <code>const</code> as it shouldn't be modifying any data members:</p>\n\n<pre><code>void printvector(const int&amp; n) const;\n</code></pre></li>\n<li><p><code>Subcubeset()</code> should use camelCase naming as it's a function.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-18T03:17:59.730", "Id": "41933", "ParentId": "27999", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T15:23:04.787", "Id": "27999", "Score": "5", "Tags": [ "c++", "queue" ], "Title": "Reducing memory footprint with queue of classes" }
27999
<p>I have these two methods:</p> <pre><code>public static String buildLine(String[] values) { StringBuilder lineBuilder = new StringBuilder(); for (int i = 0; i &lt; values.length - 1; i++) { lineBuilder.append(values[i]).append(SEPARATOR); } lineBuilder.append(values[values.length - 1]); return lineBuilder.toString(); } public static String buildLineFromNodeWorker(String[] values, NodeDecorator nodeWorker) { StringBuilder lineBuilder = new StringBuilder(); for (int i = 0; i &lt; values.length - 1; i++) { lineBuilder.append( nodeWorker.getItemValueFromAttribute(values[i])) .append(SEPARATOR); } lineBuilder .append(nodeWorker .getItemValueFromAttribute(values[values.length - 1])); return lineBuilder.toString(); } </code></pre> <p>they're identical except for what I'm passing to the <code>append</code> method from the <code>StringBuilder</code>.</p> <p>I'm not able to find a way to write the "business logic" of the loop just once.</p>
[]
[ { "body": "<p>One way using the <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">Template method pattern</a>:</p>\n\n<pre><code>abstract class LineBuilder {\n protected abstract String getLine(String value);\n\n public String buildLine(String[] values) {\n StringBuilder lineBuilder = new StringBuilder();\n for (int i = 0; i &lt; values.length - 1; i++) {\n lineBuilder.append(getLine(values[i])).append(SEPARATOR);\n }\n lineBuilder.append(getLine(values[values.length - 1]));\n return lineBuilder.toString();\n }\n}\n\nclass StringLineBuilder extends LineBuilder {\n protected String getLine(String value) {\n return value;\n }\n}\n\nclass NodeWorkerLineBuilder extends LineBuilder {\n private final NodeDecorator nodeWorker;\n\n public NodeWorkerLineBuilder(NodeDecorator nodeWorker) {\n this.nodeWorker = nodeWorker;\n }\n\n protected String getLine(String value) {\n return nodeWorker.getItemValueFromAttribute(value);\n }\n}\n</code></pre>\n\n<p>Once you define the above classes you can replace the code inside your methods with:</p>\n\n<pre><code>public static String buildLine(String[] values) {\n return new StringLineBuilder().buildLine(values);\n}\n\npublic static String buildLineFromNodeWorker(String[] values,\n NodeDecorator nodeWorker) {\n return new NodeWorkerLineBuilder(nodeWorker).buildLine(values);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T05:54:09.290", "Id": "43783", "Score": "0", "body": "Better explanation of the template method you can find here http://sourcemaking.com/design_patterns/template_method" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T22:46:26.110", "Id": "28014", "ParentId": "28012", "Score": "3" } }, { "body": "<p>A straight forward refactoring:</p>\n\n<pre><code>// Differing bit\nprivate interface Function&lt;X,Y&gt; {\n Y apply(X x);\n}\n\n// Common bit\nprivate static String buildLine(String[] values, Function&lt;String, String&gt; f) {\n StringBuilder lineBuilder = new StringBuilder();\n for (int i = 0; i &lt; values.length - 1; i++) { \n lineBuilder.append(f.apply(s)).append(SEPARATOR);\n }\n lineBuilder.append(values[values.length - 1]);\n return lineBuilder.toString();\n}\n\n// call the common routine, supply differing part as a parameter\npublic static String buildLine(String[] values) {\n return buildLine(values, new Function&lt;String, String&gt;() {\n public String apply(String s) {\n return s;\n }\n });\n}\n\n// call the common routine, supply differing part as a parameter\npublic static String buildLineFromNodeWorker(String[] values, final NodeDecorator nodeWorker) {\n return buildLine(values, new Function&lt;String, String&gt;() {\n public String apply(String s) {\n return nodeWorker.getItemValueFromAttribute(s);\n }\n });\n}\n</code></pre>\n\n<p>Two private methods above can be replaced with the following one if you have Guava libraries:</p>\n\n<pre><code>private static String buildLine(String[] values, Function&lt;String, String&gt; f) {\n return Joiner.on(SEPARATOR).join(\n Iterables.transform(Arrays.asList(values), f));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T06:31:55.400", "Id": "43726", "Score": "0", "body": "I cannot use the for loop because I would be writing the last element twice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T08:23:34.803", "Id": "43729", "Score": "0", "body": "@dierre You're right. Removed that suggestion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T05:56:41.757", "Id": "28027", "ParentId": "28012", "Score": "3" } } ]
{ "AcceptedAnswerId": "28014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T22:12:02.670", "Id": "28012", "Score": "2", "Tags": [ "java" ], "Title": "Refactoring same loop logic with different input data" }
28012
<p>Recently Torbjörn Söderstedt shipped <a href="http://torso.me/chicken-spec" rel="noreferrer">the chicken programing specification</a>. The basic premise of chicken is this: Only the word chicken, spaces and line breaks may be used. It was inspired by this <a href="http://isotropic.org/papers/chicken.pdf" rel="noreferrer">paper</a> and <a href="http://www.youtube.com/watch?v=yL_-1d9OSdk" rel="noreferrer">this talk</a>.</p> <p>Along with the specification he also created a <a href="http://torso.me/chicken.js" rel="noreferrer">javascript function</a> that <a href="http://torso.me/chicken" rel="noreferrer">implements</a> the chicken VM. Sadly (or joyfully?) he wrote the function with little more than the word chicken and thus mad if very very hard to understand.</p> <p>I was wondering, could anyone do a code review of chicken.js? Maybe add a bunch of in-line comments?</p> <pre><code>function chicken(CHICKEN, Chicken) { Chicken &amp;&amp;( chicken. chicken =[, CHICKEN, CHICKEN = Chicken = chicken. $Chicken =-( CHICKEN ==( chicken. Chicken = Chicken ))], chicken. chicken [Chicken++] = chicken. chicken, chicken. CHICKEN = ++Chicken, chicken (--Chicken), chicken. $Chicken = ++Chicken, chicken. CHICKEN++ ); Chicken = chicken. Chicken [chicken. $Chicken++ ]; chicken. Chicken = CHICKEN? Chicken? '\012'== Chicken? chicken (++ CHICKEN, chicken. chicken [++ chicken. CHICKEN ]= CHICKEN - CHICKEN ): Chicken ==' '|'\015'== Chicken || (Chicken )== "c" &amp; chicken. Chicken [chicken. $Chicken++ ]== "h" &amp; chicken. Chicken [chicken. $Chicken++ ]== "i" &amp; chicken. Chicken [chicken. $Chicken++ ]== "c" &amp; chicken. Chicken [chicken. $Chicken++ ]== "k" &amp; chicken. Chicken [chicken. $Chicken++ ]== "e" &amp; chicken. Chicken [chicken. $Chicken++ ]== "n"&amp;&amp;++chicken. chicken [chicken. CHICKEN]? chicken (CHICKEN) :[ "Error on line "+CHICKEN+": expected 'chicken'", chicken. CHICKEN = CHICKEN ++- CHICKEN ]: chicken. chicken :( CHICKEN = chicken. Chicken[chicken.CHICKEN], Chicken? (Chicken = --Chicken? --Chicken? --Chicken? --Chicken? --Chicken? --Chicken? --Chicken? --Chicken? --Chicken? chicken. CHICKEN++ &amp;&amp; --Chicken :'&amp;#'+CHICKEN+';': chicken. Chicken [chicken. Chicken [-- chicken. CHICKEN ]&amp;&amp; (chicken. $Chicken += CHICKEN), --chicken. CHICKEN ]: chicken. Chicken [chicken. Chicken [CHICKEN] = chicken. Chicken [-- chicken. CHICKEN ],-- chicken. CHICKEN ]: chicken. Chicken [chicken. Chicken [chicken. $Chicken++ ]] [CHICKEN]: CHICKEN == chicken. Chicken [-- chicken. CHICKEN ]: CHICKEN*chicken. Chicken [-- chicken. CHICKEN ]: chicken. Chicken [-- chicken. CHICKEN ]- CHICKEN: chicken. Chicken [-- chicken. CHICKEN ]+ CHICKEN: chicken. CHICKEN ++ &amp;&amp; "chicken", chicken. Chicken [chicken. CHICKEN ]= Chicken, chicken ()): CHICKEN ); return chicken. Chicken } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T23:45:22.153", "Id": "43708", "Score": "6", "body": "This question appears to be off-topic because it isn't actually asking for code review and also you didn't write the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:03:11.330", "Id": "43710", "Score": "0", "body": "Well. I did ask for a code review, but that might be the wrong language. What I'm really hoping for is an explanation of what is going on in this odd bit of javascript. At first I figured this was a goodish question for stackoverflow, but they decided not and purposed it would do better here (which it has). SO Question -> http://stackoverflow.com/questions/17414435/how-does-chicken-js-work?noredirect=1#comment25290139_17414435" } ]
[ { "body": "<p>Here's my first analysis. It's not complete, but the VM should be mostly understandable now. I've included some testcases from the homepage in the bottom.</p>\n\n<pre><code>var out,\n stack,\n input_ptr,\n stack_ptr;\n\nfunction chicken(c, b)\n{\n if(b)\n {\n // run once at the beginning of each interpretation\n // after this, chicken is only called recursively with one argument\n\n if(c == b)\n {\n out = b;\n c = b = input_ptr = 0;\n stack = [undefined, c, 0]\n stack[0] = stack;\n stack_ptr = 2;\n // parse the code\n chicken(1);\n // parsing is done, run the code\n input_ptr = 2;\n stack_ptr++;\n }\n else\n {\n // code is equal to input?!\n stack = [undefined, c, c = b = input_ptr = -( c == (out = b))];\n stack[b++] = stack;\n stack_ptr = ++b;\n chicken(--b);\n input_ptr = ++b;\n stack_ptr++;\n }\n }\n\n // either one character from the code\n // or a number of chickens to be interpreted as code\n b = out[input_ptr++];\n\n if(c)\n {\n // parsing\n if(b)\n {\n if(b == '\\n')\n {\n // start counting on the top of the stack\n stack[++stack_ptr] = 0;\n return out = chicken(c + 1, 0);\n }\n else\n {\n // call chicken again, if:\n // 1. input it ' ' or '\\r'\n // 2. input is 'chicken'\n // In the latter case, increment the top of the stack\n return out = \n (b == ' ' | '\\r' == b) ||\n ((b == \"c\" &amp; \n out[input_ptr++] == \"h\" &amp;\n out[input_ptr++] == \"i\" &amp;\n out[input_ptr++] == \"c\" &amp;\n out[input_ptr++] == \"k\" &amp;\n out[input_ptr++] == \"e\" &amp;\n out[input_ptr++] == \"n\") &amp;&amp;\n ++stack[stack_ptr]) ? \n chicken(c)\n :\n // otherwise, error\n [\"Error on line \" + c + \": expected 'chicken'\", stack_ptr = c++ -c];\n }\n }\n else\n {\n // parsing is done, continue running the code\n return out = stack;\n }\n }\n else\n {\n // run the code\n // out is the stack at this point\n console.assert(out === stack);\n\n var top = out[stack_ptr];\n\n if(b)\n {\n (b = --b? --b? --b? --b? --b? --b? --b? --b? --b?\n\n /* n push */ stack_ptr++ &amp;&amp; --b \n /* 9, BBQ */ : '&amp;#' + top + ';'\n /* 8, fr */ : out[out[--stack_ptr] &amp;&amp; (input_ptr += top), --stack_ptr]\n /* 7, peck */ : out[out[top] = out[--stack_ptr], --stack_ptr]\n /* 6, pick */ : out[out[input_ptr++]][top]\n /* 5, compare */ : out[--stack_ptr] == top\n /* 4, rooster (mult) */ : out[--stack_ptr] * top\n /* 3, fox (sub) */ : out[--stack_ptr] - top\n /* 2, add */ : out[--stack_ptr] + top\n /* 1, chicken */ : stack_ptr++ &amp;&amp; \"chicken\");\n\n // push result on stack\n out[stack_ptr] = b;\n\n // next instruction\n return out = chicken();\n }\n else\n {\n /* 0, terminate */\n return top;\n }\n }\n}\n\nvar read = require(\"fs\").readFileSync;\n\nconsole.assert(chicken(\"\",\"chicken\") === \"chicken\");\nconsole.assert(chicken(\"test foo\", read(\"echo.chicken\") + \"\") == \"test foo\")\nconsole.assert(chicken(\"\", read(\"hello.chicken\") + \"\") == \"&amp;#72;&amp;#101;&amp;#108;&amp;#108;&amp;#111;&amp;#32;&amp;#119;&amp;#111;&amp;#114;&amp;#108;&amp;#100;\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T03:28:08.257", "Id": "43720", "Score": "0", "body": "This is looking sweet. Now I can at least understand the code, though honestly, I'm still getting really lost. I've push a repo to github turning your code into a node module, so I can keep working it out on my own. Thanks. https://github.com/mcwhittemore/chicken.js" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T02:22:17.337", "Id": "28020", "ParentId": "28015", "Score": "6" } } ]
{ "AcceptedAnswerId": "28020", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T23:17:07.440", "Id": "28015", "Score": "5", "Tags": [ "javascript" ], "Title": "How does chicken.js work?" }
28015
<p>I have a basic swing application that I am trying to develop using MVC structure.</p> <p>The principal class in the model connects to a derby database and retrieves values from columns and stores them in arrays.</p> <p>My methods in the model (Connect(), Retrieve()) are public void. In runApp(), which is a SwingUtilities runnable, I am calling my model methods like this:</p> <pre><code>public static void runApp() { Model model = new Model(); model.Connect(); //Connects to database model.Retrieve(); //Retrieves database column values from tables, creates arrays View view = new View(model); Controller controller = new Controller(view, model); view.setCalculateListener(controller); } </code></pre> <p>I am trying to write this program so that everything is as less tightly coupled as possible. This code currently works as is, but I would like to do this better.</p> <p><strong>My question:</strong> How can I do this in a less coupled manner? Rather than having the methods being called here, is there a better way to do this?</p>
[]
[ { "body": "<p>For starters, consider making <code>Connect()</code> and <code>Retrieve()</code> non-public. <code>runApp()</code> doesn't seem to have a good reason to know about the operations that Model needs to perform to be usable here. Can the constructor (or, possibly more appropriately, a static factory method) hide those methods?</p>\n\n<p>Introducing state to objects is an easy way to make things complicated. If a View or Controller were somehow able to be passed a Model that had been, say, Connect()ed but not Retrieve()d, what would happen? It's simpler to factor that possibility out when that is an option.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T07:09:55.170", "Id": "28028", "ParentId": "28016", "Score": "2" } } ]
{ "AcceptedAnswerId": "28028", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T23:56:22.510", "Id": "28016", "Score": "2", "Tags": [ "java", "mvc" ], "Title": "Decoupling MVC model methods in java" }
28016
<p>Instead of writing <code>HtmlAgilityPack</code> document code over and over, I've decided to create a helper class for <code>HtmlAgilityPack</code> that prevents me that problem and adds a dispose feature for <code>HtmlDocuments</code>.</p> <p>What can I do better?</p> <pre><code>public class HtmlParser { private ArrayList Documents { get; set; } public HtmlParser() { Documents = new ArrayList(); } ~HtmlParser() { Dispose(); } public string ParseNode(string page, string xPath, ParseType type, string attributes = null) { int index = Documents.Add(new HtmlDocument()); ((HtmlDocument)Documents[index]).LoadHtml(page); HtmlNode node = ((HtmlDocument)Documents[index]).DocumentNode.SelectSingleNode(xPath); if (null != node) return type == ParseType.InnerHtml ? node.InnerHtml : type == ParseType.OuterHtml ? node.OuterHtml : type == ParseType.InnerText ? node.InnerText : node.Attributes[attributes].Value; return null; } public HtmlNode GetNode(string page, string xPath) { int index = Documents.Add(new HtmlDocument()); ((HtmlDocument)Documents[index]).LoadHtml(page); return ((HtmlDocument) Documents[index]).DocumentNode.SelectSingleNode(xPath); } public HtmlNodeCollection GetNodes(string page, string xPath) { int index = Documents.Add(new HtmlDocument()); ((HtmlDocument)Documents[index]).LoadHtml(page); return ((HtmlDocument)Documents[index]).DocumentNode.SelectNodes(xPath); } public void Dispose() { if (null != Documents) Documents.Clear(); Documents = null; GC.Collect(); } } public enum ParseType { InnerHtml, OuterHtml, InnerText, Attribute } </code></pre>
[]
[ { "body": "<p>There are a few things I've noticed.</p>\n\n<ol>\n<li>This line <code>if (null != node) return type == ParseType.InnerHtml ? node.InnerHtml : type == ParseType.OuterHtml ? node.OuterHtml : type == ParseType.InnerText ? node.InnerText : node.Attributes[attributes].Value;</code> is very confusing. You are mixing and if statement with multiple ternary really clutters up that line of code.</li>\n<li>You shoud look into the <a href=\"https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp\"><code>var</code></a> keyword. When the variable type is obvious, it is pretty much stand practise to use it. I think it really cleans up code.</li>\n<li>I'm not sure why you are using <code>GC.Collect()</code> in your constructor. In C# there is not usually a need to control Garbage Collection. The framework deals with it pretty well.</li>\n<li>I would change <code>if (null != Documents)</code> to <code>if (Documents != null)</code>. I know why that syntax is done in C/C++, but in C# it is not needed, and the latter is much more descriptive and easier to understand.</li>\n<li>I would be careful about returning null from a method. It adds extra code where the method is called to check for null. Maybe look into the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">null object design pattern</a></li>\n</ol>\n\n<p>Other than that, your use of white space and indentation is very well done. Makes reading your code much easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:28:22.160", "Id": "43711", "Score": "0", "body": "Well thank you for your very well explained answer but i have some notices. i make use of `? :` instead of creating a switch that will longer my code also i did not called GC.Collect in the constructor, am i ? otherwise all your suggestions is really helpful and i will follow them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:29:34.307", "Id": "43712", "Score": "1", "body": "Also i am calling Dispose in a destructor because this is a custom dispose method not an IDisposable implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:31:10.803", "Id": "43713", "Score": "0", "body": "Generally I'm not against the ? : operator, except when it gets this big. I'm thinking that a switch statement in a separate method would be more readable in this situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:31:39.617", "Id": "43714", "Score": "1", "body": "re: The destructor: that makes sense then :) I didn't even notice that. I will remove that comment." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T01:20:17.500", "Id": "28019", "ParentId": "28017", "Score": "3" } } ]
{ "AcceptedAnswerId": "28019", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T00:11:23.253", "Id": "28017", "Score": "0", "Tags": [ "c#", "parsing" ], "Title": "HtmlAgilityPack Helper class" }
28017
<p>I know there are many PHP upload classes out there, but I'm comfortable with my own code, so I made a simple one here.</p> <p>What do you think of my approach when <code>isImage</code> is true?</p> <p>Of course a general opinion about it and any feedback will help.</p> <pre><code>&lt;?php /** * This will allow easy handling of a php upload * @author: Mihai Ionut Vilcu (ionutvmi@gmail.com) * 2-July-2013 */ class Upload { var $settings = array( 'folder' =&gt; '.', // the folder where the images will be placed 'isImage' =&gt; 0, // if true it will treat files as images 'maxSize' =&gt; 2, // the max allowed size in MB 'allowed_extensions' =&gt; array(), // an array of lowercase allowed extensions, (!) IF EMPTY ALL ARE ALLOWED (!) 'overwrite' =&gt; 0 // if true it will overwrite the file on the server in case it has the same name ); var $errors = array(); // will hold the errors var $success = array(); // will hold the success messages var $allowed_chars = "a-z0-9_.-"; // allowed chars in a file name, case insensitive function __construct($settings = array()) { // we update the settings $this-&gt;updateSettings($settings); } /** * Will process the files * @param string $inputName the name of the input to be checked * @param array $settings settings * @return array/string uploaded file(s) name */ function upload($inputName = 'file', $settings = array()) { // we update the settings $this-&gt;updateSettings($settings); if(!isset($_FILES[$inputName])) // if we have no file we have nothing to do return false; if(is_array($inputName) || is_object($inputName)) { // multiple input names $result = array(); foreach ($inputName as $file) $result[] = $this-&gt;handleFiles($file); return $result; } else { // single input name return $this-&gt;handleFiles($_FILES[$inputName]); } } /** * Will handle the files and perform validations * @param array $files the array of the files from $_FILES * @return array array with the uploaded files */ function handleFiles($files) { $files = $this-&gt;reArrayFiles($files); if(!is_writable($this-&gt;settings['folder'])) { $this-&gt;errors[] = array($this-&gt;settings['folder'], " This folder is not writable !"); return false; } foreach ($files as $file) { $result = array(); $file['name'] = $this-&gt;filterFilename($file['name']); // if no filename nothing to do if(trim($file['name']) == '') continue; if($file['error'] &gt; 0) { $this-&gt;errors[] = array($file['name'], $this-&gt;codeToMessage($file['error'])); continue; } // we check the file size if($file['size'] &gt; $this-&gt;settings['maxSize'] * 1024 * 1024) { $this-&gt;errors[] = array($file['name'], "The size of the file exceeds the allowed limit (".$this-&gt;settings['maxSize']."MB)."); continue; } // check the extension, remember if settings allowed_extensions is empty it will return allow all of them $info = pathinfo($file['name']); $info['extension'] = isset($info['extension']) ? $info['extension'] : ''; // in case the file name has no extension if(!empty($this-&gt;settings['allowed_extensions']) &amp;&amp; !in_array(strtolower($info['extension']), $this-&gt;settings['allowed_extensions'])) { $this-&gt;errors[] = array($file['name'], "This extension is not allowed !"); continue; } // we build the path for upload $upload_path = ltrim($this-&gt;settings['folder'], DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file['name']; // check if the file exists on the server if(!$this-&gt;settings['overwrite'] &amp;&amp; file_exists($upload_path)){ $this-&gt;errors[] = array($file['name'], "This file already exists, rename it !"); continue; } if($this-&gt;settings['isImage']) { // we need to handle it as an image if($img = $this-&gt;imagecreatefromfile($file['tmp_name'], $function)) { if($function($img, $upload_path)) { // we pass the image through a filter $this-&gt;success[] = array($file['name'], "It was uploaded successfully !"); $result[] = $file['name']; } // remove uploaded file @unlink($file['tmp_name']); } else $this-&gt;errors[] = array($file['name'], "This file is not a valid image !"); } else { // we treat it as a normal file if(move_uploaded_file($file['tmp_name'], $upload_path)) { $this-&gt;success[] = array($file['name'], "It was uploaded successfully !"); $result[] = $file['name']; } } } return $result; } /** * it will rearrange the array with the info about the files generated in $_FILES * @author: http://www.php.net/manual/en/features.file-upload.multiple.php#53240 * @edited: Mihai Ionut Vilcu (it will handle one file also) * @param array $file_post the $_FILES array * @return array the new array */ function reArrayFiles(&amp;$file_post) { $file_ary = array(); if(!is_array($file_post['name'])) return array($file_post); $file_count = count($file_post['name']); $file_keys = array_keys($file_post); for ($i=0; $i&lt;$file_count; $i++) { foreach ($file_keys as $key) { $file_ary[$i][$key] = $file_post[$key][$i]; } } return $file_ary; } /** * generates the html code for a basic upload form, it can generate the input fields only or the compleate form * @param integer $number the number of inputs * @param string $name the name of the input(s) * @param integer $complete_form if true it will generate the compleate forms insetead of just input fields * @param string $location location where the form will send the data(in case the form is compleate) * @param array $extra extra attributes for input(s) * @param array $extra_form extra attributes for form * @return string html code generated */ function generateInput($number = 1, $name = 'file', $complete_form = 0, $location = '?', $extra = array(), $extra_form = array()) { $html = $attr = $attr_form = ""; foreach ($extra as $key =&gt; $value) $attr .= " $key = '$value' "; foreach ($extra_form as $key =&gt; $value) $attr_form .= " $key = '$value' "; for($i = 0; $i &lt; $number; $i++) $html .= "File ".($i+1)." &lt;input type='file' name='$name".($number &gt; 1 ? "[]" : "")."'$attr&gt; &lt;br/&gt; "; if($complete_form == 1) $html = "&lt;form action='$location' method='post' enctype='multipart/form-data' $attr_form&gt; ".$html." &lt;input type='submit' value='Upload'&gt;\n&lt;/form&gt;"; return $html; } /** * gets the max file size for upload allowed on the server in MB * @return integer the max size in MB */ function getMaxUpload() { $max_upload = (int)(ini_get('upload_max_filesize')); $max_post = (int)(ini_get('post_max_size')); $memory_limit = (int)(ini_get('memory_limit')); return min($max_upload, $max_post, $memory_limit); } /** * makes sure that the file name only contains allowed chars * @param string $filename file name * @return string filtered file name */ function filterFilename($filename) { return preg_replace("/[^$this-&gt;allowed_chars]/i", "_", $filename); } /** * it will interpret the file upload error codes * @param integer $code the error code * @return string error message */ function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break; default: $message = "Unknown upload error"; break; } return $message; } /** * makes sure that the settings are updated and correct * @param array $settings new settings * @return void */ function updateSettings($settings) { $this-&gt;settings = array_merge($this-&gt;settings, $settings); $this-&gt;settings['maxSize'] = min($this-&gt;settings['maxSize'], $this-&gt;getMaxUpload()); } /** * will create an image from a file * @credits: http://www.php.net/manual/en/function.imagecreate.php#81831 * @edited: Mihai Ionut Vilcu (ionutvmi@gmail.com) - added $fun * @param string $path path to the file * @param string $fun it will hold the function required for adding image data in the file * @param boolean $user_functions if true you need to have defined a function imagecreatefrombmp you can find one http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 * @return resource/false false if it fails */ function imagecreatefromfile($path, &amp;$fun, $user_functions = false) { $info = @getimagesize($path); if(!$info) { return false; } $functions = array( IMAGETYPE_GIF =&gt; 'imagecreatefromgif', IMAGETYPE_JPEG =&gt; 'imagecreatefromjpeg', IMAGETYPE_PNG =&gt; 'imagecreatefrompng', IMAGETYPE_WBMP =&gt; 'imagecreatefromwbmp', IMAGETYPE_XBM =&gt; 'imagecreatefromwxbm', ); if($user_functions) { $functions[IMAGETYPE_BMP] = 'imagecreatefrombmp'; } if(!$functions[$info[2]]) { return false; } if(!function_exists($functions[$info[2]])) { return false; } $fun = str_replace("createfrom", "", $functions[$info[2]]); $targetImage = $functions[$info[2]]($path); // fix for png transparency imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); return $targetImage; } } </code></pre> <p>As a side note, you can also find it on <a href="https://github.com/ionutvmi/upload-class" rel="nofollow">GitHub</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T00:36:10.283", "Id": "28018", "Score": "2", "Tags": [ "php", "object-oriented", "classes", "file-system" ], "Title": "PHP upload class" }
28018
<p>When I chose an element from this <code>HorizontalScrollView</code>, I was setting <code>focus</code> to that element by calling:</p> <pre class="lang-java prettyprint-override"><code>else if (v.getParent() == candidatesScrollView.getChildAt(0)) { Button candidateButton = (Button) v; v.requestFocusFromTouch(); v.setSelected(true); (...) } </code></pre> <p>Here is part of my XML:</p> <pre class="lang-xml prettyprint-override"><code>&lt;HorizontalScrollView android:id="@+id/CandidatesHorizontalScrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/linearLayout2" android:clickable="false" android:focusable="false" android:focusableInTouchMode="false" android:visibility="gone" &gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:clickable="false" android:focusable="false" android:focusableInTouchMode="false" android:orientation="horizontal" &gt; &lt;Button android:id="@+id/horizontalscrollview1_button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:textSize="25sp" /&gt; (...) // 11 more buttons &lt;/LinearLayout&gt; &lt;/HorizontalScrollView&gt; </code></pre> <p>After that, when I scrolled the list without choosing other element, I was losing <code>focus</code> of previously selected element. I made some research about this topic, but there was no solution that could work for me. Finally, after almost two weeks I have created some solution by myself.</p> <p>I would like you to review it and tell me what can I improve on.</p> <p>I created a custom <code>HorizontalScrollView</code> class inside and have overridden the <code>onTouchEvent()</code> method. I don't think this is optimal way of doing that, because in that case I have to do calculations every time I move even one pixel. For example, if I add <code>toast.show()</code> to the below method, it will try to show as many <code>toast</code> as many I moved pixels (If I move by 10 pixels, it will try to show 10 <code>Toast</code>). Anyway, it works for me and the selection and focus are being kept. Please help me modify this code to make finally a good answer for that known issue:</p> <pre class="lang-java prettyprint-override"><code>@Override public boolean onTouchEvent(MotionEvent ev) { int i = 0; Button button = null; for (; i &lt; 11; i++) { button = (Button)((LinearLayout)getChildAt(0)).getChildAt(i); if(button.isSelected()) break; } super.onTouchEvent(ev); button.setSelected(true); button.requestFocusFromTouch(); return true; } </code></pre> <p>To be sure that the above code will work, you need to have only one selected item in your <code>HorizontalScrollView</code> at a time, i.e when you press different <code>Button</code>, you need to make the previous one <code>setSelected(false)</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T18:38:50.830", "Id": "43835", "Score": "0", "body": "(FYI I do not know android development, but I know events and...) You appear to be executing this code for every onMotionEvent, rather then when your event of concern (scrolling) is stopped. [metacode] if(scrolling stopped){ do parent scrolling stopped; re-select text; } You might also figure out whether you can save which button was selected at the time of selection, rather than searching for it every time. Not sure if that helps, but I hope so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T00:15:55.587", "Id": "43855", "Score": "0", "body": "I decided not to play with the focus anymore. I just set the background so it looks like a focused. I updated my solutions in the original link posted in the question." } ]
[ { "body": "<p>I'm not familiar with Android, so just some generic notes:</p>\n\n<ol>\n<li><pre><code>int i = 0;\nButton button = null;\nfor (; i &lt; 11; i++)\n</code></pre>\n\n<p>I think the most developers more familiar with the following (equal and shorter) form:</p>\n\n<pre><code>for (int i = 0; i &lt; 11; i++)\n</code></pre></li>\n<li><p><code>11</code> and <code>0</code> are magic numbers. Use a named constant instead of them which explains the meaning of these numbers (and probably removes some duplication and makes maintenance easier).</p></li>\n<li><p>I think <code>MotionEvent</code> variable could deserve a little bit longer name for better readability. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><p>You could increase the abstraction level and readability a little bit with a new method whose name contains the purpose of the loop:</p>\n\n<pre><code>@Override\npublic boolean onTouchEvent(MotionEvent event) {\n Button button = getSelectedButton();\n super.onTouchEvent(event);\n button.setSelected(true);\n button.requestFocusFromTouch();\n\n return true;\n}\n\nprivate Button getSelectedButton() {\n LinearLayout linearLayout = (LinearLayout) getChildAt(0);\n for (int i = 0; i &lt; 11; i++) {\n Button button = (Button) linearLayout.getChildAt(i);\n if (button.isSelected()) {\n return button;\n }\n }\n throw new IllegalStateException(\"no button selected\");\n}\n</code></pre>\n\n<p>Note that the <code>Button</code> variable get a smaller scope and the <code>linearLayout</code> local variable. </p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>One Level of Abstraction per Function</em>, p36; <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>, p296; <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n<li><p>If you return <code>null</code> the <code>button.setSelected()</code> will throw a <code>NullPointerException</code> (or if you don't find any selected button in the original code). I guess having zero selected button is not a valid state of the application. If it somehow happens I'd throw an exception immediately (instead of setting <code>null</code> as the <code>Button</code> reference).</p>\n\n<pre><code>private Button getSelectedButton() {\n for (int i = 0; i &lt; 11; i++) {\n Button button = (Button) ((LinearLayout) getChildAt(0)).getChildAt(i);\n if (button.isSelected())\n return button;\n }\n throw new IllegalStateException(\"no button selected\");\n}\n</code></pre>\n\n<p>(<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><pre><code>super.onTouchEvent(event);\nbutton.setSelected(true);\n</code></pre>\n\n<p>Are you sure that you need <code>setSelected(true)</code> here? It seems that it's already selected before the super call (the for loop returns a selected button) but <code>super.onTouchEvent()</code> might unselect it. If super doesn't change this state you could remove the <code>button.setSelected</code> call.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:14:34.917", "Id": "42905", "ParentId": "28021", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T02:23:44.593", "Id": "28021", "Score": "3", "Tags": [ "java", "performance", "android", "xml" ], "Title": "Scrolling in Horizontal ScrollView losing selection" }
28021
<p>This code works well, but it's too long and looks too bad. I've tried to format it, but it all sets data, so I don't know how to make it better.</p> <p>Here is the class:</p> <pre><code>private static BrandProfitAndLoss getAllRateComparisonRecords(BrandProfitAndLoss brandProfitAndLoss , BrandProfitAndLoss brandProfitAndLossComp){ BrandProfitAndLoss result = new BrandProfitAndLoss(); result.setDate(brandProfitAndLossComp.getDate()); result.setOrder_item_num_comp(compareData(brandProfitAndLoss.getOrder_item_num(), brandProfitAndLossComp.getOrder_item_num())); result.setOrder_count_comp(compareData(brandProfitAndLoss.getOrder_count(), brandProfitAndLossComp.getOrder_count())); result.setOrder_price_comp(compareData(brandProfitAndLoss.getOrder_price(), brandProfitAndLossComp.getOrder_price())); result.setOrder_amount_comp(compareData(brandProfitAndLoss.getOrder_amount(), brandProfitAndLossComp.getOrder_amount())); result.setOrder_gross_comp(compareData(brandProfitAndLoss.getOrder_gross(), brandProfitAndLossComp.getOrder_gross())); result.setOrder_wholesale_price_comp(compareData(brandProfitAndLoss.getOrder_wholesale_price(), brandProfitAndLossComp.getOrder_wholesale_price())); result.setDelivery_count_comp(compareData(brandProfitAndLoss.getDelivery_count(), brandProfitAndLossComp.getDelivery_count())); result.setDelivery_price_comp(compareData(brandProfitAndLoss.getDelivery_price(), brandProfitAndLossComp.getDelivery_price())); result.setDelivery_item_num_comp(compareData(brandProfitAndLoss.getDelivery_item_num(), brandProfitAndLossComp.getDelivery_item_num())); result.setDelivery_gross_comp(compareData(brandProfitAndLoss.getDelivery_gross(), brandProfitAndLossComp.getDelivery_gross())); result.setDelivery_amount_comp(compareData(brandProfitAndLoss.getDelivery_amount(), brandProfitAndLossComp.getDelivery_amount())); result.setApproval_rate_comp(compareData(brandProfitAndLoss.getApproval_rate(), brandProfitAndLossComp.getApproval_rate())); result.setShipping_comp(compareData(brandProfitAndLoss.getShipping(), brandProfitAndLossComp.getShipping())); result.setAll_delivery_price_comp(compareData(brandProfitAndLoss.getAll_delivery_price_comp(), brandProfitAndLossComp.getAll_delivery_price_comp())); result.setReturn_sales_comp(compareData(brandProfitAndLoss.getReturn_sales(), brandProfitAndLossComp.getReturn_sales())); result.setPoint_discount_comp(compareData(brandProfitAndLoss.getPoint_discount(), brandProfitAndLossComp.getPoint_discount())); result.setPoint_allowance_comp(compareData(brandProfitAndLoss.getPoint_allowance(), brandProfitAndLossComp.getPoint_allowance())); result.setSales_amount_comp(compareData(brandProfitAndLoss.getSales_amount(), brandProfitAndLossComp.getSales_amount())); result.setPurchasing_cost_comp(compareData(brandProfitAndLoss.getPurchasing_cost(), brandProfitAndLossComp.getPurchasing_cost())); result.setProfit_comp(compareData(brandProfitAndLoss.getProfit(), brandProfitAndLossComp.getProfit())); result.setProfit_gross_comp(compareData(brandProfitAndLoss.getProfit_gross(), brandProfitAndLossComp.getProfit_gross())); result.setYfc_cost_comp(compareData(brandProfitAndLoss.getYfc_cost(), brandProfitAndLossComp.getYfc_cost())); result.setCommission_cost_comp(compareData(brandProfitAndLoss.getCommission_cost(), brandProfitAndLossComp.getCommission_cost())); result.setServer_cost_comp(compareData(brandProfitAndLoss.getServer_cost(), brandProfitAndLossComp.getServer_cost())); result.setBrand_cost_comp(compareData(brandProfitAndLoss.getBrand_cost(), brandProfitAndLossComp.getBrand_cost())); result.setBrand_pol_comp(compareData(brandProfitAndLoss.getBrand_pol(), brandProfitAndLossComp.getBrand_pol())); result.setCompLastYearRate_comp(compareData(brandProfitAndLoss.getCompLastYearRate(), brandProfitAndLossComp.getCompLastYearRate())); return result; } </code></pre> <p>And here is the <code>compareDate</code> method:</p> <pre><code>private static float compareData(float thisYear, float lastYear) { float result = 0; if(thisYear == 0 || lastYear == 0){ return result; } return (thisYear / lastYear) - 1; } </code></pre>
[]
[ { "body": "<p>Can you change the <code>BrandProfitAndLoss</code> class? If so, consider something like the Builder pattern. This will have the additional benefit of likely allowing the instance you return to be immutable.</p>\n\n<p>Since the scope of your <code>brandProfitAndLoss</code> and <code>brandProfitAndLossComp</code> variables is pretty small, consider a shorter variable name. It just bulks up each line, and you're unlikely to lose track of the variable since you can see its entire lifespan at one time.</p>\n\n<p>Make <code>result</code> and your parameters final variables.</p>\n\n<p>Make your methods more consistently named, you're using some odd combination of camelCase and underscores that is hard to read and easy to mix up. Java is most often camelCased, but adherence to any standard is better than a mishmosh.</p>\n\n<p>Rename your method: it does not appear that this class \"gets all rate comparison records\". It seems to generate some sort of single comparison record and return it.</p>\n\n<p>Rename your other method: <code>compareData</code> is undescriptive as to what the method does.</p>\n\n<p>Regarding <code>compareData</code>:\nThere's no sense in storing a value into a variable if you're only using it once (in the case of <code>result</code>). Also, you should not be using floats to store data that refers to money, as it will NOT work the way you hope it will. There are appropriate classes in Java for handling money in predictable ways (e.g. BigDecimal), you should use those wherever possible. </p>\n\n<p>I'm not entirely sure what you're trying to get accomplished with this method, so I can't suggest much. Is it just to show which of those numbers is greater? Can you use some kind of inline comparison in the setters above? Perhaps the classes (even, say, Float) support compareTo (from the Comparator interface), which would simplify this a lot.</p>\n\n<p>Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T08:18:26.403", "Id": "43728", "Score": "1", "body": "+1 just for \"shorter variable names\". Using e.g. `b1` and `b2` instead of `brandProfitAndLoss` and `brandProfitAndLossComp` will make each line 36 characters shorter and much more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T01:28:31.750", "Id": "43778", "Score": "0", "body": "@James McMillan thank for your help, it's very necessary for me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:20:50.413", "Id": "43959", "Score": "2", "body": "-1 for shorter variable names - the problem with this method is already readability, you're trying to compensate for an unclear design by taking unnecessary shortcuts. But +1 for the comment on camelCase - it's not standard Java convention to use underscores in method names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T19:14:00.810", "Id": "44054", "Score": "0", "body": "@Trisha Partially agreed. The names of the _method parameters_ should be kept long and descriptive, but in the method _body_, shorter names pointing to the same objects could be used." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T05:51:52.670", "Id": "28026", "ParentId": "28022", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T03:22:34.547", "Id": "28022", "Score": "4", "Tags": [ "java" ], "Title": "Brand profit and loss" }
28022
<p>My concern lies in understanding the nature of an object. My reasoning: when I instantiate my class, I am either creating an entirely new coupon, or I am referencing an existing one from the database. So I am thinking that the new <code>TJ_Coupon</code> actually is a new coupon. Am I thus using the constructor correctly?</p> <p>And then my other question is about abstraction. How far should I abstract? I have my setters which then go through three functions to actually change the DB. I am interested in feedback about that flow (seen near the end of the document and moving up).</p> <pre><code>/** * Class TJ_Coupon * Exceptions * Codes: * 0 -&gt; Code Wrong Length * 1 -&gt; Bad Date * 2 -&gt; Wrong Discount Format * 3 -&gt; Uses not positive integer * 4 -&gt; Coupon code already exists * 5 -&gt; Coupon code does not exist * 6 -&gt; Coupon has already been used * 7 -&gt; Coupon code is not for current user * 8 -&gt; WP User ID is not valid * 9 -&gt; Coupon can only be used once per order */ class TJ_Coupon { /** * @var string */ protected $name; /** * @var string */ protected $code; /** * @var string */ protected $discount; /** * With either a $ prefix or a % suffix * @var string */ protected $expiration_date; /** * @var int */ protected $uses; /** * @var int WP_User ID */ protected $user; /** * @param $code string coupon code * @param $create bool do you want to update database or just instantiate * @param $new_coupon array * @throws Exception */ function __construct($code, $create = false, $new_coupon = array()) { $coupons = get_option('tj_coupons', array()); if ($create) { $name = $new_coupon['name']; $code = $new_coupon['code']; $discount = $new_coupon['discount']; $expiration_date = $new_coupon['expiration_date']; $uses = $new_coupon['uses']; $user = $new_coupon['user']; if (isset($coupons["C_" . $code])) throw new Exception ('Coupon code already exists', 4); $name = $this-&gt;check_name($name); $code = $this-&gt;check_code($code); $discount = $this-&gt;check_discount($discount); $expiration_date = $this-&gt;check_expiration_date($expiration_date); $uses = $this-&gt;check_uses($uses); $user = $this-&gt;check_user($user); $this-&gt;update_coupon($name, $code, $discount, $expiration_date, $uses, $user); } else { if (!isset($coupons["C_" . $code])) throw new Exception ('Coupon code does not exists', 5); $coupon = $coupons["C_" . $code]; $this-&gt;setName($coupon['name']); $this-&gt;setCode($coupon['code']); $this-&gt;setDiscount($coupon['discount']); $this-&gt;setExpirationDate($coupon['expiration_date']); $this-&gt;setUses((int) $coupon['uses']); $this-&gt;setUser((int) $coupon['user']); } } /** * Updates Coupon * Make parameters false if you don't want to update that variable * @access protected * @param string|bool $name * @param string|bool $code * @param string|bool $discount * @param string|bool $expiration_date * @param int|bool $uses * @param int|bool $user */ protected function update_coupon ($name = false, $code = false, $discount = false, $expiration_date = false, $uses = false, $user = false ) { if (!$name) $name = $this-&gt;name; else $this-&gt;name = $name; if (!$code) $code = $this-&gt;code; else $this-&gt;code = $code; if (!$discount) $discount = $this-&gt;discount; else $this-&gt;discount = $discount; if (!$expiration_date) $expiration_date = $this-&gt;expiration_date; else $this-&gt;expiration_date = $expiration_date; if (!$uses) $uses = $this-&gt;uses; else $this-&gt;uses = $uses; if (!$user) $user = $this-&gt;$user; else $this-&gt;user = $user; $coupon = array( 'name' =&gt; $name, 'code' =&gt; $code, 'discount' =&gt; $discount, 'expiration_date' =&gt; $expiration_date, 'uses' =&gt; (int) $uses, 'user' =&gt; (int) $user ); $this-&gt;update_database($coupon); } /** * Update Coupon Database * @access protected * @param $coupon */ protected function update_database ($coupon) { $coupons = get_option('tj_coupons', array()); if (!isset($coupons["C_" . $this-&gt;code])) { $coupons = array_reverse($coupons); $coupons["C_" . $this-&gt;code] = $coupon; $coupons = array_reverse($coupons); } else $coupons["C_" . $this-&gt;code] = $coupon; update_option('tj_coupons', $coupons); } /* Coupon Use Functions ========================================================================== */ /** * Function to process new price from a coupon without affecting user count * * @param $user_id string * @param $price string without currency symbol * @return int * @throws Exception */ public function process_coupon($user_id, $price) { $coupons = get_user_meta($user_id, 'tj_coupons', true); if (isset($coupons["C_" . $this-&gt;code])) { $coupon = $coupons["C_" . $this-&gt;code]; if ($this-&gt;is_used($coupon['uses'])) throw new Exception ('You have already used this coupon.', 6); $uses = (int) $coupon['uses'] + 1; } else $uses = 1; if (!$this-&gt;can_user_use($user_id)) throw new Exception ('This coupon is not for you.', 7); return array('new_price' =&gt; $this-&gt;apply_discount($price), 'uses' =&gt; $uses); } /** * Function to use a coupon, affects user count * * @uses process_coupon * @param $user_id int WP User ID * @param $price string without $ prefix * @return mixed string without $ prefix */ public function use_coupon($user_id, $price) { $processed = $this-&gt;process_coupon($user_id, $price); $uses = $processed['uses']; $new_price = $processed['new_price']; $coupons["C_" . $this-&gt;code]['uses'] = $uses; $coupons["C_" . $this-&gt;code][time()] = array( 'use_number' =&gt; $uses ); update_user_meta($user_id, 'tj_coupons', $coupons); return $new_price; } /** * Apply the discount to a certain price * * @param $price string without currency symbol * @return int new price */ public function apply_discount($price) { if ($this-&gt;is_dollar()) return (int) $price - (int) substr($this-&gt;discount, 1); elseif ($this-&gt;is_percent()) return (int) $price * (1 - ((int) substr($this-&gt;discount, 0, -1) * .01)); else return $price; } /** * Checks if the current user can use this coupon */ public function can_user_use($user_id) { if ($this-&gt;for_user() &amp;&amp; $user_id != $this-&gt;user) return false; else return $this-&gt;for_user() &amp;&amp; $user_id != $this-&gt;user; } /* Utility Functions ========================================================================== */ /** * Determines if the coupon is only for a certain user * @return bool */ public function for_user() { if ($this-&gt;user == 'false') return false; else return true; } /** * Determines if a coupon is expired by date * @return bool */ public function is_expired() { if (time() &gt; strtotime($this-&gt;expiration_date)) return true; else return false; } /** * Determine if the coupon code has been used up * @access public * @param $uses int number of times coupon has been used * @return bool */ public function is_used($uses) { if ($this-&gt;uses &lt;= $uses) return true; else return false; } /** * Determine if discount is by percentage * @access public * @return bool */ public function is_percent() { if (substr($this-&gt;discount, -1) == "%") return true; else return false; } /** * Determine if discount is by dollar * @access public * @return bool */ public function is_dollar() { if (substr($this-&gt;discount, 0, 1) == "$") return true; else return false; } /* Coupon Sanitization ========================================================================== */ /** * @param $code * @return string * @throws Exception */ protected function check_code($code) { if (7 != strlen($code)) throw new Exception ('Discount code is the wrong length', 0); return sanitize_text_field($code); } /** * @param $discount * @return string * @throws Exception */ protected function check_discount($discount) { if (substr($discount, 0, 1) == "$" &amp;&amp; substr($discount, -1) == "%") throw new Exception ('Bad $ or %', 2); $chars = count_chars($discount, 1); if (isset($chars[ord('$')]) &amp;&amp; $chars[ord('$')] != 1) // Check if the discount has more than one $ throw new Exception ('Too many $', 2); if (isset($chars[ord('%')]) &amp;&amp; $chars[ord('%')] != 1) // Check if the discount has more than one % throw new Exception ('Too many %', 2); if (isset($chars[ord('$')]) &amp;&amp; isset($chars[ord('%')])) // Check if the discount has both $ and % throw new Exception ('Both % and $', 2); if (!isset($chars[ord('$')]) &amp;&amp; !isset($chars[ord('%')])) // Check if the discount has both $ and % throw new Exception ('No $ or %', 2); return sanitize_text_field($discount); } /** * @param $expiration_date * @return string * @throws Exception */ protected function check_expiration_date($expiration_date) { if (!strtotime($expiration_date) || time() &gt; strtotime($expiration_date)) throw new Exception ('Bad Date', 1); return sanitize_text_field($expiration_date); } /** * @param $name * @return string */ protected function check_name($name) { return sanitize_text_field($name); } /** * @param $uses * @return string * @throws Exception */ protected function check_uses($uses) { if (!is_int($uses) || $uses &lt; 0 ) throw new Exception ('Uses is not a positive integer', 3); if ($uses == 0) throw new Exception ('You can\' have a coupon with 0 uses'); return sanitize_text_field($uses); } /** * @param $user * @return string * @throws Exception */ protected function check_user($user) { if (!is_int($user)) throw new Exception ('User ID is not valid', 8); return sanitize_text_field($user); } /* Getters and Setters ========================================================================== */ /** * Set Coupon Code * @access public * @param $code string * @param $update bool if you want to update database */ public function setCode($code, $update = false) { $code = $this-&gt;check_code($code); if ($update) $this-&gt;update_coupon(false, $code, false, false, false, false); $this-&gt;code = $code; } /** * Get Coupon Code * @access public * @return string */ public function getCode() { return $this-&gt;code; } /** * Set Discount * @access public * @param $discount string (percentage or $ amount) with currency symbol * @param $update bool if you want to update database * @throws Exception */ public function setDiscount($discount, $update = false) { $discount = $this-&gt;check_discount($discount); if ($update) $this-&gt;update_coupon(false, false, $discount, false, false, false); $this-&gt;discount = $discount; } /** * Get Discount * @access public * @return string (percentage or $ amount) */ public function getDiscount() { return $this-&gt;discount; } /** * Set expiration date * @access public * @param $expiration_date string ISO 8601 * @param $update bool if you want to update database * @throws Exception */ public function setExpirationDate($expiration_date, $update = false) { $expiration_date = $this-&gt;check_expiration_date($expiration_date); if ($update) $this-&gt;update_coupon(false, false, false, $expiration_date, false, false); $this-&gt;expiration_date = $expiration_date; } /** * Get Expiration Date * @access public * @return string string ISO 8601 */ public function getExpirationDate() { return $this-&gt;expiration_date; } /** * Set Discount Name * @access public * @param $name string * @param $update bool if you want to update database */ public function setName($name, $update = false) { $name = $this-&gt;check_name($name); if ($update) $this-&gt;update_coupon($name, false, false, false, false, false); $this-&gt;name = $name; } /** * Get Discount Name * @access public * @return string */ public function getName() { return $this-&gt;name; } /** * Set Discount Uses * @access public * @param $uses int * @param $update bool if you want to update database * @throws Exception */ public function setUses($uses, $update = false) { $uses = $this-&gt;check_uses($uses); if ($update) $this-&gt;update_coupon(false, false, false, false, $uses, false); $this-&gt;uses = $uses; } /** * Get Discount Uses * @access public * @return int */ public function getUses() { return $this-&gt;uses; } /** * Set Coupon for User * @access public * @param $user int WP_User ID * @param $update bool if you want to update database * @throws Exception */ public function setUser($user, $update = false) { if ($update) $this-&gt;update_coupon(false, false, false, false, false, $user); $this-&gt;user = $user; } /** * Get User for which this coupon is for * @access public * @return int */ public function getUser() { return $this-&gt;user; } /** * Get Coupon users name * @uses get_user_by * @access public * @return string */ public function getUserName() { $user = get_user_by('id', $this-&gt;user); return $user-&gt;display_name; } } </code></pre>
[]
[ { "body": "<p>Typically method names on objects do not contain the object type being operated on. For example, instead of <code>update_coupon</code>, you would want to name it <code>update</code>, as that is what you are doing <em>to</em> the coupon. So it would be called like <code>testCoupon=&gt;update()</code> The \"coupon\" part is implicit based on the object you are operating on. A name like \"update_coupon\" would typically expect a <code>Coupon</code> as a parameter to update, ex: <code>testCoupon=&gt;update_with_coupon(otherCoupon)</code>.</p>\n\n<p>Along the same lines, <code>getUserName()</code> should likely be a <code>name()</code> method (or property if there is not extensive processing required to retrieve it, typically) on the <code>User</code> object. The <code>Coupon</code> should have no knowledge of how to retrieve a <code>User</code> object's name.</p>\n\n<p>You might want to stay consistent stylistically as well. Instead of having camel-case <code>getUserName()</code> intermixed with underscore-separated names <code>update_database()</code>.</p>\n\n<p>Also, with such tight-coupling between the object in question and the database entries, you may want to look into an Object Relation Mapper (ORM) framework to reduce the amount of boilerplate/CRUD code you need to write. Paris/Idiorm is a good one I've used for PHP in the past.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:31:16.407", "Id": "28037", "ParentId": "28023", "Score": "3" } }, { "body": "<p>I'm not seeing <em>blatant</em> non-OOPness, but there is a little funkiness here:</p>\n\n<ul>\n<li><p>The setters ideally should be usable -- and should be <em>used</em> -- everywhere you import potential user input into the object. Since they validate the data before modifying anything, if you use them consistently, you can ensure the coupon's fields are valid without actually having to check if they are every time.</p>\n\n<p>The problem is that your setters update the database. Besides the fact that modifying all the fields of a coupon means updating the <code>tj_coupons</code> option 6 times, things go sideways if i start with a new coupon and don't set <code>code</code> instantly. The functionalities of setting fields in the coupon and updating the database, should be separated and easily distinguishable. Perhaps have a public <code>save()</code> method or something.</p></li>\n<li><p>Your constructor is doing more work than it should. All it should really do is set stuff up. You might consider splitting up the functionality to add a new coupon vs retrieving an old one. </p>\n\n<pre><code>protected function __construct($coupon) {\n $this-&gt;name = $this-&gt;check_name($coupon['name']);\n $this-&gt;code = $this-&gt;check_code($coupon['code']);\n $this-&gt;discount = $this-&gt;check_discount($coupon['discount']);\n $this-&gt;expiration_date = $this-&gt;check_expiration_date($coupon['expiration_date']);\n $this-&gt;uses = $this-&gt;check_uses($coupon['uses']);\n $this-&gt;user = $this-&gt;check_user($coupon['user']);\n}\n\npublic static function withCode($code) {\n $coupons = get_option('tj_coupons', array());\n $C_code = 'C_' . $coupon['code'];\n\n if (!isset($coupons[$C_code]))\n throw new Exception ('Coupon code does not exist', 5);\n\n return new TJ_Coupon($coupons[$C_code]);\n}\n\npublic static function create($coupon) {\n $coupons = get_option('tj_coupons', array());\n\n # I personally prefer failing as early as possible.\n # Here, you fail the instant you see a bad coupon code,\n # rather than doing a bunch of work you're just going to toss out.\n $C_code = 'C_' . $coupon['code'];\n if (!isset($coupon['code']) or isset($coupons[$C_code]))\n throw new Exception ('Coupon code already exists', 4);\n\n $new_coupon = new TJ_Coupon($coupon);\n $new_coupon-&gt;update_coupon();\n return $new_coupon;\n}\n</code></pre>\n\n<p>And then you'd use it like</p>\n\n<pre><code>$existing = Coupon::withCode('ABCD1234');\n\n$created = Coupon::create(array(\n 'code' =&gt; 'stuff',\n 'name' =&gt; 'new coupon',\n ... other fields ...\n));\n</code></pre></li>\n<li><p>Oh, and as has already been mentioned, <code>$coupon-&gt;update_coupon()</code> is redundant. Consider your method names as commands to the object or info about it. The object already knows what it is; you don't have to tell it. :)</p></li>\n<li><p>The functions like <code>check_user</code> and <code>check_discount</code>, that do nothing more than validate a parameter against hard-coded rules, other parameters, or data unrelated to the instance, could be <code>static</code>. </p></li>\n<li><p>An if/else to determine whether to return true or false is largely unnecessary. Boolean expressions evaluate to a value. Just return the expression you're comparing or testing. For example,</p>\n\n<pre><code>if (time() &gt; strtotime($this-&gt;expiration_date))\n return true;\nelse\n return false;\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>return time() &gt; strtotime($this-&gt;expiration_date);\n</code></pre></li>\n<li><p><code>can_user_use($user_id)</code> looks like it always returns false. (<code>if ((condition)) return false; else return (condition);</code> could only ever return true if <code>condition</code> evaluates to false the first time and true the second. If that's the case, $DEITY help the maintainer of this code.)</p>\n\n<p>I might make it look like</p>\n\n<pre><code>public function can_user_use($user_id)\n{\n return (!$this-&gt;for_user() or $user_id == $this-&gt;user);\n}\n</code></pre>\n\n<p>if the logic is as i understand it.</p></li>\n<li><p><code>check_discount</code> seems more complicated than it has to be, and a bit error prone.</p>\n\n<ul>\n<li>It doesn't do much validation other than counting characters. The current validation allows for ugliness like <code>42$50</code> and <code>%10$</code>.</li>\n<li>Are the chances of someone putting two $ signs, or two % signs, really so high that it's worth having separate error messages for?</li>\n</ul>\n\n<p>You should probably be checking against a regex rather than just counting chars. If the regex matches, and it's correct, you can safely assume the input format is valid. (You might still want to check that the number part is within a certain range, so you don't have 150% coupons. But you can know for sure that the discount <em>looks</em> correct.)</p>\n\n<p>For example:</p>\n\n<pre><code>protected function check_discount($discount)\n{\n $ok = preg_match('/^(\\$?)(\\d*(?:\\.\\d+)?)(%?)$/', $discount, $matches);\n # make sure there's a match, with a number and exactly one of $ or %\n if (!($ok and $matches[2] and ($matches[1] xor $matches[3]))) {\n throw new UnexpectedValueException(\n \"'$discount' doesn't match \\$number or number%\", 2\n );\n }\n\n # sanitizing is no longer strictly necessary. It won't do anything useful,\n # since we've already disqualified whatever it'd clean up.\n return $discount;\n}\n</code></pre></li>\n<li><p>By the way, note how above, i threw an <code>UnexpectedValueException</code> rather than an <code>Exception</code>. (I was originally going to suggest <code>InvalidArgumentException</code>, but it's a \"logic exception\" -- it basically implies that there's a bug in the script, rather than a bug in the input.)</p>\n\n<p><strong>Never throw <code>new Exception</code>.</strong> The type of the exception object is itself information about the error, and can be used in a <code>catch</code> to differentiate between exceptions you are prepared to handle and ones that should continue to bubble up. Without that extra info, you basically have to catch everything if you catch anything, and exceptions start becoming too unwieldy to be worth the trouble.</p>\n\n<p>Always throw some subtype that provides more info about the exception. Some people will advocate throwing based on the location of the error, and recommend you have a <code>CouponException</code> or other such junk. I don't; to me, that's not much better than <code>Exception</code>. But even those people at least ensure that the name provides useful info. (They just provide the wrong info in that name. :P) I'd recommend instead throwing exceptions based on the reason behind the error.</p>\n\n<p>On the other side, you should almost never <code>catch (Exception $e)</code> either. It catches everything, requiring you to disambiguate, and can hide errors that really should have been allowed to bubble up. Instead, catch the types of exceptions you are prepared to handle, and let everything else propagate.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T15:27:18.853", "Id": "28085", "ParentId": "28023", "Score": "5" } } ]
{ "AcceptedAnswerId": "28085", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T03:32:48.543", "Id": "28023", "Score": "4", "Tags": [ "php", "e-commerce" ], "Title": "Coupon code manager" }
28023
<p>There's this Ajax-heavy, jQuery-based site which I'm about to work on. There hasn't been much structure in the JavaScript code so far (lots of functions at global scope, hard-coded in the HTML <code>onclick="something(args);"</code>. How can I improve upon that and introduce some structure?</p> <p>Here's what I've tried. This part is supposed to handle a single element which consists of a text field (span) which is replaced by an input on focus and runs an AJAX update call when a <kbd>submit</kbd> button is clicked or <kbd>enter</kbd> is pressed.</p> <pre><code>$(function() { var box = $('.foobar-info'), input = box.find('input'), label = box.find('span#name'), button = box.find('button'); label.click(start_edit); button.click(submit); input.keypress2(KEYS.enter, submit); function start_edit() { box.addClass('is-edit'); } function submit() { MyAjaxModule.edit_foobar(save_success, {'id': GLOBAL_FOO_ID, 'value': input.val()}); } function save_success(data) { label.text(input.val()); box.removeClass('is-edit'); } }); </code></pre> <p>Showing and hiding of parts is driven by the CSS:</p> <pre><code>.foobar-info .state-display {display: inline;} .foobar-info .state-edit {display: none;} .foobar-info.is-edit .state-display {display: none;} .foobar-info.is-edit .state-edit {display: inline;} </code></pre> <p>So far this achieves:</p> <ul> <li>keeps the behaviour away from the markup</li> <li>keeps relevant behaviour together in one block</li> </ul> <p>On the other hand, I don't think it's <strong>testable</strong> or particularly <strong>easy to re-use with different configurations</strong>.</p> <p>I've attempted to rewrite this to use objects and <code>this.</code> lookups instead of the big closure, but didn't end up in a code that would please me. For example, this part</p> <pre><code>label.click(start_edit); </code></pre> <p>would look like</p> <pre><code>this.label.click(this.start_edit.bind(this)); </code></pre> <p>which looks really verbose plus it's super-easy to forget the unwieldy <code>.bind(this)</code> part.</p> <p><a href="http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/" rel="nofollow">This article</a> served some inspiration, but felt rather hacky to me, mostly because relying on global name lookups.</p> <p>Questions:</p> <ul> <li>Any particular problems with my approach except what I've mentioned so far? How can I solve it?</li> <li>Is there a canonical way to structure the code which I'll be happy to incorporate?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:52:10.587", "Id": "43752", "Score": "0", "body": "The Module Pattern mentioned in that article is really great for projects like this because you can add/remove functionality in a jiffy. Also check out the Observer Pattern, aka Pub/Sub, which might be helpful with structuring your AJAX calls." } ]
[ { "body": "<p>If this is a sizable component on your page which has state and a UI that reflects that state and, optionally, the data is server-backed, you might want to invest in the use of a framework. Try <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a> (or MVC-like) frameworks like <a href=\"http://backbonejs.org/\" rel=\"nofollow\">Backbone.js</a> and others. In addition, use templating frameworks for the UI. My choice is <a href=\"https://github.com/janl/mustache.js/\" rel=\"nofollow\">Mustache</a>, but still, there are a lot more.</p>\n\n<p>This will split your code into the View, which is your UI. There's the Controller, otherwise known as the logic of the component. Then there's the Model, which is the data, usually split between local and server data, synced. Note that some frameworks are not strictly MVC but should serve the same purpose.</p>\n\n<p>By now you might think \"Sure, the code is now split up into separate components. But there are many components, what should I do?\". Module management comes into play with dependency management libraries. I usually use <a href=\"http://requirejs.org/\" rel=\"nofollow\">RequireJS</a>. These libraries manage the proper loading of required scripts before the scripts that require them execute.</p>\n\n<p>So in summary, you split your code into parts of the MVC, glue them together with the dependency manager.</p>\n\n<hr>\n\n<p>On the other hand, if this is component is somewhat small, then you might opt to make a widget/plugin. You might still need the MVC approach, but instead of using a baked framework, you roll your own. It's as simple as abstracting a few low-level operations into generic functions and data structures and you are good to go.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript\" rel=\"nofollow\">OOP concepts in JS</a> would be your best friend here, as you can encapsulate several entities into objects. For example, you can create a View object and have it hold the UI elements of interest and several render methods. You can make a Model object which holds a simple data structure, and a few <a href=\"http://en.wikipedia.org/wiki/Create,_read,_update_and_delete\" rel=\"nofollow\">CRUD methods</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:33:50.223", "Id": "28139", "ParentId": "28030", "Score": "1" } }, { "body": "<p>There are two schools of thought</p>\n\n<ul>\n<li>Programmatic</li>\n<li>Declarative</li>\n</ul>\n\n<p>Your example here is programmatic, where JavaScript is binding events after the DOM load. The problem I have with programmatic is, using your words, although it <em>\"keeps the behavior away from the markup\"</em> it moves the markup into the behavior. The interface that is needed to reuse the same JavaScript is now tied to what is defined on the page. Using declarative, your example being <code>onclick=\"something(args);\"</code>, I can more easily follow a Model View Presenter (MVP) pattern where the view simply forwards all events to the Presenter to perform the business logic.</p>\n\n<p>Here the events can be organized into a class object to remove them from the global namespace. Scope can be controlled by passing in the model as a parameter.</p>\n\n<p><strong>presenter.js</strong></p>\n\n<pre><code>function Presenter(parameter) {\n\n // private variables\n var myVar;\n\n // public method\n this.submit = function() {\n };\n\n // private method\n function doSomething() {\n }\n}\n</code></pre>\n\n<p><strong>page.html</strong></p>\n\n<pre><code>...\n&lt;script type=\"text/javascript\" src=\".../presenter.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n var presenter = new Presenter(...);\n&lt;/script&gt;\n...\n&lt;button onclick=\"presenter.onButtonClick();\"&gt;Click me&lt;/button&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T19:14:01.467", "Id": "28260", "ParentId": "28030", "Score": "2" } }, { "body": "<p>I don't know what those first two answers are about, they're completely inappropriate IMO; There's no way this solution calls for MVC or for declarative syntax. Your code is beautiful exactly the way it is; honestly it's very well done. </p>\n\n<p>I did have a little trouble matching up the variables with the click handlers because you coded them in a different order and I got confused; inlining the calls like this eliminates that problem, and you don't need those temporary variables any more.</p>\n\n<pre><code>$(function() {\n var box = $('.foobar-info'),\n box.find('input').keypress2(KEYS.enter, submit);\n box.find('span#name').click(start_edit);\n box.find('button').click(submit);;\n ///etc.\n</code></pre>\n\n<p>Naturally you still need the \"label\" variable so your handler can get it. Although personally I have a thing about keeping my variables very tightly scoped (especially in Javascript where a C# developer tends to be surprised by variable hoisting and other lovely subtleties in Javascript) so I would actually write it all out in the handler, like this:</p>\n\n<pre><code>function save_success(data) {\n $('.foobar-info span#name').removeClass('is-edit');\n}\n</code></pre>\n\n<p>Not saying this is better-- it will have (very) slightly worse performance-- but I think it is clearer and more maintainable. Totally a matter of taste. (If you are going to keep a variable for \"label,\" I would suggest using a more descriptive name. If you're minifying your JS files there's no reason not to use longer names).</p>\n\n<p>One other small note. This selector</p>\n\n<pre><code>$('span#name')\n</code></pre>\n\n<p>will not perform as well as </p>\n\n<pre><code>$('#name')\n</code></pre>\n\n<p>and for your purposes should do exactly the same thing, assuming there is only one element with an ID of \"name.\" The subtle difference is the 'span#name' will use jquery's Javascript code and can possibly return a set of elements; using '#name' only will use the getElementById built-in method (which is way faster) and will never return more than one element (usually the first one that matches). In theory a valid DOM document has unique IDs so the distinction is only useful in special situations (e.g. rows generated dynamically that all have the same ID).</p>\n\n<p>While we're going over JQuery internals here's another tip. This line</p>\n\n<pre><code>var box = $('.foobar-info')\n</code></pre>\n\n<p>is not very efficient on older browsers-- it will result in a complete DOM scan. If possible, prefix with something like</p>\n\n<pre><code>var box = $('div.foobar-info')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T01:51:40.217", "Id": "33893", "ParentId": "28030", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T09:08:51.387", "Id": "28030", "Score": "6", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Handling a text field and submit button with Ajax" }
28030
<p>I have come across a fun puzzle, sorting a linked list, and I wanted to go for quicksort. However, I am not quite sure whether my partitioning algorithm is efficient enough. I also believe that my code is not clean.</p> <p>Is it possible to remove some variables or make it more efficient?</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; struct Node { int data; Node *next; }; void printList(Node *list) { Node *temp = list; while(temp != NULL) { cout&lt;&lt;temp-&gt;data&lt;&lt;" "; temp = temp-&gt;next; } } int partition(Node *list, int start, int end) { Node *startPtr = list, *endPtr = list, *head = list; for(int i = 0; i &lt; start; i++) if(startPtr == NULL || startPtr-&gt;next == NULL) return -1; startPtr = startPtr-&gt;next; for(int i = 0; i &lt; end; i++) { if(endPtr == NULL || endPtr-&gt;next == NULL) return -1; endPtr = endPtr-&gt;next; } Node *temp = NULL, *temp2 = startPtr; int pivot = endPtr-&gt;data; while(temp2-&gt;next != endPtr) { if(temp2-&gt;data &lt; pivot) { if(temp != NULL) temp = temp-&gt;next; else temp = startPtr; swap(temp-&gt;data, temp2-&gt;data); } temp2 = temp2-&gt;next; } temp = temp-&gt;next; swap(temp-&gt;data, endPtr-&gt;data); int index; Node *temp3 = list; for(index = 0; temp3-&gt;data != pivot; index++) temp3 = temp3-&gt;next; return index; } int main() { Node *a = new Node; Node *b = new Node; Node *c = new Node; Node *d = new Node; Node *e = new Node; Node *f = new Node; a-&gt;next = b; a-&gt;data = 2; b-&gt;next = c; b-&gt;data = 6; c-&gt;next = d; c-&gt;data = 3; d-&gt;next = e; d-&gt;data = 1; e-&gt;next = f; e-&gt;data = 7; f-&gt;data = 5; cout&lt;&lt;partition(a, 0, 5)&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T11:26:22.013", "Id": "43733", "Score": "0", "body": "Can you please look at your code again? For me it looks like as if you forgot brackets in the first `for` loop in the function `partition`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T12:35:21.383", "Id": "43736", "Score": "1", "body": "I recommend fixing the indentation. That makes the code a lot more pleasant to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T13:49:19.863", "Id": "43799", "Score": "0", "body": "Please add a statement of the exact puzzle. Reading your code doesn't make it clear to me. Running it just prints '3'. And `printList` is unused..." } ]
[ { "body": "<p>Yeah, you're missing brackets, but I think I get what you're trying to do. If I'm wrong, ignore this obviously.</p>\n\n<p><code>printList</code> can just use a <code>for</code>-loop:</p>\n\n<pre><code>void printList(Node *list)\n{\n\n for(Node *temp = list; temp != NULL; temp = temp-&gt;next;)\n {\n cout&lt;&lt;temp-&gt;data&lt;&lt;\" \";\n }\n} \n</code></pre>\n\n<p>Now for the partition function, you're always returning <code>-1</code> if <code>startPtr == NULL</code> or <code>endPtr == NULL</code>. But you say that those point to what list points to (at the start of the function). In that case, just check if list is null first. Your function won't do anything if it is anyway:</p>\n\n<pre><code>if(list == NULL)\n return -1;\n</code></pre>\n\n<p>Now in those <code>for</code>-loops, all you have to do is check if <code>startPtr-&gt;next</code> and <code>endPtr-&gt;next == NULL</code>.</p>\n\n<p>In your <code>while</code> loop, you have this code:</p>\n\n<pre><code>if(temp2-&gt;data &lt; pivot)\n{\n if(temp != NULL)\n temp = temp-&gt;next;\n else\n temp = startPtr;\n\n swap(temp-&gt;data, temp2-&gt;data);\n}\n</code></pre>\n\n<p>But what if, for example, <code>temp == NULL</code> and <code>temp2 == startPtr</code>? Assuming <code>swap()</code> does what it says it does, you're unnecessarily swapping values. It might be expensive, and it might not be. I dunno. The function might also do something weird if you try to swap the same exact values. (As a side note, you're just passing the value of data. If swap doesn't take values by reference, you won't actually be doing anything to <code>temp-&gt;data</code> and <code>temp2-&gt;data</code>).</p>\n\n<p>Also, in the declaration of your <code>while</code> loop, you're not checking for if <code>temp2 == NULL</code>.</p>\n\n<pre><code>while(temp2-&gt;next != endPtr) //This is will throw a Null Pointer Access Violation exception if temp2 == NULL\n</code></pre>\n\n<p>This could happen, because you aren't checking if <code>temp2-&gt;next == NULL</code> before you say <code>temp2 = temp2-&gt;next</code>. If it ever is, your loop will crash the program. I don't know if it's possible for <code>temp2</code> to reach the end of the list, but if it is, you should just add a conditional.</p>\n\n<p>After your <code>while</code>-loop, you have:</p>\n\n<pre><code>temp = temp-&gt;next;\nswap(temp-&gt;data, endPtr-&gt;data);\n</code></pre>\n\n<p>That could potentially cause the same problems I described before.</p>\n\n<p>Anyway, these are just suggestions. I didn't check thoroughly to see if there were variables you could remove, though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T13:27:35.423", "Id": "28036", "ParentId": "28032", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T10:12:59.623", "Id": "28032", "Score": "1", "Tags": [ "c++", "performance", "linked-list" ], "Title": "Efficiency of a linked list partitioning algorithm" }
28032
<p>I have the following code, which does the following:</p> <p>Reads from the packet from UDP (SNMP) into an array, check if this number is > 127, if yes then '&amp;' this with 127, now pad it with leading zero's to make it 7 bits in total. Combine it with result. Now check the next one in the packet and repeat the above. It works for if 3 numbers > 127. Can this code be optimized check for unlimited throughout the length of the array</p> <p>Please do let me know if you require any further information.</p> <p>Thank you.</p> <pre><code> int[] obj = new int[Objectlength]; string result = string.Empty; for (int cnt = 0; cnt &lt; Objectlength; cnt++) { obj[cnt] = Convert.ToInt16(packet[objectstart]); objectstart++; if (obj[cnt] &gt;127) { int brush = 127; int bin = obj[cnt] &amp; brush; string binR1 = Convert.ToString(bin, 2).PadLeft(7, '0'); result = result + binR1; cnt++; if ((packet[objectstart] &gt; 127) | (packet[objectstart] &lt; 127)) { Console.WriteLine(packet[objectstart]); int bin1 = packet[objectstart] &amp; brush ; binR1 = Convert.ToString(bin1, 2).PadLeft(7, '0'); result = result + binR1; obj[cnt] = Convert.ToInt16(packet[objectstart]); cnt++; objectstart++; if ((packet[objectstart] &gt; 127) | (packet[objectstart] &lt; 127)) { Console.WriteLine(packet[objectstart]); int bin2 = packet[objectstart] &amp; brush; binR1 = Convert.ToString(bin2, 2).PadLeft(7, '0'); result = result + binR1; obj[cnt] = Convert.ToInt16(packet[objectstart]); objectstart++; } } } } </code></pre>
[]
[ { "body": "<p>First things first. Your variable names are not very well thought out. Even after I decode it, <code>cnt</code> or <code>count</code>?? does not describe what it does. I think a better name would be <code>currentIndex</code>.</p>\n\n<p>Second, C# standards say to use camelCasing for variable names. I would also read up on <code>var</code>, it is a very useful keyword for cleaning up code.</p>\n\n<p>Third, <code>brush</code> should be a constant, if you follow my suggestion on the change to recursion, it should be made a class constant.</p>\n\n<p>I also don't like that cnt is incremented outside of the loop.</p>\n\n<p>Now onto the main question.</p>\n\n<p>Just seeing <code>if ((packet[objectstart] &gt; 127) | (packet[objectstart] &lt; 127))</code> twice in the same structure (one inside the other one) is a huge code smell to me, especially when it is the same code inside the second, as it is the first. This looks like a good case for recursion, a method calling itself.</p>\n\n<p>It would go something like this:</p>\n\n<pre><code>private string ProcessSegment(int[] obj, int currentIndex, int objectStart, dynamic[] packet)\n{\n if ((packet[objectstart] != 127) || currentIndex &gt; Objectlength)\n {\n return string.Empty;\n }\n\n Console.WriteLine(packet[objectstart]);\n\n var bin2 = packet[objectstart] &amp; brush;\n binR1 = Convert.ToString(bin2, 2).PadLeft(7, '0');\n\n obj[currentIndex] = Convert.ToInt16(packet[objectstart]);\n\n return binR1 + ProcessSegment(obj, currentIndex++, objectStart++, packet);\n}\n</code></pre>\n\n<p>Your calling code will look something like:</p>\n\n<pre><code>obj[cnt] = Convert.ToInt16(packet[objectstart]);\nobjectstart++;\n\nif (obj[cnt] &gt;127)\n{\n result += ProcessSegment(obj, cnt++, objectstart++, packet);\n}\n</code></pre>\n\n<p>I have no way of testing this, but I think it should work. Also note, please change the dynamic in the <code>ProcessSegment</code> call to be whatever the packet variable is</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T00:22:39.727", "Id": "43772", "Score": "0", "body": "Good comments overall. Tail recursion is usually fun, but in this case you end up concatenating the strings, which is somewhat slow. I would yield substrings / characters using a while / for loop instead. Looks like IEnumerable and recursion can be combined, but the result is slow. http://stackoverflow.com/questions/2055927/ienumerable-and-recursion-using-yield-return" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T01:24:54.663", "Id": "43776", "Score": "0", "body": "@Leonid that is true, and there are ways to get around it. I was trying to keep it relevant to the question so the OP could see what was done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T03:52:20.610", "Id": "43779", "Score": "0", "body": "@JeffVanzella: Yes the I didn't like the recursive if statements either so I sat down yesterday and did the method thing. I haven't tested your's so I'm not sure about this one, but it's worth a try. I take other comments of yours like naming etc. This is a great answer. Hands up for that. Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:11:22.013", "Id": "28042", "ParentId": "28033", "Score": "1" } } ]
{ "AcceptedAnswerId": "28042", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T10:30:38.317", "Id": "28033", "Score": "1", "Tags": [ "c#", "optimization", ".net" ], "Title": "C# code - SNMP packet processing" }
28033
<p>I come from a C background and need help refactoring the following imgur image uploader script I wrote.</p> <p>It checks if a <code>token_file</code> with <code>access_token</code> and <code>refresh_token</code> exists. If not, it instructs the user to go to a webpage, allow access to my app and enter the PIN generated from the site back to my program so that I can exchange it with access and refresh tokens.</p> <p>I upload the picture taken with the 'scrot' utility to the users album, put the direct link on clipboard, and show a system notification. I'm not using the libnotify gem because it segfaults.</p> <p>If the upload failed because the <code>access_token</code> is expired, which lasts only 60 minutes, I use the refresh token I got from the first authorization step, get a new one and update the <code>token_file</code> as well.</p> <p>I know I should be using a class to keep things more organized. </p> <p>I just don't know what's the best way to deal with info like <code>client_id</code> and <code>token_file</code>. Should they be instance or class methods? Also what should I put in the <code>initialize</code> method, the reading of tokens from the file or launch scrot?</p> <p>I know I don't error check for everything yet.</p> <pre><code>#!/usr/bin/env ruby require 'httparty' require 'json' require 'clipboard' $client_id = 'xxxxxxxxxxx' $client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' $token_file = '.imgur_token' def auth_app puts 'Follow the link to allow the application access to your account and enter the pin', "https://api.imgur.com/oauth2/authorize?client_id=#{$client_id}&amp;response_type=pin" print 'Pin: ' pin = STDIN.gets.chomp response = HTTParty.post 'https://api.imgur.com/oauth2/token', :body =&gt; { 'client_id' =&gt; $client_id, 'client_secret' =&gt; $client_secret, 'grant_type' =&gt; 'pin', 'pin' =&gt; pin } if response['access_token'] == nil puts 'Authorization failed' else tokens = { 'access_token' =&gt; response['access_token'], 'refresh_token' =&gt; response['refresh_token'] } File.write($token_file, tokens.to_json) end tokens end def refresh_token(refresh_token) response = HTTParty.post 'https://api.imgur.com/oauth2/token', :body =&gt; { 'refresh_token' =&gt; refresh_token, 'client_id' =&gt; $client_id, 'client_secret' =&gt; $client_secret, 'grant_type' =&gt; 'refresh_token' } response['access_token'] end def upload_image(access_token) response = HTTParty.post 'https://api.imgur.com/3/upload.json', :headers =&gt; { 'Authorization' =&gt; "Bearer #{access_token}" }, :body =&gt; { 'image' =&gt; Base64.encode64(File.read('imgur.png')) } response['data']['link'] end abort('scrot not found') unless system('scrot -s imgur.png') tokens = File.exists?($token_file) ? JSON.parse(File.read($token_file)) : auth_app if (link = upload_image(tokens['access_token'])) == nil tokens['access_token'] = refresh_token(tokens['refresh_token']) link = upload_image(tokens['access_token']) File.write($token_file, tokens.to_json) end if link != nil Clipboard.copy link system('notify-send Upload complete') else system('notify-send Upload error') end File.delete('imgur.png') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:23:59.517", "Id": "43748", "Score": "0", "body": "As a suggestion, using `$` global variables is a first sign something is awry. CONSTANTS are a better choice usually, or pass the value in as a parameter to the method." } ]
[ { "body": "<p>I'd do it something like this. Comments are sprinkled throughout:</p>\n\n<pre><code>#!/usr/bin/env ruby\n\nrequire 'httparty'\nrequire 'json'\nrequire 'clipboard'\n</code></pre>\n\n<p>Use constants instead of globals:</p>\n\n<pre><code>CLIENT_ID = 'xxxxxxxxxxx'\nCLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\nTOKEN_FILE = '.imgur_token'\n</code></pre>\n\n<p>Move strings that are subject to change to the top of the file for easy access:</p>\n\n<pre><code>AUTHORIZE_URL = \"https://api.imgur.com/oauth2/authorize?client_id=#{ CLIENT_ID }&amp;response_type=pin\"\nTOKEN_URL = 'https://api.imgur.com/oauth2/token'\n\ndef auth_app\n</code></pre>\n\n<p>I prefer to see separate strings being printed on individual lines, rather than split them with <code>,</code> and let <code>puts</code> do it. It helps the code reflect what the output will be:</p>\n\n<pre><code> puts 'Follow the link to allow the application access to your account and enter the pin:'\n puts AUTHORIZE_URL\n\n print 'Pin: '\n pin = STDIN.gets.chomp\n</code></pre>\n\n<p>I know it's common/popular in Ruby to not use parenthesis to delimit parameters to methods, but I always use them. It visually separates the parameters from the method name, and also forces the correct parsing in ambiguous cases when blocks are also passed in. </p>\n\n<p>Also, I prefer to see the parameters on separate lines from opening/closing braces and brackets when there is more than a trivial array or hash. Again, it's a readability thing:</p>\n\n<pre><code> response = HTTParty.post(\n TOKEN_URL,\n :body =&gt; {\n 'client_id' =&gt; CLIENT_ID,\n 'client_secret' =&gt; CLIENT_SECRET,\n 'grant_type' =&gt; 'pin',\n 'pin' =&gt; pin \n }\n )\n</code></pre>\n\n<p>I reversed the order of the test for clarity and simplicity. Rather than test for <code>nil</code>, I test for the \"positive\" condition, which is a simpler test:</p>\n\n<pre><code> if response['access_token']\n tokens = {\n 'access_token' =&gt; response['access_token'],\n 'refresh_token' =&gt; response['refresh_token'] \n }\n File.write(TOKEN_FILE, tokens.to_json)\n else\n puts 'Authorization failed'\n end\n tokens\nend\n\ndef refresh_token(refresh_token)\n\n response = HTTParty.post(\n TOKEN_URL,\n :body =&gt; {\n 'refresh_token' =&gt; refresh_token,\n 'client_id' =&gt; CLIENT_ID,\n 'client_secret' =&gt; CLIENT_SECRET,\n 'grant_type' =&gt; 'refresh_token' \n }\n )\n\n response['access_token']\nend\n\ndef upload_image(access_token)\n\n response = HTTParty.post 'https://api.imgur.com/3/upload.json',\n :headers =&gt; { 'Authorization' =&gt; \"Bearer #{access_token}\" },\n :body =&gt; { 'image' =&gt; Base64.encode64(File.read('imgur.png')) }\n\n response['data']['link']\nend\n\nabort('scrot not found') unless system('scrot -s imgur.png')\n\nif File.exists?(TOKEN_FILE)\n tokens = JSON.parse(File.read(TOKEN_FILE))\nelse\n tokens = auth_app\nend\n</code></pre>\n\n<p>I do NOT like seeing an assignment inside the conditional test. It's confusing and an error-in-waiting in the future if someone things you meant to do an equality check and \"corrects\" the code:</p>\n\n<pre><code>link = upload_image(tokens['access_token'])\n</code></pre>\n\n<p>Again, I reversed the test:</p>\n\n<pre><code>if (!link)\n tokens['access_token'] = refresh_token(tokens['refresh_token'])\n link = upload_image(tokens['access_token'])\n File.write(TOKEN_FILE, tokens.to_json)\nend\n</code></pre>\n\n<p>I reversed the test and assign a message to a string so I can fall through and use a single <code>system</code> invocation:</p>\n\n<pre><code>if link\n response_msg = 'notify-send Upload error'\nelse\n Clipboard.copy link\n response_msg = 'notify-send Upload complete'\nend\nsystem(response_msg)\n\nFile.delete('imgur.png')\n</code></pre>\n\n<p>In general I think your code is pretty good, with just a few tweaks that I'd do. I'd rather write my code as clearly and cleanly as I can, even for trivial stuff, because I never know when I'll need to revisit it. Sometimes I have to tweak something a year or two later, so being able to comprehend what the heck I was thinking quickly is important.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T18:57:32.407", "Id": "28044", "ParentId": "28038", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:45:41.233", "Id": "28038", "Score": "1", "Tags": [ "ruby", "api" ], "Title": "How should I refactor my image uploader script?" }
28038
<p>Here is a function I wrote that can read chunks of large files (> 3 GB). It's designed to be used contentiously so that one can use it in a while loop until it returns EOF. </p> <p>It's an early prototype and is only written to work under 32-bit Linux.</p> <p>I'm okay with feedback on readability, maintainability, or anything else.</p> <pre><code>/** * Reads a chunk of given size into memory (heap) from file. Chunk size is * measured in amount of pages. * * The chunk will be allocated before reading starts. So no matter what * the return code you always need to decref the chunk. * * Parameters: * - pages : The amount of pages to read to memory. The size of a page * a page differs from different systems, but it is usually 4 KiB. * See getpagesize or _SC_PAGESIZE for sysconf in unistd.h for * details. * - start_pos: The position in the file to start reading from * - *end_pos : Pointer to the location where the end position of the * reading shall be placed. This will be the byte after the last * read byte, so that read_chunk can be called with this value * as start_pos directly. * - **chunk : Pointer to the pointer of an byte array where the result * will be placed in. * * Return values: * - Returns 0 on success * - Returns -1 if chunk size was above 2^31 bits (~ 2 GB) * - Returns -2 if an fseek error occured, see errno for details * - Returns -3 if an fread error occured, see errno for details * - Returns -4 on EOF */ int8_t read_fachunk( FILE *f, uint16_t pages, uint64_t start_pos, uint64_t *end_pos, struct byte_array **chunk) { assert(f != NULL); assert(end_pos != NULL); assert(chunk != NULL); assert(pages != 0); uint64_t chunk_b = pages * sysconf(_SC_PAGESIZE); if(chunk_b &gt; MAX_CHUNK_SIZE) { return -1; } uint64_t curr_pos = 0; int64_t err = lseek64(fileno(f), start_pos, SEEK_SET); *chunk = byte_array_create(chunk_b); if (err == -1) return -2; curr_pos = fread((*chunk)-&gt;bytes, sizeof(uint8_t), chunk_b, f); (*chunk)-&gt;curr_i = curr_pos; if (ferror(f) != 0) { err = -3; goto complete; } if (feof(f) != 0) { err = -4; goto complete; } err = 0; complete: *end_pos = start_pos + curr_pos; return err; } </code></pre>
[]
[ { "body": "<p>Here are a few comments on your function.</p>\n\n<p>Firstly taking the prototype, why return an <code>int8_t</code>. A simple <code>int</code> is better\nas <code>uint8_t</code> will probably be slower. Also returning several types of error\nis unusual in UNIX functions like this. I'd expect <code>errno</code> to tell what\nfailed and suggest you return the number of bytes read, 0 on EOF and -1 on\nerror (like read(2)).</p>\n\n<p>And again on the prototype, why are you passing a <code>FILE</code> instead of a\ndescriptor? Passing a FILE and then messing around with the raw descriptor\nmakes me uneasy.</p>\n\n<hr>\n\n<p>You allocate a strange structure in the function. This is odd for a low level\nutility. It is unnecessary and arguably wrong, as it means the caller cannot\navoid an allocation even if the buffer from the last call can be reused or a\nstatic buffer is available. Just pass a buffer and its size (as a <code>size_t</code>)\ninto the call.</p>\n\n<p>And it would be more normal to pass in the size to read (as a <code>size_t</code>)\ninstead of the number of pages. If you pass a buffer and its size as I\nsuggested above, you don't need an extra size to say how much to read.</p>\n\n<hr>\n\n<p>You are mixing use of buffered <code>fread</code> (operating on a FILE) and <code>lseek</code> (on\nan fd). This is a bad idea as you are messing with something the FILE has\nreason to call its own. If you are going to seek, then use <code>read</code> to read the\ndata.</p>\n\n<p>And in your use of <code>fread</code>, the call returns the number of items read (number\nof bytes in this case) so assigning that to a variable called <code>curr_pos</code> is\nnot sensible. The name <code>nread</code> would make more sense. And keeping that value\nin the <code>byte_array</code> structure with a different, equally meaningless name,\n<code>curr_i</code>, is unnecessary.</p>\n\n<p>Also, reading up to end-of-file might return less than requested. That is\n<strong>not</strong> an error from the perspective of this function (it might be from an\napplication perspective if the file size is expected to be multiples of page\nsize, but the handling of such an error doesn't belong here). So calling\n<code>feof</code> and treating end-of-file as an error is wrong. There is only a\npossible error it <code>nread != chunk_b</code>. But you should be using <code>read(2)</code>...</p>\n\n<hr>\n\n<p>Some other points:</p>\n\n<ul>\n<li><p>your <code>goto</code> statements are unnecessary. Occasionally gotos are useful in\nsimplifying error recovery, but in this case they simplify nothing.</p></li>\n<li><p>your <code>end_pos</code> is unnecessary. The file descriptor knows its current\noffset, which is available with <code>fseek(fd, 0, SEEK_CUR)</code></p></li>\n<li><p><code>chunk_b</code> is a bad name for a size, don't you think? </p></li>\n<li><p>test the return from lseek immediately. If you have a <code>stderr</code>, use <code>perror</code>\nto print the reason for failure (perhaps best in the calling functions).</p></li>\n<li><p>use of <code>sizeof(uint8_t)</code> is silly - just use 1</p></li>\n</ul>\n\n<p><strong>EDIT</strong></p>\n\n<p>FILEs and <code>fopen</code>, <code>fwrite</code>, <code>fread</code>, <code>fprintf</code>, <code>fgets</code> etc are provided by <code>stdio</code> for use as buffered IO in which the standard library maintains a buffer through which your requests are served. When you use <code>fread</code> to read (say) 10 bytes, the library might read a whole page or disc sector or line of input from the terminal (on the assumption that you'll want the rest later) and give you just the amount you asked for, saving the rest in the buffer. The \"file descriptor\" (fd), which is returned by <code>fileno</code>, is the lower level interface to the actual file returned by <code>open</code> (type <code>man 2 open</code> on UNIX/Linux/MacOS) - <code>open</code> is used by <code>fopen</code> to open the actual file/device. </p>\n\n<p>If you are doing unbuffered or 'raw' IO, you can use open/write/read/lseek etc to save the overhead of the stdio and to give you more control. Since you are explicitly seeking to the location you want to read, you are certainly doing raw (unbuffered) IO and the lower-level interface makes more sense. </p>\n\n<p>On the interaction between buffered and unbuffered IO on the same underlying file descriptor, I've never read anything that suggests this is forbidden. But intuitively it seems that using buffered IO and then moving the file's position by <code>seek</code>ing behind stdio's back is asking for trouble. Also, if you are on a 32-bit system, stdio probably does not support files bigger than 2GB (or perhaps 4). </p>\n\n<p>I just would never mix calls to the FILE and the fd. Hopefully someone else with deeper knowledge will shed some more light on this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:49:28.707", "Id": "43763", "Score": "0", "body": "Thank you very much for all the feedback! About the inconsistency using `FILE` and using `fd` is because I just changed `fseek` to `lseek64` as I couldn't use `fseek` on files bigger than 2^31. To be honest I have never encountered `fd` before. I currently use `fopen` in another function that then passes the `FILE` to this function. What do suggest I use instead? `open` in fcntl.h?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T00:20:04.917", "Id": "43771", "Score": "1", "body": "I added a note on FILEs and fds" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:31:08.050", "Id": "43791", "Score": "0", "body": "Perfect explanation, now it makes sense. Thanks again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T17:48:15.433", "Id": "28041", "ParentId": "28039", "Score": "2" } } ]
{ "AcceptedAnswerId": "28041", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T15:47:27.753", "Id": "28039", "Score": "2", "Tags": [ "c", "linux" ], "Title": "Functionality to read large files (> 3 GB) in chunks" }
28039
<p>I've decided to learn Haskell by following the current Coursera algorithms course using Haskell to implement the algorithms discussed.</p> <p>First up is merge sort, which I've implemented as shown here. I'm brand new to Haskell so looking for any suggestions for improvements to the code - it seems quite verbose - and pointers on anything I may be doing wrong or in a weird way because I don't know what I'm doing.</p> <pre><code>module Main where import System.Environment main :: IO () main = do args &lt;- getArgs mapM_ putStrLn $ sort args sort :: (Ord a) =&gt; [a] -&gt; [a] sort xs = reduce True $ map (arr) xs arr :: a -&gt; [a] arr x = [x] reduce :: (Ord a) =&gt; Bool -&gt; [[a]] -&gt; [a] reduce _ [] = [] reduce forwards (x:[]) = if forwards then x else reverse x reduce forwards xs = reduce (not forwards) (combine forwards [] xs) combine :: (Ord a) =&gt; Bool -&gt; [[a]] -&gt; [[a]] -&gt; [[a]] combine forwards acc [] = acc combine forwards acc (x:[]) = (reverse x):acc combine forwards acc (x:y:zs) = let merged = merge forwards x y acc' = merged:acc in combine forwards acc' zs merge :: (Ord a) =&gt; Bool -&gt; [a] -&gt; [a] -&gt; [a] merge forwards xs ys = mergeIter forwards [] xs ys mergeIter :: (Ord a) =&gt; Bool -&gt; [a] -&gt; [a] -&gt; [a] -&gt; [a] mergeIter _ acc [] [] = acc mergeIter forwards acc (x:xs) [] = mergeIter forwards (x:acc) xs [] mergeIter forwards acc [] (y:ys) = mergeIter forwards (y:acc) [] ys mergeIter forwards acc (x:xs) (y:ys) | x &lt;= y &amp;&amp; forwards = mergeIter forwards (x:acc) xs (y:ys) | x &gt; y &amp;&amp; not forwards = mergeIter forwards (x:acc) xs (y:ys) | otherwise = mergeIter forwards (y:acc) (x:xs) ys </code></pre> <p>One specific question I have is around recursive function with accumulator arguments - you'll see in the listing that I've had to create a <code>mergeIter</code> function just to allow a default for the initial argument for the accumulator. </p> <p>As far as I can see Haskell doesn't support default values for arguments - should I be doing something else instead? A fold maybe?</p>
[]
[ { "body": "<p>OK, so let's see. <code>arr x = [x]</code> is usually called <code>wrap</code>, or just the operator section <code>(:[])</code> is used. But <code>map</code> can also be written with list comprehension, giving us</p>\n\n<pre><code>sort :: (Ord a) =&gt; [a] -&gt; [a]\nsort xs = reduce True [[x] | x &lt;- xs]\n</code></pre>\n\n<p>I find it much more visually apparent that way. We usually use short variable names in Haskell, with the same goal. When I see a variable <code>fw</code> and then <code>not fw</code> I get it that it is a toggle, a flag of some sorts, I don't need to see the long name like <code>forwardorbackwardsflag</code> explaining it to me in words while at the same time obscuring this visually. So we get</p>\n\n<pre><code> where\n reduce _ [] = []\n reduce fw [xs] = if fw then xs else reverse xs\n reduce fw s = reduce (not fw) (combine fw [] s)\n</code></pre>\n\n<p>we make it an internal function to <code>sort</code>, because this is what it is. It has no otherwise uses on its own. It's too tailored for the specific use here. -- <code>(x:[])</code> is written also <code>[x]</code>, which is a lot simpler. -- We don't have to annotate types of everything. Here <code>reduce</code> is defined right under its use site, so we see that the initial value of <code>fw</code> is <code>True</code>. For me, it is self-documenting enough, but YMMV. Next, <code>combine</code>. There's no need to name all those interim entities. The name of the function itself isn't right, it's too generic. What it does, specifically, is process the elements of its input list <em>in pairs</em>:</p>\n\n<pre><code> rpairs fw acc [] = acc\n rpairs fw acc [x] = reverse x : acc\n rpairs fw acc (x:y:zs) = rpairs fw (merge fw x y : acc) zs\n</code></pre>\n\n<p>It also builds its result in reversed order. We can make it an internal function to <code>reduce</code>, so that <em>its</em> argument <code>fw</code> could be referred to in <code>rpairs</code> body. At the same time there is no need in the separate accumulator really, we can just build the result naturally, in lazy fashion:</p>\n\n<pre><code> where\n reduce _ [] = []\n reduce fw [xs] = if fw then xs else reverse xs\n reduce fw s = reduce (not fw) (reverse $ pairs s)\n where\n pairs [] = []\n pairs [x] = [reverse x]\n pairs (x:y:zs) = merge fw x y : pairs zs\n</code></pre>\n\n<p>For <code>merge</code> to be able to refer to <code>fw</code> it too should be put here as an internal function to <code>reduce</code>. It is usual to split such functions into two like you did, the interface function (\"the <em>wrapper</em>\") and the internal <em>\"worker\"</em> function, except that normally the worker is made internal to the wrapper. But here the wrapper itself is too specialized, it reverses its result so is unlikely to be useable in general, so no need for the split. Thus we arrive at:</p>\n\n<pre><code>sort :: (Ord a) =&gt; [a] -&gt; [a]\nsort xs = reduce True [[x] | x &lt;- xs]\n where\n reduce _ [] = []\n reduce fw [xs] = if fw then xs else reverse xs\n reduce fw s = reduce (not fw) . reverse . pairs $ s\n where\n pairs (x:y:t) = rmerge [] x y : pairs t\n pairs [x] = [reverse x]\n pairs [] = []\n\n rmerge acc [] [] = acc\n rmerge acc xs [] = reverse xs ++ acc\n rmerge acc [] ys = reverse ys ++ acc\n rmerge acc (x:xs) (y:ys)\n | fw &amp;&amp; x &lt;= y || not fw &amp;&amp; x &gt; y\n = rmerge (x:acc) xs (y:ys)\n | otherwise = rmerge (y:acc) (x:xs) ys\n</code></pre>\n\n<p>There's no shame in calling <code>rmerge</code> with the initial value as we do here, it's just an internal function here, called from another internal function.</p>\n\n<hr>\n\n<p>But actually the reversals that <code>rmerge</code> performs are unnecessary, because of Haskell's lazy evaluation. <code>merge</code> now becomes a general function, usable in general. <code>pairs</code> too. <code>reduce</code> performs the same processing step on its input iteratively until a condition is met - there's a higher order function <code>until</code> that already captures this pattern. This leads to some more simplification of the code:</p>\n\n<pre><code>sort :: (Ord a) =&gt; [a] -&gt; [a]\nsort [] = []\nsort xs = head $ until (null . tail) (pairwise merge) [[x] | x &lt;- xs]\n -- (reverse . pairwise merge) \npairwise f (x:y:t) = f x y : pairwise f t\npairwise _ t = t\n\nmerge xs [] = xs\nmerge [] ys = ys\nmerge (x:xs) (y:ys)\n | x &lt;= y = x : merge xs (y:ys)\n | otherwise = y : merge (x:xs) ys\n</code></pre>\n\n<p>I think we would need to toggle between <code>&lt;=</code> and <code>&lt;</code> in <code>merge</code> to ensure the sort's stability, if we were to proceed by <code>(reverse . pairwise merge)</code> steps. But, perhaps we can just throw that <code>reverse</code> away.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T23:18:57.793", "Id": "44063", "Score": "0", "body": "Heh, looks a lot nicer & shorter... but I don't really understand it. Could you maybe go into how you got from what I'd written to what you've ended up with and why you made the changes you made? I really don't know any Haskell so you might need to explain it in quite basic terms :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T00:03:28.277", "Id": "44064", "Score": "0", "body": "I was hoping you'd ask something specific. Start by comparing my 1st code and yours. Convince yourself it does the same thing. If you have questions, ask. :) btw `a . b . c $ x == (a . b . c) x == a $ b $ c $ x = a (b (c x))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T06:41:47.990", "Id": "44085", "Score": "0", "body": "@Russell I've added some derivation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:26:16.047", "Id": "44091", "Score": "0", "body": "Phew! That's exactly what I needed, thanks. There was just so much going on I didn't know what to ask. Genuinely amazed by Haskell - it's like learning to program all over again, which is exciting :-)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:30:12.127", "Id": "44093", "Score": "0", "body": "Also your version trashes mine in terms of speed - over a randomly chosen 10m numeric strings, mine comes in at 2m23.322s and yours at 1m45.831s. Amazing.\n\nThere is one thing I really don't understand though... Presumably your speed increase is down to not needing the `reverse`s, because you've constructed your recursive calls like this: `f x y : pairwise f t` and `x : merge xs (y:ys)` (which also looks a lot nicer, too) - but doesn't this mean the calls are not tail-recursive? Why don't you get a stack overflow on large input? Is there some magic I don't know about? Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:37:00.297", "Id": "44094", "Score": "1", "body": "you're welcome. :) yes, it isn't tail recursion, because of the laziness. In Haskell it's known as \"guarded recursion\", at times as corecursion. I think it is very close to the [tail recursion modulo cons](https://en.wikipedia.org/wiki/Tail_call#Tail_recursion_modulo_cons). cf. http://stackoverflow.com/questions/12057658/lazy-evaluation-and-time-complexity/12057921#12057921 :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:43:00.510", "Id": "44095", "Score": "0", "body": "@Russell As for speed, I'm sure more advanced Haskell using arrays, vectors and such can be faster. But with lists this style usually gives you the best performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:55:05.253", "Id": "44096", "Score": "0", "body": "@Russell another consideration is \"space leaks\" - memory retention. If you name something it will want to stay in memory; if you use an expression inline, and there are no back-pointers into it holding on to the long ago seen parts of it, then chances are it will get GC'ed on the fly. For this to happen, you should compile, with -O2 switch, and test the compiled executable at your terminal prompt standalone (*not* loading compiled file into GHCi, which can leak memory still). Space leaks lead to slowdowns obviously. Run your file as \">name +RTS -s\" to see run-time stats on finish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T11:14:57.677", "Id": "44097", "Score": "0", "body": "!!!! \"tail recursion modulo cons.\" - now that is very, very cool! Obliterates at a stroke one of the things that makes writing a lot of tail-recursive functions ugly!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T13:01:15.340", "Id": "44099", "Score": "0", "body": "@Russell be sure your language supports it; or implement it on your own (example [here](http://stackoverflow.com/a/13256555/849891)). :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T13:07:17.277", "Id": "44100", "Score": "0", "body": "Ah, if only Ruby supported tail recursion at all - I'd definitely implement that! I might have a try to see if it's possible to do with `reduce`/`inject`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T13:18:28.197", "Id": "44101", "Score": "0", "body": "If you happen to be feeling generous... I've just posted a Haskell question on Stackoverflow I get the feeling you'd have no problem answering :-) http://stackoverflow.com/questions/17512494/recursive-state-monad-for-accumulating-a-value-while-building-a-list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T16:08:18.203", "Id": "44119", "Score": "0", "body": "btw the standard terminology is \"Haskell's guarded recursion\". TRMC analogy is something that *I* have been \"pushing\" but so far none of the bigwigs got on board with that. TRMC is an optimization for strict languages after all. :) For Haskell it is usually called \"guarded recursion\". Being a big fan of Prolog, I'm a little invested with the TRMC angle. :) -- BTW I once [asked a similar question](http://stackoverflow.com/q/9149183/849891). It relates to [this piece of code](http://rosettacode.org/wiki/Hamming_numbers#Direct_calculation_through_triples_enumeration)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T09:10:04.217", "Id": "44745", "Score": "0", "body": "update: the proper term is \"guarded corecursion\" (as contrasted with \"structural recursion\"). See the answer by pigworker http://stackoverflow.com/a/3983390/849891. :)" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T19:55:12.250", "Id": "28206", "ParentId": "28045", "Score": "3" } }, { "body": "<p>The code looks way to complicated to me, in fact this isn't even the kind of merge sort I'm used to, which is \"split the list in two parts, sort the parts, merge them back to one list\". Here is a short implementation:</p>\n\n<pre><code>sort xs@(_:_:_) = merge $ map sort $ split xs \nsort xs = xs\n\nsplit = foldr (\\x [l,r]-&gt; [x:r,l]) [[],[]]\n\nmerge [x:xs,y:ys]\n | x &lt; y = x : merge [xs, y:ys]\n | otherwise = y : merge [x:xs, ys]\nmerge xss = concat xss \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T05:27:09.097", "Id": "44210", "Score": "0", "body": "It was a similar, but much more complicated version of this I did first, but as I was using a linked list I decided that finding the halfway point of the list and splitting it for every recursive call was too inefficient. That's why I decided to try working from the bottom up instead. This is really nice and concise though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-13T10:57:58.010", "Id": "44646", "Score": "1", "body": "[1..16] --> [1,3..16] # [2,4..16] --> ([1,5..15]#[3,7..15]) # ([2,6..16]#[4,8..16]) --> ( ([1,9]#[5,13]) # ([3,11]#[7,15]) ) # ( ([2,10]#[6,14]) # ([4,12]#[8,16]) ) ==> access patterns are all over the place, so it seems that this top-down variant will need more space to operate (and so will probably be slower too) than the bottom-up method where the initial access to the input list is one sequential pass. With `split (x:xs) = g (x:) xs xs where g f xs [] = (f [], xs); g f (x:xs) (_:_:ys) = g (f.(x:)) xs ys` top-down is sequential access, but it does repeated traversals of the halves." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T21:33:34.513", "Id": "28263", "ParentId": "28045", "Score": "1" } } ]
{ "AcceptedAnswerId": "28206", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T19:01:15.503", "Id": "28045", "Score": "6", "Tags": [ "haskell", "recursion", "mergesort" ], "Title": "Merge Sort: exercise" }
28045
<p>I am trying to implement in C/C++ a 'classical' Divide and Conquer algorithm which solves the following problem "Given an array of n-1 numbers (int) from 0 to n, find the missing number".</p> <p>I am using the typical algorithm: start from MSB (1) find out how many bits of 1, 0 I should have (MSB bits) (2) find out how many bits of 1, 0 I actually have (MSB bits)</p> <p>split the array into 2 subarrays: one with MSBs of 0, the other with MSBs of 1. By using (1) and (2) I figure out in which subarray my number should be and I recursively call the function for the next bit (MSB-1), until my subarray contains only 1 element.</p> <p>I've written the code, and it works, but I have the feeling that it isn't really that aesthetic (the function has a lot of parameters), because I had some difficulties.</p> <p>Let's say that we have v = {0,1,2,3,5,6,7}. exp1 = 4 (expected number of "1" MSB bits). I know how to calculate exp1, because I know that one number is missing from 0 to 7. act1 = 3 (actual ...) So, we will have something like this: 0 1 2 3 | 5 6 7. Because act1 &lt; exp1, we recursively call the function for the 5 6 7 part and for MSB-1.</p> <p>exp1 = ? I will be unable to calculate this, because I will have no information upon the missing number. That is why I use the <strong>flagR</strong> and <strong>flagL</strong> flags. So that I know which part of the array I recursively called in order to compute exp1. But I really don't like the fact that I have been forced to use this 'trick'.</p> <p>I have noticed myself that I should've forced an order in the partitioning process: the numbers that have 0 as MSB (current MSB) should be in the first part, the others in the second. I will rewrite the code.</p> <p>The main() function isn't really that important for now, it serves for testing, currently.</p> <p>Here is my spaghetti code:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cmath&gt; // get bit #j from int i unsigned int get_bit(int i, int j) { return i &amp; (1&lt;&lt;j); } int find(int v[], int left, int right, int max_bit, int flagL, int flagR) { if (left == right) if (flagR != 0) return v[left] + 1; if (flagL != 0) return v[left] - 1; else { int exp0 = 0; // expected bits of 0 int act0 = 0; // actual bits of 0 int act1 = 0; // actual bits of 1 int exp1 = 0; // expected bits of 1 for (int i=left+flagL;i&lt;=right+flagR;i++) if (get_bit(i,max_bit) == 0) exp0++; else exp1++; for (int i=left;i&lt;=right;i++) if (get_bit(v[i],max_bit) == 0) act0++; else act1++; // val_cur is the max_bit of the pivot (v[right]) unsigned int val_cur = get_bit(v[right],max_bit); int i = 0; int k = 0; int man = 0; // divides the array into 2 subarrays // one subarray contains elements with max_bit = 0 // the other contains elements with max_bit = 1 for (k=1;k&lt;right;k++) { if (get_bit(v[k],max_bit) == val_cur) { i++; man = v[i]; v[i] = v[k]; v[k] = man; } } i++; man = v[i]; v[i] = v[k]; v[k] = man; // i is the "border" between the subarrays // recursively call the function for the next bit (max_bit-1) // and with the correct partition if (get_bit(v[i],max_bit) == 1) if (act1 &lt; exp1) return find(v,left,i,max_bit-1,0,1); else return find(v,i+1,right,max_bit-1,-1,0); else if (act0 &lt; exp0) return find(v,left,i,max_bit-1,0,1); else return find(v,i+1,right,max_bit-1,-1,0); } } int main() { int n = 7; int v[] = {7,0,4,1,3,6,2}; // find the maximum number of bits int bits = 0; bits = floor(log(n*1.0)/log(2*1.0)); // call the function printf("%d",find(v,0,6,bits,0,1)); return 0; } </code></pre>
[]
[ { "body": "<p>I don't follow the definition:</p>\n\n<pre><code>\"Given an array of n-1 numbers (int) from 0 to n, find the missing number\".\n</code></pre>\n\n<p>So if n == 7, as in your example code, there should be 6 numbers (n-1) in the\narray. There are 8 numbers in the the range \"0 to n\" (0,1,2,3,4,5,6,7).\nPerhaps the problem definition meant \"0 to n-1\" or \"0 up to n, not including\nn\".</p>\n\n<p>Your example code has seven numbers and n == 7:</p>\n\n<pre><code>int n = 7;\nint v[] = {7,0,4,1,3,6,2};\n</code></pre>\n\n<p>I would expect n to be 8 for an array of 7 numbers where one of the 8 is\nmissing.</p>\n\n<p>Anyway, your example works, printing '5', but if you replace, say the 2 with a 5\nit now prints '3'. Unless I messed up!</p>\n\n<p><hr>\nOn the code, <strong>C ignores white space</strong> (unlike say Python). Look at the\nif-else chain at the beginning of <code>find</code>:</p>\n\n<pre><code>if (left == right) \n if (flagR != 0)\n return v[left] + 1;\n if (flagL != 0)\n return v[left] - 1;\nelse\n{\n int exp0 = 0; // expected bits of 0\n</code></pre>\n\n<p>According to the indentation of statements, you intended the <code>if (flagR != 0)</code>\nand <code>if (flagL != 0)</code> to be dependent upon <code>left == right</code>, as in:</p>\n\n<pre><code>if (left == right) {\n if (flagR != 0) {\n return v[left] + 1;\n }\n if (flagL != 0) {\n return v[left] - 1;\n }\n}\nelse {\n int exp0 = 0; // expected bits of 0\n</code></pre>\n\n<p>But what the compiler will see is</p>\n\n<pre><code>if (left == right) {\n if (flagR != 0) {\n return v[left] + 1;\n }\n}\nif (flagL != 0) {\n return v[left] - 1;\n}\nelse {\n int exp0 = 0; // expected bits of 0\n</code></pre>\n\n<p>If you get the editor to re-indent the code for you (or use UNIX <code>indent</code>\ncommand), you will see that your indenting is wrong. The lesson is always to\nuse braces to say explicitly what you mean.</p>\n\n<p>The same goes for your other expressions:</p>\n\n<pre><code>for (int i=left+flagL;i&lt;=right+flagR;i++)\n if (get_bit(i,max_bit) == 0)\n exp0++;\n else\n exp1++;\n</code></pre>\n\n<p>should be more like this:</p>\n\n<pre><code>for (int i = left + flagL; i &lt;= right + flagR; i++) {\n if (get_bit(i, max_bit) == 0) {\n exp0++;\n } else {\n exp1++;\n }\n}\n</code></pre>\n\n<p>In this case, there is no misunderstanding by the compiler but you should add the braces nevertheless - consider what happens if you don't add explicit braces with:</p>\n\n<pre><code>for (int i=left+flagL;i&lt;=right+flagR;i++)\n if (get_bit(i,max_bit) == 0)\n exp0++;\n else\n exp1++;\n something_else();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:31:22.537", "Id": "43840", "Score": "0", "body": "Thanks for the review!\nAt the \n `if (left == right)`\n\n an\n `else\n if (flagL != 0)\n return v[left] - 1;`\n\nshould do the trick without braces. (But I've forgotten the else)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:48:49.533", "Id": "43844", "Score": "0", "body": "Just use braces. You wont find many reviews here of C code where reviewers don't point out missing braces. You might think they are not necessary or ugly, but standard best practice says you are wrong :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T13:28:05.363", "Id": "28076", "ParentId": "28053", "Score": "3" } } ]
{ "AcceptedAnswerId": "28076", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T20:52:14.743", "Id": "28053", "Score": "1", "Tags": [ "c++", "c", "algorithm", "array", "bitwise" ], "Title": "Missing element from array (D&C) - code design/aesthetic improvement" }
28053
<p>How should I approach refactoring this code?</p> <pre><code>def separate_comma(number) a = number.to_s.split('') b = a.size/3.0 if a.size &lt; 4 p number.to_s elsif a.size%3 == 0 n = -4 (b.to_i-1).times do |i| a.insert(n, ',') n -= 4 end p a.join("") else n = -4 b.to_i.times do |i| a.insert(n, ',') n -= 4 end p a.join("") end end separate_comma(97425) # =&gt; "97,425" separate_comma(89552600) # =&gt; "895,926,600" separate_comma(0) # =&gt; "0" separate_comma(100) # =&gt; "100" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:08:35.663", "Id": "43871", "Score": "2", "body": "Just a hint: Remember [i18n](http://en.wikipedia.org/wiki/Internationalization_and_localization). Among other things the symbol for grouping digits isn't always a comma, so avoid hard-coding it." } ]
[ { "body": "<p>This does the same thing more succinctly</p>\n\n<pre><code>number.to_s.reverse.gsub(/(\\d{3})(?=\\d)/, '\\\\1,').reverse\n</code></pre>\n\n<p>source: <a href=\"https://stackoverflow.com/a/11466770/1429887\">https://stackoverflow.com/a/11466770/1429887</a></p>\n\n<p>It converts the number to a string, reverses it, places a comma every three digits (if it is followed by a digit), then reverses it back to its original order.</p>\n\n<p>You might want to make it a function such as</p>\n\n<pre><code>def format_number(number)\n number.to_s.reverse.gsub(/(\\d{3})(?=\\d)/, '\\\\1,').reverse\nend\n</code></pre>\n\n<p>so that you can call the process multiple times</p>\n\n<p>However, this method does not work with numbers that contain 3+ decimals. To solve that:</p>\n\n<pre><code>def format_number(number)\n number = number.to_s.split('.')\n number[0].reverse!.gsub!(/(\\d{3})(?=\\d)/, '\\\\1,').reverse!\n number.join('.')\nend\n</code></pre>\n\n<p>This method splits the integer into the whole number part and the decimal part. It then adds the comma to the whole number and then tacks on the second decimal part. </p>\n\n<p>[edit]: the second line of that function should have been number[0] to get the first element (the whole number one). Sorry if you viewed it before I realized my mistake.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T04:56:20.633", "Id": "28066", "ParentId": "28054", "Score": "7" } }, { "body": "<p>I am not sure how hard may be for a newbie to take on <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">functional programming</a>, but if you are interested in new ways of programming, check it out. A more specific article on Ruby: <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow noreferrer\">FP with Ruby</a>. If you think in terms of expressions (what things are) instead of statements (update, insert, delete, ...), code is more declarative (and usually shorter). I'll use no regexps to show an alternative approach to the existing answer:</p>\n<pre><code>def separate_comma(number)\n reverse_digits = number.to_s.chars.reverse\n reverse_digits.each_slice(3).map(&amp;:join).join(&quot;,&quot;).reverse\nend\n</code></pre>\n<p>If you want to support decimals:</p>\n<pre><code>def separate_comma(number)\n whole, decimal = number.to_s.split(&quot;.&quot;)\n whole_with_commas = whole.chars.to_a.reverse.each_slice(3).map(&amp;:join).join(&quot;,&quot;).reverse\n [whole_with_commas, decimal].compact.join(&quot;.&quot;)\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-18T02:39:56.813", "Id": "493452", "Score": "1", "body": "[String::chars](https://ruby-doc.org/core-2.6/String.html#method-i-chars) returns an Array so you don't need the `to_a` following `chars`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-07-03T20:44:05.377", "Id": "28100", "ParentId": "28054", "Score": "13" } }, { "body": "<p>If you're using Ruby on Rails, there is a number helper for doing just that. </p>\n\n<pre><code>number_with_delimiter(12345,delimiter: \",\") # =&gt; 12,345\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-14T00:22:12.357", "Id": "392701", "Score": "6", "body": "That function is [part of `ActionView`](https://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_delimiter). The question does not mention that Ruby on Rails is being used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-14T21:31:11.393", "Id": "392862", "Score": "0", "body": "Good point.. that was an assumption." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-13T20:10:13.497", "Id": "203699", "ParentId": "28054", "Score": "2" } } ]
{ "AcceptedAnswerId": "28100", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T21:28:42.920", "Id": "28054", "Score": "8", "Tags": [ "beginner", "ruby", "formatting", "integer" ], "Title": "Separate numbers with commas" }
28054
<p>I'm new to PHP programming. I would love some feedback on this simple code I wrote which queries a database based on some arguments supplied by a user and returns an HTML table displaying the data. </p> <p>The table in my db has three columns: <code>Manufacturer</code>, <code>Model</code>, <code>ForSale</code>.</p> <p>The user picks from three drop down menus on the web page and this php script is called with the data.</p> <pre><code>&lt;?php $db = new SQLite3("db/mantisui.db"); $manufacturer= $_GET['mfr']; $model = $_GET['mod']; $forsale = $_GET['forSale']; // create the query $q = "SELECT * FROM vehicles"; $addwhere = true; // if all mfrs chosen, skip WHERE clause $pos = strpos($manufacturer, 'All'); if ($pos === false) { $q .= " WHERE Manufacturer='$manufacturer'"; $addwhere = false; } // if any models chosen, skip WHERE clause $pos = strpos($model, 'Any'); if ($pos === false) { if ($addwhere == false) { $q .= " AND"; } else { $q .= " WHERE"; $addwhere = false; } $q .= " Model='$model'"; } // if any for sale status chosen, skip WHERE clause $pos = strpos($forsale, 'Any'); if ($pos === false) { if ($addwhere == false) { $q .= " AND"; } else { $q .= " WHERE"; $addwhere = false; } $q .= " ForSale='$forsale'"; } $response = $db-&gt;query($q); // generate the output table $output = "&lt;table id='screens' class='table tablesorter table-condensed table-striped table-hover table-bordered'&gt;"; $output .= "&lt;thead&gt;&lt;tr&gt;&lt;th&gt;MANUFACTURER&lt;/th&gt;&lt;th&gt;MODEL&lt;/th&gt;&lt;th&gt;FOR SALE&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;"; while ($res = $response-&gt;fetchArray()) { $id = $res['Id']; $txtMfr= $res['Manufacturer']; $txtModel= $res['Model']; $txtForSale = $res['ForSale']; $output .= "&lt;tr class='vehiclerow'&gt;&lt;td style='display:none' class='id_row'&gt;$id&lt;/td&gt;&lt;td&gt;$txtMfr&lt;/td&gt;&lt;td&gt;$txtModel&lt;/td&gt;&lt;td&gt;$txtForSale&lt;/td&gt;&lt;td class='status_cell'&gt;$status&lt;/td&gt;&lt;/tr&gt;"; } $output .= "&lt;/table&gt;"; echo $output; $db-&gt;close(); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T00:50:11.210", "Id": "43773", "Score": "1", "body": "See: http://xkcd.com/327/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:18:57.820", "Id": "43806", "Score": "0", "body": "Ha! I'll try and remember that :)" } ]
[ { "body": "<p>Generally, it is a good idea to separate your view logic from your business logic, e.g your data access.</p>\n\n<p>The code you've presented is procedural, and whilst there's nothing wrong with that at this stage, it could become unsustainable in terms of future maintainability.</p>\n\n<p>One thing that I am conscious about, is that you are directly plugging variables into your SQL query that you are constructing: there is a risk of SQL injection. I would suggest that you wrap your variables with <code>sqlite_escape_string</code> before placing them into your query. I note that you might want to look into PDO for database portability and a 'better' layer between your application and the database.</p>\n\n<p>You seem to be be using <code>strpost</code> to ascertain whether a manufacturer was 'All'. I would suggest doing the following:</p>\n\n<pre><code>$whereSubClause = array();\n\n/* Firstly identify if we have 'All' as the manufacture - \n * if we do, we don't need to add constraints to the query.\n */\nif ( 'All' != $manufacturer ){\n\n $mfg = sqlite_escape_string($manufacturer);\n $whereSubclause[] = \"`Manufacturer` = {$mfg}\";\n\n}\n\nif ( 'Any' != $model ){\n\n $model = sqlite_escape_string($model);\n $whereSubclause[] = \"`Model` = {$model}\";\n\n}\n\nif ( 'Any' != $forsale ){\n\n $forSale = sqlite_escape_string($forsale);\n $whereSubclause[] = \"`ForSale` = {$forSale}\";\n\n}\n\n// We can now safely construct the SQL -- \n// I haven't provided the method for this, but you'd end up with:\n\n$query = \"SELECT * FROM `vehicles` WHERE (`Manufacturer` = 'AMG') AND (`Manufacturer` = 'AMG') AND (`ForSale` = '1')\"\n</code></pre>\n\n<p>I would then personally output the data into an array, which can then be passed to a view. Using a <code>foreach</code> loop, I would construct the rows in the table. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T23:49:22.267", "Id": "43768", "Score": "0", "body": "Very helpful! Lots of good basic PHP fundamentals. I just learned some about templating which I'm assuming is considered one approach to MVC. Are there other approaches that are good for separating data and presentation logic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:47:19.010", "Id": "43825", "Score": "0", "body": "MVC is basically a pattern or architecture; pretty much all architectures support the separation of concerns. There's MVP MVVM and PAC." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T18:27:03.747", "Id": "43834", "Score": "0", "body": "Makes sense. Thanks again! I'll upvote your answer as soon as I have enough rep points to do so!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:52:45.500", "Id": "28061", "ParentId": "28055", "Score": "3" } }, { "body": "<p>With regard to the PHP injection issue, I actually think parameterisation of the inputs is a better method.</p>\n\n<p>Something like the example below (sorry it is not structured like your specific case):</p>\n\n<pre><code>$sql = \"SELECT articleId, title, html, tldr, createdDate, lastUpdate FROM Articles WHERE articlePK=? and status='published'\";\n$stmt = $con-&gt;prepare($sql);\n$stmt-&gt;bind_param(\"i\",$articlePK);\n$stmt-&gt;execute();\n$stmt-&gt;bind_result($articleId, $title, $html, $tldr, $date, $lastUpdate);\n$stmt-&gt;fetch(); //only ever return one row \n$stmt-&gt;close();\n</code></pre>\n\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T16:41:06.833", "Id": "28137", "ParentId": "28055", "Score": "3" } } ]
{ "AcceptedAnswerId": "28061", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T21:28:47.083", "Id": "28055", "Score": "3", "Tags": [ "php", "ajax", "database", "sqlite" ], "Title": "Querying a database with PHP" }
28055
<p>I am reading "<a href="http://rads.stackoverflow.com/amzn/click/1847194141" rel="nofollow">Object-Oriented JavaScript</a>" by Stoyan Stefanov to learn JavaScript and in the end of the chapter named "Objects", there's an exercise that asks you to implement your own <code>String</code> object. I have implemented some methods of <code>String</code> (not all), I'd be happy if you could check and let me know how it could be done better:</p> <pre><code>function MyString(primitive) { this.length = 0; var i = 0; // Here length is calculated and the indexer is set. for (var c in primitive) { this[i++] = primitive[c]; this.length++; } this.toString = function() { return primitive; }; this.valueOf = this.toString; this.substring = function(start, end) { var result = ''; // Edge cases for the parameters. if ((typeof end !== 'number' &amp;&amp; typeof parseInt(end) !== 'number') || end &gt; this.length) end = this.length; if (end &lt;= 0 || isNaN(end)) { end = start; start = 0; } for (var i = start; i &lt; end; i++) { result += this[i]; } return result; } this.charAt = function(i) { var x = parseInt(i); x = isNaN(x) ? 0 : x; return this.substring(x, x+1); }; return this; } var s = new MyString('hello'); console.log(s.length); console.log(s[0]); console.log(s.toString()); console.log(s.valueOf()); console.log(s.charAt(1)); console.log(s.charAt('2')); console.log(s.charAt('e')); console.log(s.substring(1, 3)); </code></pre> <p>Any and all suggestions are welcome. I'm completely new to JavaScript and would love to hear my mistakes.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:03:46.513", "Id": "43757", "Score": "0", "body": "You'll want to use prototypes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:08:05.390", "Id": "43758", "Score": "0", "body": "The length property should be read-only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:10:29.950", "Id": "43759", "Score": "0", "body": "I know it should be read-only but I have no idea at the moment how to make it so. And the prototypes chapter is the next one (I'm reading it now). Could you add an answer with your suggested improvements?" } ]
[ { "body": "<p>Some information up front: </p>\n\n<ol>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow\"><code>Object.defineProperty</code></a> is an Ecmascript 5 feature, and is not available in older browsers (IE &lt; 9). </p></li>\n<li><p>There is likely a cleaner way of doing all of this.</p></li>\n</ol>\n\n<p>This is a basic skeleton: </p>\n\n<pre><code>function MyString(primitive) {\n var length = 0, a; // private internal variable to track length, and our iterator\n\n // the loop below basically ensures that this string object is immutable. \n for(a in primitive){\n (function(char){\n Object.defineProperty(this, length++, {\n get:function(){return char;}\n });\n }).call(this,primitive[a]);\n }\n\n // we can \"get\" the length, but we can't \"set\" it.\n Object.defineProperty(this, \"length\", {\n get:function(){return length;}\n });\n\n return this;\n}\n\n// defining methods on the prototype of an object allows us to share the same instance \n// of the method without recreating it for each instance of the object. \n// (reduced memory footprint)\nMyString.prototype.toString = function(){\n return [].join.call(this, ''); \n // since our object is \"array-like\", we can use array methods on it. \n}\n\nMyString.prototype.charAt = function(index){\n return this[index];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T13:22:26.047", "Id": "43893", "Score": "0", "body": "Note: Be aware of the problem when using `this[index]`, not supported in IE < 8, see [string.charAt\\(x\\) or string\\[x\\]?](http://stackoverflow.com/questions/5943726/string-charatx-or-stringx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-06T08:16:37.233", "Id": "137869", "Score": "0", "body": "@Xotic750 This is true but in this case it should work since he is not accessing the string but the MyString object which has an internal 0: 'a' etc representations" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:46:34.130", "Id": "28058", "ParentId": "28056", "Score": "2" } } ]
{ "AcceptedAnswerId": "28058", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T21:50:56.687", "Id": "28056", "Score": "1", "Tags": [ "javascript", "strings" ], "Title": "Implementation of String object as an exercise" }
28056
<p>I have written a unit / component in Delphi which helps make it easy to write JSON data. I know there are already existing ways to do this, but the ways I've used are too awkward. I have used an XML writer in Delphi before (not sure exactly what one) but I liked the way it worked, and re-created a JSON version. It's very lightweight, and I'd like to know if I'm missing anything important.</p> <p>PS - I know there is an unimplemented property <code>LineBreak</code> but that's to come later...</p> <pre><code>unit JsonBuilder; interface uses Windows, Classes; type TJsonBuilder = class(TComponent) private FLines: TStringList; FIndent: Integer; FLineBreak: Boolean; FHierarchy: Integer; FNeedComma: Boolean; function GetLines: TStrings; procedure SetIndent(const Value: Integer); procedure SetLineBreak(const Value: Boolean); procedure SetLines(const Value: TStrings); function GetAsJSON: String; procedure SetAsJSON(const Value: String); procedure WriteLine(const S: String); procedure WriteStartProperty(const Name: String); procedure UpdateStat(const H: Integer; const C: Boolean); function GetIndent: String; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure WriteStartDoc; procedure WriteEndDoc; procedure WriteStartObject; overload; procedure WriteStartObject(const Name: String); overload; procedure WriteEndObject; procedure WriteStartArray; overload; procedure WriteStartArray(const Name: String); overload; procedure WriteEndArray; procedure WriteString(const Name, Value: String); procedure WriteInteger(const Name: String; const Value: Integer); procedure WriteBoolean(const Name: String; const Value: Boolean); procedure WriteDouble(const Name: String; const Value: Double); procedure WriteCurrency(const Name: String; const Value: Currency); procedure WriteStream(const Name: String; AStream: TStream); procedure WriteBreak; property AsJSON: String read GetAsJSON write SetAsJSON; property Lines: TStrings read GetLines write SetLines; published property Indent: Integer read FIndent write SetIndent; property LineBreak: Boolean read FLineBreak write SetLineBreak; end; function JsonEncode(const S: String): String; function Base64Encode(AStream: TStream; const LineBreaks: Boolean = False): string; implementation uses StrUtils, SysUtils; const Base64Codes: array[0..63] of char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function Base64Encode(AStream: TStream; const LineBreaks: Boolean = False): string; const dSize=57*100;//must be multiple of 3 var d:array[0..dSize-1] of byte; i,l:integer; begin Result:=''; l:=dSize; while l=dSize do begin l:=AStream.Read(d[0],dSize); i:=0; while i&lt;l do begin if i+1=l then Result:=Result+ Base64Codes[ d[i ] shr 2]+ Base64Codes[((d[i ] and $3) shl 4)]+ '==' else if i+2=l then Result:=Result+ Base64Codes[ d[i ] shr 2]+ Base64Codes[((d[i ] and $3) shl 4) or (d[i+1] shr 4)]+ Base64Codes[((d[i+1] and $F) shl 2)]+ '=' else Result:=Result+ Base64Codes[ d[i ] shr 2]+ Base64Codes[((d[i ] and $3) shl 4) or (d[i+1] shr 4)]+ Base64Codes[((d[i+1] and $F) shl 2) or (d[i+2] shr 6)]+ Base64Codes[ d[i+2] and $3F]; inc(i,3); if LineBreaks then if ((i mod 57)=0) then Result:=Result+#13#10; end; end; end; function JsonEncode(const S: String): String; var X: Integer; C: Char; procedure Repl(const Val: String); begin Delete(Result, X, 1); Insert(Val, Result, X); end; begin Result:= StringReplace(S, '\', '\\', [rfReplaceAll]); Result:= StringReplace(Result, '"', '\"', [rfReplaceAll]); Result:= StringReplace(Result, '/', '\/', [rfReplaceAll]); for X := Length(Result) downto 1 do begin C:= Result[X]; if C = #10 then Repl('\'+#10); if C = #13 then Repl('\'+#13); end; end; { TJsonBuilder } constructor TJsonBuilder.Create(AOwner: TComponent); begin inherited; FLines:= TStringList.Create; FHierarchy:= 0; FIndent:= 4; FLineBreak:= True; FNeedComma:= False; end; destructor TJsonBuilder.Destroy; begin FLines.Free; inherited; end; procedure TJsonBuilder.Clear; begin FLines.Clear; end; procedure TJsonBuilder.SetIndent(const Value: Integer); begin FIndent := Value; if FIndent &lt; 0 then FIndent:= 0; end; procedure TJsonBuilder.SetLineBreak(const Value: Boolean); begin FLineBreak := Value; end; function TJsonBuilder.GetLines: TStrings; begin Result:= TStrings(FLines); end; procedure TJsonBuilder.SetLines(const Value: TStrings); begin FLines.Assign(Value); end; procedure TJsonBuilder.UpdateStat(const H: Integer; const C: Boolean); begin FHierarchy:= FHierarchy + H; FNeedComma:= C; end; function TJsonBuilder.GetIndent: String; var X: Integer; Y: Integer; begin Result:= ''; for X := 1 to FHierarchy do for Y := 1 to FIndent do Result:= Result + ' '; end; procedure TJsonBuilder.WriteLine(const S: String); var T: String; begin if FNeedComma then begin //Add comma to prior line T:= FLines[FLines.Count-1]; T:= T + ','; FLines[FLines.Count-1]:= T; end; FLines.Add(GetIndent+S); end; procedure TJsonBuilder.WriteStartDoc; begin WriteStartObject; end; procedure TJsonBuilder.WriteEndDoc; begin WriteEndObject; end; procedure TJsonBuilder.WriteStartObject; begin WriteLine('{'); UpdateStat(1, False); end; procedure TJsonBuilder.WriteStartObject(const Name: String); begin WriteStartProperty(Name); WriteStartObject; end; procedure TJsonBuilder.WriteEndObject; begin UpdateStat(-1, False); WriteLine('}'); UpdateStat(0, True); end; procedure TJsonBuilder.WriteStartArray; begin WriteLine('['); UpdateStat(1, False); end; procedure TJsonBuilder.WriteStartArray(const Name: String); begin WriteStartProperty(Name); WriteStartArray; end; procedure TJsonBuilder.WriteEndArray; begin UpdateStat(-1, False); WriteLine(']'); UpdateStat(0, True); end; procedure TJsonBuilder.WriteStartProperty(const Name: String); begin WriteLine('"'+Name+'" :'); UpdateStat(0, False); end; procedure TJsonBuilder.WriteInteger(const Name: String; const Value: Integer); begin WriteLine('"'+Name+'" : '+IntToStr(Value)); UpdateStat(0, True); end; procedure TJsonBuilder.WriteStream(const Name: String; AStream: TStream); var S: String; begin S:= Base64Encode(AStream); WriteLine('"'+Name+'" : "'+S+'"'); UpdateStat(0, True); end; procedure TJsonBuilder.WriteString(const Name, Value: String); begin WriteLine('"'+Name+'" : "'+JsonEncode(Value)+'"'); UpdateStat(0, True); end; procedure TJsonBuilder.WriteBoolean(const Name: String; const Value: Boolean); begin WriteLine('"'+Name+'" : '+IfThen(Value, 'true', 'false')); UpdateStat(0, True); end; procedure TJsonBuilder.WriteBreak; begin WriteLine(''); UpdateStat(0, False); end; procedure TJsonBuilder.WriteCurrency(const Name: String; const Value: Currency); begin WriteLine('"'+Name+'" : '+FormatFloat('0.#', Value)); UpdateStat(0, True); end; procedure TJsonBuilder.WriteDouble(const Name: String; const Value: Double); begin WriteLine('"'+Name+'" : '+FormatFloat('0.#', Value)); UpdateStat(0, True); end; function TJsonBuilder.GetAsJSON: String; begin Result:= FLines.Text; end; procedure TJsonBuilder.SetAsJSON(const Value: String); begin FLines.Text:= Value; end; end. </code></pre> <p>Implementation of this object is like so...</p> <pre><code>function GetSomething: String; var JB: TJsonBuilder; X: Integer; begin JB:= TJsonBuilder.Create(nil); try JB.WriteStartDoc; JB.WriteStartObject('some_object_name'); JB.WriteString('prop_name', 'Property Value'); JB.WriteInteger('another_prop', 123); JB.WriteStartArray('items'); for X := 1 to 5 do begin JB.WriteStartObject; JB.WriteString('some_item_name', 'Item '+IntToStr(X)); JB.WriteCurrency('item_price', 19.99 * X); JB.WriteEndObject; end; JB.WriteEndArray; JB.WriteEndObject; JB.WriteEndDoc; Result:= JB.AsJSON; finally JB.Free; end; end; </code></pre> <p>This outputs the following JSON text:</p> <pre><code>{ "some_object_name" : { "prop_name" : "Property Value", "another_prop" : 123, "items" : [ { "some_item_name" : "Item 1", "item_price" : 20 }, { "some_item_name" : "Item 2", "item_price" : 40 }, { "some_item_name" : "Item 3", "item_price" : 60 }, { "some_item_name" : "Item 4", "item_price" : 80 }, { "some_item_name" : "Item 5", "item_price" : 100 } ] } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T03:43:57.470", "Id": "43861", "Score": "0", "body": "This seems an awfully complex way to build JSON... Granted, i don't know Delphi, so this may just be how y'all like it. But to me, it looks almost more complicated than doing the JSON generation yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T04:00:56.033", "Id": "43862", "Score": "0", "body": "@cHao When it comes to small and simple JSON structures, it's simple to use raw string concatenation. But when it comes to larger complex JSON structures, raw concatenation becomes overwhelming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:27:22.610", "Id": "54299", "Score": "0", "body": "19.99 became 20" } ]
[ { "body": "<p>It is rather verbose and complicated and it doesn't seem to really allow per your conventions for valid structures like <code>[{\"name\":\"bob\"},{\"name\":\"ted\"}]</code> (although that may appear to me that way because I just skimmed through it), and property names do need to be proper JSON strings... but if it works for you, you'll hear no arguments from me!</p>\n\n<p>Actually I gave it more than just a skim.</p>\n\n<p>You're doing something weird with your control characters. You can't just put a slash in front of them to escape. The character represented by \"\\r\" -- I think in your code represented by #10, but I always forget which of <code>\\r</code> and <code>\\n</code> is char(10) and char(13) -- literally needs to have <code>\\r</code> in the JSON encoding, most certainly not {the actual contol character! That breaks strings!! </p>\n\n<p>(Please See the <a href=\"http://json.org\" rel=\"nofollow\">http://json.org</a> side panel).</p>\n\n<pre><code>char\nany-Unicode-character-\n except-\"-or-\\-or-\n control-character\n\\\"\n\\\\\n\\/\n\\b\n\\f\n\\n\n\\r\n\\t\n\\u four-hex-digits\n</code></pre>\n\n<p>To encode for JSON, you really don't have to do much, but what you do you ought to make the best effort to do correctly!!</p>\n\n<p>Over all, I find your code needlessly verbose to be used regularly. It might work fine for some code automatically generated, though, once you fix the string encoding and any other possible encoding issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T08:50:57.813", "Id": "28158", "ParentId": "28059", "Score": "1" } } ]
{ "AcceptedAnswerId": "28158", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:48:03.963", "Id": "28059", "Score": "1", "Tags": [ "json", "delphi" ], "Title": "Is this legitimate for building a JSON file?" }
28059
<p>I see many many programs that are written out of the <code>main</code> method. But most of my programs are written in <code>main()</code> and access some methods from other classes.</p> <p>Am I programming in the correct way?</p> <p>main.java:</p> <pre><code>import java.util.Scanner; import games.Spin; public class Mains { //Declaring Scanner object as console. static Scanner console = new Scanner(System.in); //Declaring Spin game object as spin static Spin spin = new Spin(); //Available games array static String[] content = {"spin", "tof"}; //Navigation options array static String[] navigateGame = {"start", "back"}; public static void main (String[] args) { // Setting the default number for inputNumber int inputNumber = 0; // Setting the defult value for inputString String inputString = ""; // The main game loop boolean game = true; // Spin game loop boolean spinGame = false; // Truth or false game loop boolean tofGame = false; System.out.print("Welcome! Please select a game: "); for (int i = 0; i &lt; content.length; i++) { System.out.print(content[i]); if (i &lt; content.length -1) { System.out.print(", "); } } //New line.. System.out.println(); //The main game loop while (game) { //This is the input we will enter to the console. inputString = console.nextLine(); //If we are not in any of the games.. if (!spinGame &amp;&amp; !tofGame) { //Looping through the array for (String s : content) { //If the entered input, contains any word that is in the array, enter switch statement, to find out which word was it. if (inputString.equalsIgnoreCase(s)) { //Entering switch statement to find out which of the values matched in the array. switch (inputString) { //Spin game match case "spin": //Start spin game spinGame = true; break; //Tof game match. case "tof": //Start tof game tofGame = true; break; } //Getting out of the for loop, so we won't get could not find game error after match found. break; } else { //No match found, throw error. System.out.println("Could not find game!"); //Break out of the loop. break; } } } /* * Spin Game Start */ //Setting up the text once user entered the game. if (spinGame) { System.out.println("Welcome to the spin game!"); System.out.println("Please enter 'start' to start and 'back' to go back."); } /* * Main Spin Game loop */ while (spinGame) { //This is the input we will pass the console. inputString = console.nextLine(); //Looping through the array for selected navigation option. for (String s : navigateGame) { //Checking if the entered value contains any word inside the navgiation options array. if (inputString.equalsIgnoreCase(s)) { //Entering the switch statement to find out what word. switch (inputString) { //Case start game //This will spin the wheel once, and tell results. case "start": //Printing the spinned value frm spinWheel(). System.out.println(spin.spinWheel()); //Setting the console to receive more inputs. inputString = console.nextLine(); break; //Case back //This will go back to the lobby. case "back": //Quit spinGame. spinGame = false; //Back to the top of the method. main(args); break; } } } } } } } </code></pre> <p>Spin.java:</p> <pre><code>package games; public class Spin { public String spinWheel() { return "It works!"; } } </code></pre> <p>I did not make the spin part because I really need to know if I am doing well. Because I see most of the people are doing things in the different way, I hate sticking with a one way while I think it's incorrect.</p> <p>Is there anything wrong with my way of coding and handling?</p>
[]
[ { "body": "<p>There are several things that you can improve in your code. Actually a good practice for your own benefit as a developer is <strong>plan before you do it</strong>. If you are planing to do a doghouse, you don't need a blueprint, but if you are building <strong>your house</strong> a blueprint looks good (<em>Code Complete 2 reference</em>).</p>\n\n<p>When you do everything in the same class or method you are killing lots of good options that Object Oriented Programming give you. \nFor example, if you need to extend your class, and just change a part of it, if everything is in the same method you will have to copy everything just to change maybe a line. More about overriding <a href=\"https://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why\">here</a>. You should aim to have <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">specialized function classes</a>.</p>\n\n<p>Also, you will improve readability and how clean is your code. It's not easy to figure out what your code is doing when you have a huge method. Method names should be really indicative of that the method will do or return. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:20:24.950", "Id": "43807", "Score": "0", "body": "+1 for the Code Complete 2 suggestion. I would also suggest reading Clean Code by Robert Martin." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T13:35:28.153", "Id": "28078", "ParentId": "28060", "Score": "3" } }, { "body": "<p>Having the entire program contained in one function is rather frowned upon by pretty much all camps. A function hundreds of lines long can be a real pain to fix, if ever you have to.</p>\n\n<p>Add to that, you're using 4 flags to keep track of what you're doing. And it's just going to keep growing, if you add more games. The bigger the function gets, the more moving parts there are...the more stuff shares a scope...the easier it is for something to get modified by accident, or collide namewise, or any number of other things, and the easier it is for functionality to blend together, whether in the code or in your mind. If you break up the code into short, discrete chunks with decently descriptive names, it reduces overall complexity as well as cognitive load.</p>\n\n<p>You'd do well to identify parts of the code that represent discrete operations, and split them off into their own functions. For example, in your <code>main</code> method, you have:</p>\n\n<ul>\n<li>Code to prompt for a game choice</li>\n<li>Code to ask the user what to do next in the current game</li>\n<li>Code to run the \"spin\" game</li>\n<li>Eventually, i presume, code to run the \"tof\" game</li>\n</ul>\n\n<p>These chunks, at the very least, could be split off -- particularly since you currently use flags to make the states mutually exclusive anyway. Those flags you're using would disappear; the program would begin tracking its state <em>implicitly</em>, by what function it's in.</p>\n\n<pre><code>public class Mains {\n static Scanner console = new Scanner(System.in);\n\n // Navigation options array\n // i'm guessing this will be shared between spin and tof\n static String[] navigateGame = {\"start\", \"back\"};\n\n public static void main (String[] args) {\n String[] content = { \"spin\", \"tof\" };\n while (true) {\n printGameMenu(content);\n String choice = getChoice(content);\n\n switch (choice) {\n case \"spin\":\n spinGame();\n break;\n /* once you implement the TOF game...\n case \"tof\":\n tofGame();\n break;\n */\n default:\n System.out.println(\"Could not find game!\");\n break;\n }\n }\n }\n\n public static void printGameMenu(String[] content) {\n System.out.print(\"Welcome! Please select a game: \");\n for (int i = 0; i &lt; content.length; i++) {\n System.out.print(content[i]);\n if (i &lt; content.length -1) {\n System.out.print(\", \");\n }\n }\n System.out.println();\n }\n\n\n public static String getChoice(String[] options)\n {\n do {\n String inputString = console.nextLine();\n\n for (String s : options) {\n if (inputString.equalsIgnoreCase(s)) {\n\n // BTW...rereading this Q&amp;A, i noticed something. In your code,\n // when you've found a match, you use `inputString` -- the string\n // entered by the user -- and you don't know whether it's\n // lowercase. This means even though you've found a match, it\n // might not match any of your `switch` cases.\n //\n // The string in your options array is more under your control.\n // You should probably either use that or stop trying to be\n // case-agnostic, since it probably isn't working anyway.\n\n return s;\n }\n }\n System.out.println(\"Invalid option. Please choose from the listed options.\");\n } while (true);\n }\n\n public static void spinGame()\n {\n Spin spin = new Spin();\n System.out.println(\"Welcome to the spin game!\");\n System.out.println(\"Please enter 'start' to start and 'back' to go back.\");\n\n while (true) {\n String inputString = getChoice(navigateGame);\n\n switch (inputString) {\n case \"start\":\n System.out.println(spin.spinWheel());\n break;\n case \"back\":\n return;\n default:\n // this should never happen\n throw new RuntimeException(\"Unexpected: '\" + inputString + \"'\");\n }\n }\n }\n}\n</code></pre>\n\n<p>By the way, in your code, you call <code>main(args)</code> to go back to the game selection phase. Don't do that. That isn't a loop, it's recursion...and if you do it over and over, without returning, eventually your program is going to run out of stack space and crash. Not to mention, it makes exiting awkward; now you have to explicitly kill the app.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:22:44.263", "Id": "43817", "Score": "1", "body": "I would make `choice` an `enum`. This way you don't have to iterate over all `options` in `getChoice()` and it'll make the code even cleaner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:23:45.407", "Id": "43819", "Score": "0", "body": "Can you link me to a good explanation about Enums, jlordo?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T13:58:35.250", "Id": "28079", "ParentId": "28060", "Score": "5" } }, { "body": "<p>Since nobody has mentioned it so far:</p>\n\n<p><strong>All your comments are bad.</strong></p>\n\n<p>They merely repeat what the code does. They provide no additional information whatsoever. As such, they are redundant, create visual clutter which makes the code harder to read, and they need to be updated whenever your code changes, otherwise they become out of sync with the code and provide <em>false</em> information.</p>\n\n<p>All of these comments must be removed (yes, I really mean <em>all</em> comments).</p>\n\n<p>Comments should only be used to explain <em>why</em> a piece of code is in place (or why it’s missing).</p>\n\n<p>The only comment that goes in the right direction is the following:</p>\n\n<pre><code>// A good solution to not loop through all games when printing.\n</code></pre>\n\n<p>Unfortunately, it doesn’t go far enough: I still have no idea what the purpose of <code>notFound</code> is, and I suspect part of the reason is the variable name. Choose variable names that are concise yet <em>specific</em> in describing what they do. But you don’t use that variable anyway so its name doesn’t matter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:29:45.437", "Id": "43821", "Score": "0", "body": "notFound boolean is the boolean I used to throw not found errors, but unfortunately, it didn't work cause the logic was bad. and I forgot to remove it, sorry for that!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:09:21.747", "Id": "28086", "ParentId": "28060", "Score": "4" } } ]
{ "AcceptedAnswerId": "28079", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T22:48:18.953", "Id": "28060", "Score": "4", "Tags": [ "java", "beginner", "object-oriented", "game" ], "Title": "Simple spin game" }
28060
<p>How can I refactor this?</p> <pre><code>require'yaml' require 'text-table' class Yahtzee def initialize puts "Welcome to Yahtzee, please enter your name." @name = gets.chomp @turn = 0 @scorecard = {"aces" =&gt; 0, "twos" =&gt; 0, "threes" =&gt; 0, "fours" =&gt; 0, "fives" =&gt; 0, "sixes" =&gt; 0, "3 of a kind" =&gt; 0, "4 of a kind" =&gt; 0, "full house" =&gt; 0, "sm. straight" =&gt; 0, "lg. straight" =&gt; 0, "chance" =&gt; 0, "yahtzee" =&gt; 0} end def roll @roll_count = 1 @roll = Array.new(5) {rand(6) + 1} p @roll puts "That was your first roll, you are allowed 2 more rolls." more_rolls? end def more_rolls? puts "Would you like to roll again? (y or n)" roll_again_choice = gets.chomp.downcase if roll_again_choice == "y" roll_again elsif roll_again_choice == "n" section(@roll) else more_rolls? end end #Refactor for error on input of anything besides 1-5 and commas def roll_again puts "Which dice would you like to keep from this roll? (1, 2, 3, 4, 5)" dice_to_keep = gets.chomp.split(',').map {|x| (x.to_i) - 1}.map {|x| @roll[x]} new_roll = Array.new(5 - dice_to_keep.size) {rand(6) + 1} @roll = new_roll + dice_to_keep p @roll @roll_count += 1 puts "That was roll number #{@roll_count}, you have #{3-@roll_count} remaining." if @roll_count &lt; 3 more_rolls? else section(@roll) end end def section(roll) view_scorecard puts "\nYou rolled a #{roll}. What section would you like to score?" section_choice = gets.chomp.downcase section_to_score(section_choice) end def section_to_score(section_choice) if @scorecard[section_choice] == 0 case section_choice when "aces" then ones when "twos" then twos when "threes" then threes when "fours" then fours when "fives" then fives when "sixes" then sixes when "3 of a kind" then three_of_a_kind when "4 of a kind" then four_of_a_kind when "full house" then full_house when "sm. straight" then sm_straight when "lg. straight" then lg_straight when "yahtzee" then yahtzee when "chance" then @scorecard["chance"] = @roll.inject(:+) else puts "Please choose a section to score." section_choice = gets.chomp.downcase section_to_score[section_choice] end elsif @scorecard["yahtzee"] == 50 yahtzee_plus else puts "You already scored that section, please choose another section." section_choice = gets.chomp @turn -= 1 section_to_score(section_choice) end @turn += 1 if @turn == 13 @scorecard = @scorecard.each_key {|k| @scorecard[k] == "scratch" ? @scorecard[k] = 0 : @scorecard[k]} view_scorecard @top_total = @scorecard.values_at("aces", "twos", "threes", "fours", "fives", "sixes").inject(:+) @lower_total = @scorecard.values_at("3 of a kind", "4 of a kind", "full house", "sm. straight", "lg. straight", "chance", "yahtzee").inject(:+) bonus @grand_total = @top_total + @lower_total view_scorecard highscore else puts "\nYou have #{13 - @turn} turns left. Roll again." view_scorecard end end def ones if @roll.include?(1) @scorecard["aces"] = @roll.select {|x| x == 1}.inject(:+) else @scorecard["aces"] = "scratch" end end def twos if @roll.include?(2) @scorecard["twos"] = @roll.select {|x| x == 2}.inject(:+) else @scorecard["twos"] = "scratch" end end def threes if @roll.include?(3) @scorecard["threes"] = @roll.select {|x| x == 3}.inject(:+) else @scorecard["threes"] = "scratch" end end def fours if @roll.include?(4) @scorecard["fours"] = @roll.select {|x| x == 4}.inject(:+) else @scorecard["fours"] = "scratch" end end def fives if @roll.include?(5) @scorecard["fives"] = @roll.select {|x| x == 5}.inject(:+) else @scorecard["fives"] = "scratch" end end def sixes if @roll.include?(6) @scorecard["sixes"] = @roll.select {|x| x == 6}.inject(:+) else @scorecard["sixes"] = "scratch" end end def three_of_a_kind if @roll.map {|x| @roll.count(x)}.any? {|y| y &gt;= 3} @scorecard["3 of a kind"] = @roll.inject(:+) else puts "Your roll is not a 3 of a kind! Please select another section or type 'scratch' to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["3 of a kind"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else three_of_a_kind end end end def four_of_a_kind if @roll.map {|x| @roll.count(x)}.any? {|y| y &gt;= 4} @scorecard["4 of a kind"] = @roll.inject(:+) else puts "Your roll is not a 4 of a kind! Please select another section or type scratch to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["4 of a kind"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else four_of_a_kind end end end def full_house if @roll.map {|x| @roll.count(x)}.any? {|y| y == 2} &amp;&amp; @roll.map {|z| @roll.count(z)}.any? {|i| i == 3} @scorecard["full house"] = 25 else puts "Your roll is not a Full House! Please select another section or type scratch to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["full house"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else full_house end end end def has_straight?(need) num = 1 @roll = @roll.sort.uniq @roll.each_with_index do |e, i| if i &lt; @roll.length-1 then if (@roll[i+1] - @roll[i]) &gt; 1 then break if num &gt;= need num = 1 end num += 1 end end num &gt;= need end def sm_straight if has_straight?(4) @scorecard["sm. straight"] = 30 else puts "Your roll is not a sm. straight! Please select another section or type scratch to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["sm. straight"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else sm_straight end end end def lg_straight if has_straight?(5) @scorecard["lg. straight"] = 40 else puts "Your roll is not a lg. straight! Please select another section or type scratch to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["lg. straight"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else lg_straight end end end def yahtzee if @roll.uniq.size == 1 @scorecard["yahtzee"] = 50 else puts "Your roll is not a Yahtzee! Please select another section or type scratch to score 0 for this section." scratch = gets.chomp if scratch == "scratch" @scorecard["yahtzee"] = "scratch" elsif @scorecard.has_key?(scratch) @turn -= 1 section_to_score(scratch) else yahtzee end end end def yahtzee_plus if @roll.uniq.size == 1 puts "You scored another Yahtzee! Please choose what section you want to score your 100 points!" yahtzee_placement = gets.chomp @scorecard[yahtzee_placement] = 100 else "Your roll is not a Yahtzee! Please select another section." section_choice = gets.chomp @turn -= 1 section_to_score(section_choice) end end def view_scorecard table = Text::Table.new :rows =&gt; [["YAHTZEE",{:value =&gt; "Scorecard", :align =&gt; :center},"NAME:#{@name}"],:separator, ['Upper Section', 'How to Score', 'Score'], :separator, ['Aces', 'Count &amp; Add Only Aces', {:value =&gt; "#{@scorecard["aces"]}", :align =&gt; :right}], ['Twos', 'Count &amp; Add Only Twos', {:value =&gt; "#{@scorecard["twos"]}", :align =&gt; :right}], ['Threes', 'Count &amp; Add Only Threes', {:value =&gt; "#{@scorecard["threes"]}", :align =&gt; :right}], ['Fours', 'Count &amp; Add Only Fours', {:value =&gt; "#{@scorecard["fours"]}", :align =&gt; :right}], ['Fives', 'Count &amp; Add Only Fives', {:value =&gt; "#{@scorecard["fives"]}", :align =&gt; :right}], ['Sixes', 'Count &amp; Add Only Sixes', {:value =&gt; "#{@scorecard["sixes"]}", :align =&gt; :right}], :separator, ['Bonus', 'Score 35', {:value =&gt; "#{@bonus}", :align =&gt; :right}], :separator, ['Upper Total', '---------------------&gt;', {:value =&gt; "#{@top_total}", :align =&gt; :right}], :separator, ['Lower Section', 'How to Score', 'Score'], :separator, ['3 of a Kind', 'Add Total of All Dice', {:value =&gt; "#{@scorecard["3 of a kind"]}", :align =&gt; :right}], ['4 of a Kind', 'Add Total of All Dice', {:value =&gt; "#{@scorecard["4 of a kind"]}", :align =&gt; :right}], ['Full House', 'Score 25', {:value =&gt; "#{@scorecard["full house"]}", :align =&gt; :right}], ['Sm. Straight', 'Score 30', {:value =&gt; "#{@scorecard["sm. straight"]}", :align =&gt; :right}], ['Lg. Straight', 'Score 40', {:value =&gt; "#{@scorecard["lg. straight"]}", :align =&gt; :right}], ['Yahtzee', 'Score 50', {:value =&gt; "#{@scorecard["yahtzee"]}", :align =&gt; :right}], ['Chance', 'Add Total of All Dice', {:value =&gt; "#{@scorecard["chance"]}", :align =&gt; :right}], :separator, ['Lower Total', '---------------------&gt;', {:value =&gt; "#{@lower_total}", :align =&gt; :right}], :separator, ['Upper Total', '---------------------&gt;', {:value =&gt; "#{@top_total}", :align =&gt; :right}], :separator, ['Grand Total', '---------------------&gt;', {:value =&gt; "#{@grand_total}", :align =&gt; :right}]] puts table end def bonus if @top_total &gt;= 63 @top_total += 35 @bonus = 35 p "You received a 35 point bonus for having at least 63 points in the top section!" else @top_total @bonus = 0 end end def highscore if File.exists?('highscore.txt') hs = YAML.load_file("highscore.txt") else hs = { 1 =&gt; { player: '', score: 0, date: '' }, 2 =&gt; { player: '', score: 0, date: '' }, 3 =&gt; { player: '', score: 0, date: '' }, 4 =&gt; { player: '', score: 0, date: '' }, 5 =&gt; { player: '', score: 0, date: '' }, 6 =&gt; { player: '', score: 0, date: '' }, 7 =&gt; { player: '', score: 0, date: '' }, 8 =&gt; { player: '', score: 0, date: '' }, 9 =&gt; { player: '', score: 0, date: '' }, 10 =&gt; { player: '', score: 0, date: '' }, } end (1..10).each do |rank| t = Time.now if @grand_total &gt; hs[rank][:score] hs[rank][:score] = @grand_total hs[rank][:date] = "#{t.month}/#{t.day}/#{t.year}" hs[rank][:player] = @name puts "Congratulations you set a new HIGH SCORE!" break end end puts "Thanks for playing!" File.write('highscore.txt', hs.to_yaml) hs_table = YAML.load_file('highscore.txt') hs_table_rank = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th"] hs_table_players = (1..10).map do |rank| hs_table[rank][:player] end hs_table_scores = (1..10).map do |rank| hs_table[rank][:score] end hs_table_dates = (1..10).map do |rank| hs_table[rank][:date] end hs_table = hs_table_rank, hs_table_players, hs_table_scores, hs_table_dates hs_table = hs_table.transpose hs_table.unshift(["RANK", "PLAYER", "SCORE", "DATE"]) puts hs_table.to_table(:first_row_is_head =&gt; true) end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T04:56:08.517", "Id": "43781", "Score": "0", "body": "It's a lot of code, but a Ruby guy (not me) might find some improvements/best practices. Why the close vote?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:27:36.777", "Id": "43789", "Score": "0", "body": "@mnhg Questions containing just code with no explanation tend to be closed, because it's not clear what is the OP asking for. But I think that in this case, the title of the question is enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:33:48.587", "Id": "43792", "Score": "0", "body": "According to the title and the context he ask for general improvements. Stating this in the post would be nice, but doing it not seem no reason for closing this post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T20:46:15.333", "Id": "43847", "Score": "2", "body": "I was told by someone at StackOverflow that after I wrote code I was satisfied with, in this case the program executing start to finish correctly after several games, that I should put it on codereview so that more experienced programmers can refactor it and show me Ruby best practices. I am new to Ruby and programming in general, this is my first full program, I did not mean to post incorrectly if that is the case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T09:48:56.230", "Id": "44144", "Score": "0", "body": "For starters you might want to consider switching to two-space indent, which is a very strong convention in ruby." } ]
[ { "body": "<p>I would start with code formatting :D And replacing <code>@scorecard</code> initialization with following one (instead of explicit zerofication):</p>\n\n<pre><code>@scorecard = Hash.new{ |h,k| h[k] = 0 }\n</code></pre>\n\n<p>In nearly all cases you use <code>gets</code>, you puts before:</p>\n\n<pre><code>puts \"Your roll is not a Full House!..\"\nscratch = gets.chomp\n</code></pre>\n\n<p>You can extract this into a dedicated method:</p>\n\n<pre><code>def ask message\n puts message\n gets.chomp\nend\n</code></pre>\n\n<p>So that your calls will become:</p>\n\n<pre><code>scratch = ask \"Your roll is not a Full House!..\"\n</code></pre>\n\n<p>This place seems useless:</p>\n\n<pre><code>File.write('highscore.txt', hs.to_yaml)\nhs_table = YAML.load_file('highscore.txt')\n</code></pre>\n\n<p>Final multiple <code>map</code>s can be replaced into something more beautiful, but we will need something to make ordinal numbers, we'll steel this method from ActiveSupport (Ruby on Rails):</p>\n\n<pre><code>def ordinalize(number)\n abs_number = number.to_i.abs\n\n if (11..13).include?(abs_number % 100)\n suffix = \"th\"\n else\n suffix = case abs_number % 10\n when 1; \"st\"\n when 2; \"nd\"\n when 3; \"rd\"\n else \"th\"\n end\n end\n\n \"#{number}#{suffix}\"\nend\n</code></pre>\n\n<p>Once we have this, we can refactor last maps into something like this:</p>\n\n<pre><code>hs_table = [[\"RANK\", \"PLAYER\", \"SCORE\", \"DATE\"]]\n(1..10).each do |rank|\n hs_table &lt;&lt; [\n ordinalize(rank),\n hs_table[rank][:player],\n hs_table[rank][:score],\n hs_table[rank][:date]\n ]\nend\n</code></pre>\n\n<p>Well at least these are first steps I would take. After first iteration, there might be more ideas more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T16:09:19.700", "Id": "28199", "ParentId": "28063", "Score": "4" } } ]
{ "AcceptedAnswerId": "28199", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T23:20:09.600", "Id": "28063", "Score": "4", "Tags": [ "ruby", "game", "random", "playing-cards", "dice" ], "Title": "Yahtzee program" }
28063
<p><strong>MyText.txt</strong> </p> <pre><code>This is line 1 This is line 2 Time Taken for writing this# 0 days 0 hrs 1 min 5 sec Nothing Important Sample Text </code></pre> <p><strong>Objective</strong></p> <p>To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file (which is a value already inside the file)"</p> <p><strong>My Code</strong></p> <pre><code>with open('MyText.txt', 'r') as f: f.readline() for line in f: if 'Sample Text' in line: print "I have found it" f.seek(0) f.readline() for line in f: if 'Time Taken' in line: print line print ' '.join(line.split()) f.close() </code></pre> <p>The code is working fine. I want to know if this code can be made even better. Considering I am new to Python, I am sure there would be a better way to code this. Can anyone suggest alternative/faster approaches for this?</p>
[]
[ { "body": "<p>How about this:</p>\n\n<pre><code>with open('MyText.txt', 'r') as f:\n time = None\n for line in f:\n if 'Time Taken' in line:\n time = line[line.find(\"#\") + 1:].strip()\n if 'Sample Text' in line:\n print \"I have found it\"\n if time:\n print \"Time taken:\", time\n</code></pre>\n\n<ul>\n<li>not sure what that first <code>f.readline()</code> was for...</li>\n<li>no need to explicitly invoke <code>f.close()</code> when using <code>with</code></li>\n<li>find time taken in the first pass through the file instead of resetting the pointer and seeking again</li>\n<li>you could use <code>find()</code> to get the substring after the <code>#</code> and <code>strip()</code> to get rid of the extra spaces</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T23:08:57.440", "Id": "43854", "Score": "0", "body": "Point1 ,Point2 and Point3 are very valid. Thanks for pinting those out. Point 4: `print ' '.join(line.split()) print line[line.find(\"#\") + 1:].strip()` give the following output `Time Taken for writing this# 0 days 0 hrs 0 min 14 sec\nTime Taken for writing this# 0 days 0 hrs 0 min 14 sec` I prefer first to the second as it looks better formatted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T08:58:17.273", "Id": "28070", "ParentId": "28067", "Score": "0" } }, { "body": "<p>as you say, it does look like this code is doing exactly what you want. But it also looks like you are repeating yourself in a couple of places.</p>\n\n<p>If it was me, I would prefer to loop through the file only once and check for both <code>Sample Text</code> and <code>Time Taken</code> at the same time, and then only print out if the sample text is there:</p>\n\n<pre><code>def my_read(my_text):\n time_taken, sample_text = False, False\n with open(my_text) as f:\n for i in f:\n time_taken = ' '.join(i.split()) if 'Time Taken' in i else time_taken\n sample_text = 'I have found it!' if 'Sample Text' in i else sample_text\n\n # now, if sample text was found, print out\n if sample_text:\n print sample_text\n print time_taken\n return\n\nmy_read('MyText.txt')\n</code></pre>\n\n<p>By testing for both, you avoid having to use <code>f.seek(0)</code> and start looping through the file again. Of course, this is based on the sample input above - and assumes that there isn't multiple lines with 'Time taken' or 'Sample Text' in them. </p>\n\n<p>Hope this helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:14:53.973", "Id": "28071", "ParentId": "28067", "Score": "1" } } ]
{ "AcceptedAnswerId": "28071", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T06:10:09.127", "Id": "28067", "Score": "4", "Tags": [ "python", "beginner", "file", "python-2.x" ], "Title": "Text file reading and printing data" }
28067
<h2><strong>Introduction</strong></h2> <p>So i am building a SPA with AngularJS. The application provides a large number of <code>&lt;input&gt;</code> elements and can be seen as a huge form.</p> <p>However, i am not using an actual <code>&lt;form&gt;</code> element because of the applications architecture. Once everything is filled, all of the data will be submitted by a single button, though.</p> <p>This has lead to the problem that i can not use Angular's build-in form validation. I was forced to write my own implementation.</p> <h2><strong>The issue</strong></h2> <p>What follows is my approach to validate the stuff. Everything works fine for me and gets the job done. Nevertheless, i would like to hear the opinions of some advanced or maybe even professional colleagues on how good or bad said approach is and where it could be improved.</p> <strong>HTML</strong> <p><br> This is a snippet from the applications 'form'. To maintain better readability, i've stripped out the ng-model attributes.</p> <pre><code>&lt;div&gt; &lt;label for="searchClient"&gt;Kundennummer&lt;/label&gt; &lt;input validate-string type="text" id="searchClient"&gt; &lt;label for="recName"&gt;Name*&lt;/label&gt; &lt;input validate-string type="text" id="recName"&gt; &lt;/div&gt; </code></pre> <p>As you can see, validation is triggered via a directive restricted to attribute.</p> <strong>The directive</strong> <p><br></p> <pre><code>app.directive('validateString',function(){ return{ restrict: 'A', link: function(scope, element){ var el = angular.element(element); el.attr('valid','nope'); element.bind('input',function(){ if (element[0].value !== ""){ el.removeAttr('valid'); } else{el.attr('valid','false');} }) } } }); </code></pre> <p>The directive sets a default attribute of valid="false" to every element the directive is attached to. If an input is made, the attribute is removed. Once everything is done and the user decides to submit, a validation function will fire:</p> <strong>validate()</strong> <p><br></p> <pre><code>Shipment.prototype.validate = function(){ var inputs = $document.find('input'); var inValidElements = 0; for (var i = 0; i&lt;inputs.length;i++){ if(inputs[i].attributes.valid !== undefined &amp;&amp; inputs[i].attributes.valid !== ""){ inValidElements++; } } console.log(inValidElements); // Here we can handle those invalidElements }; </code></pre> <p>validate() will look up all <code>&lt;input&gt;</code> elements on the page and set a default number of invalid elements of zero. Then, it will take each of those elements, check whether or not it has an attribute of <code>valid</code> and if so, increment the invalidElements counter. At this point, further handling of those elements would be possible.</p> <h2><strong>Conclusion</strong></h2> <p>Would you appreciate this approach of validating a pseudo-form?</p>
[]
[ { "body": "<p>While your code works, I would have structured it differently. I would suggest reading <a href=\"https://stackoverflow.com/q/14994391/677526\">this question</a> on StackOverflow.</p>\n\n<p>In your position, I'd have written a directive to place on the outer container that holds all of the inputs, and I would have made your <code>validate</code> function a part of the directive itself. By doing this, you might be able to avoid looking for elements that have a specific class set; you could simply use the values of the datamodel to determine that. I would probably use an object to hold key/value pairs, and use the input ID as the key (with the validity value as the object).</p>\n\n<p>I don't have sample code at the moment (and it seems that, for this site, sample code is essential to a good answer) but I'll try to mock something up tomorrow, perhaps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:56:09.093", "Id": "44011", "Score": "0", "body": "Thank you very much so far, i will try to implement your concept. Nevertheless, i would appreciate a sample, as you suggested." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T03:55:24.107", "Id": "28185", "ParentId": "28068", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T08:25:21.900", "Id": "28068", "Score": "-2", "Tags": [ "javascript", "html", "validation", "angular.js" ], "Title": "An own approach to Angularjs validation" }
28068
<p>In my system there are 3 main functionalities:</p> <ol> <li>Add users to database </li> <li>Delete users from database </li> <li>Updater users </li> </ol> <p>This is the screenshot in my UI:</p> <p><img src="https://i.stack.imgur.com/bDZaB.jpg" alt="enter image description here"></p> <p>When clicking on the button of add new user, a jQuery modal form dialog appears and there is a form to add user details to the database. </p> <p>When clicking on the images under delete column (see above image), a jQuery confirmation dialog appears, and if confirmation is true, the user should be deleted from the database. In the meantime, a particular table row, which belongs to the deleted user, should disappear from the table with a fadeout effect. </p> <p>Here I have use jQuery and Ajax with PHP and MySQL for the project first time. How is my jQuery and Ajax code? Are there any security issues or refactoring method in my code?</p> <p>NOTE: Adding/deleting functionality is working perfectly with the posted code. </p> <p><strong>jQuery:</strong></p> <pre><code>$(function(){ $( "input[type=submit], button" ) .button() .click(function( event ) { event.preventDefault(); }); // form validation var name = $( "#name" ), address = $( "#address" ), city = $( "#city" ), all = $( [] ).add( name ).add( address ).add( city ), tips = $( ".validateTips" ); function updateTips( t ) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 1500 ); tips.css("color", "red"); } function checkLength( o, n, min, max ) { if ( o.val().length &gt; max || o.val().length &lt; min ) { o.addClass( "ui-state-error" ); updateTips( "Length of " + n + " must be between " + min + " and " + max + "." ); return false; } else { return true; } } function checkRegexp( o, regexp, n ) { if ( !( regexp.test( o.val() ) ) ) { o.addClass( "ui-state-error" ); updateTips( n ); return false; } else { return true; } } $("#dialog").dialog({ autoOpen: false, height: 'auto', width: 350, modal: true, buttons: { "Add New User": function() { var bValid = true; all.removeClass( "ui-state-error" ); bValid = bValid &amp;&amp; checkLength( name, "Your Name", 3, 60 ); bValid = bValid &amp;&amp; checkLength( address, "Your Address", 3, 50 ); bValid = bValid &amp;&amp; checkLength( city, "Your City", 3, 40 ); bValid = bValid &amp;&amp; checkRegexp( name, /^[a-z -']+$/i, "Your name may consist of A-Z, a-z, 0-9, underscores, begin with a letter." ); bValid = bValid &amp;&amp; checkRegexp( address, /^[a-z -']+$/i, "Your name may consist of A-Z, a-z, 0-9, underscores, begin with a letter." ); bValid = bValid &amp;&amp; checkRegexp( city, /^[a-z -']+$/i, "Your name may consist of A-Z, a-z, 0-9, underscores, begin with a letter." ); if ( bValid) { $.ajax({ type: "POST", // HTTP method POST or GET url: "process.php", //Where to make Ajax calls //dataType:"text", // Data type, HTML, json etc. dataType: 'html', data: { name: $('#name').val(), address: $('#address').val(), city: $('#city').val() }, beforeSend: function(){ $('#loading').dialog({ height: 57, width: 400, modal: true, position: { my: "center top+20", at: "center top+20", of: window }, resizable: false, draggable: false, dialogClass: 'no-close loading-dialog', hide: { effect: "fade", duration: 500 } }); }, success:function(data){ $('#manage_user table &gt; tbody:last').find('tr:first').before(data); }, error:function (xhr, ajaxOptions, thrownError){ //On error, we alert user alert(thrownError); }, complete: function(){ //alert('update success'); //$('#loading').hide(); setTimeout("$('#loading').dialog('close');", 300); $('#success').dialog({ height: 57, width: 400, modal: true, position: { my: "center top+20", at: "center top+20", of: window }, resizable: false, draggable: false, dialogClass: 'no-close success-dialog', hide: { effect: "fade", duration: 1000 } }); setTimeout("$('#success').fadeOut('slow').dialog('close');", 3000); } }); $(this).dialog("close"); } }, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { all.val( "" ).removeClass( "ui-state-error" ); } }); $( "#FormSubmit" ) .button() .click(function() { $( "#dialog" ).dialog( "open" ); }); $('#filter-value').change(function(){ var filterValue = $(this).val(); //console.log(filterValue); $.ajax({ type: 'post', url: 'table.php', dataType: 'html', data: {filter: filterValue}, success:function(data){ $('#response').html(data); //alert(data); }, error:function (xhr, ajaxOptions, thrownError){ //On error, we alert user alert(thrownError); }, complete: function(){ //alert('update success'); } }); }); // set a default value to dropdown $('#filter-value').val(5).change(); //##### Send delete Ajax request to process.php ######### $("body").on("click", "#response table td a.del_button", function(e) { e.returnValue = false; var clickedID = this.id.split('-'); //Split string (Split works as PHP explode) var DbNumberID = clickedID[1]; //and get number from array var myData = 'recordToDelete='+ DbNumberID; //build a post data structure //console.log(myData); var $tr = $(this).closest('tr'); //here we hold a reference to the clicked tr which will be later used to delete the row $("#delete_this_user").dialog({ resizable: false, height:140, modal: true, buttons: { "Yes": function() { //$row.remove(); $(this).dialog( "close" ); $.ajax({ type: "POST", // HTTP method POST or GET url: "process.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables beforeSend: function(){ $('#loading').dialog({ height: 57, width: 400, modal: true, position: { my: "center top+20", at: "center top+20", of: window }, resizable: false, draggable: false, dialogClass: 'no-close loading-dialog', hide: { effect: "fade", duration: 500 } }); }, success:function(response){ //on success, hide element user wants to delete. $tr.find('td').fadeOut(1000,function(){ $tr.remove(); }); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }, complete: function(){ setTimeout("$('#loading').dialog('close');", 300); $('#success').dialog({ height: 57, width: 400, modal: true, position: { my: "center top+20", at: "center top+20", of: window }, resizable: false, draggable: false, dialogClass: 'no-close success-dialog', hide: { effect: "fade", duration: 1000 } }); setTimeout("$('#success').fadeOut('slow').dialog('close');", 3000); } }); }, "no": function() { $(this).dialog( "close" ); } }, position: { my: 'top center', at: 'top center', of: $('#response table') } }); }); }); </code></pre> <p>This is the HTML from the index.php page:</p> <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;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;User Registration System&lt;/title&gt; &lt;link type="text/css" rel="stylesheet" href="css/styles.css" media="all" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/jquery-ui-1.10.3.custom.css" /&gt; &lt;script type="text/javascript" src="js/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery-ui-1.10.3.custom.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/complete.js" &gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;User Management System&lt;/h1&gt; &lt;div id="popup-msg"&gt; &lt;div id="loading" title="Loading"&gt; &lt;img src="images/my-ajax-loader.gif" width="25" /&gt; &lt;p&gt;Please wait a few seconds.&lt;/p&gt; &lt;/div&gt; &lt;div id="success" title="Hurray!"&gt; &lt;p&gt;User table is updated.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="manage_user"&gt; &lt;form action="" method=""&gt; &lt;div id="response"&gt;&lt;/div&gt; &lt;button id="FormSubmit"&gt;Add New User&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;br /&gt; &lt;div style="margin: 0 20px 20px;"&gt; &lt;form method="post" action=""&gt; &lt;select id="filter-value" name="filter"&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="20"&gt;20&lt;/option&gt; &lt;option value="30"&gt;30&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="dialog" class="new_user_dialog_box" title="Add New User"&gt; &lt;p&gt;Fill this form with your details and click on 'Add New User' button to register.&lt;/p&gt; &lt;p class="validateTips"&gt;All form fields are required.&lt;/p&gt; &lt;div id="new_user_form"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Name :&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="name" value="" id="name" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address :&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="address" value="" id="address" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;City :&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="city" value="" id="city" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="delete_this_user" title="Delete User"&gt; &lt;p&gt;Are you sure you want to delete this user?&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This is the PHP code for the table display on index.php:</p> <pre><code>&lt;?php //echo '&lt;pre&gt;', print_r($_POST) . '&lt;/pre&gt;'; //die('I am here'); if ( isset($_POST['filter'])) { $filter = $_POST['filter']; echo $filter; // include configuration file require_once('../test.php'); // make the query $q = "SELECT id, name, address, city FROM users ORDER BY id DESC LIMIT $filter"; // execute the query $r = mysqli_query($dbc, $q); // count the users $num = mysqli_num_rows($r); // define output variable $output = ''; // get all registered users if ( $num &gt;= 1 ) { // print how many users are $output = "&lt;h2&gt;There are $num registered users&lt;/h2&gt;\n"; // print the table header $output .= "&lt;table&gt;\n"; $output .= " &lt;tr&gt;\n"; $output .= " &lt;th&gt;&lt;input type='checkbox' class='selectAll' name='selectAll' value='' /&gt; Name&lt;/th&gt;\n"; $output .= " &lt;th&gt;Address&lt;/th&gt;\n"; $output .= " &lt;th&gt;City&lt;/th&gt;\n"; $output .= " &lt;th&gt;Edit&lt;/th&gt;\n"; $output .= " &lt;th&gt;Delete&lt;/th&gt;\n"; $output .= " &lt;/tr&gt;\n"; $output .= " &lt;tbody&gt;\n"; while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){ $id = $row['id']; $name = $row['name']; $address = $row['address']; $city = $row['city']; // make the table body $output .= " &lt;tr&gt;\n"; $output .= " &lt;td&gt;&lt;input type='checkbox' name='' value='' class='' /&gt;&amp;nbsp;&amp;nbsp;$name&lt;/td&gt;\n"; $output .= " &lt;td&gt;$address&lt;/td&gt;\n"; $output .= " &lt;td&gt;$city&lt;/td&gt;\n"; $output .= " &lt;td&gt;&lt;a href='#' id='edit-$id' class='edit_button'&gt;&lt;span class='edit_ico'&gt;&lt;/span&gt;&lt;/a&gt;&lt;/td&gt;\n"; $output .= " &lt;td&gt;&lt;a href='#' id='delete-$id' class='del_button'&gt;&lt;span class='delete_ico'&gt;&lt;/span&gt;&lt;/a&gt;&lt;/td&gt;\n"; $output .= " &lt;/tr&gt;\n"; } } else { $output .= "&lt;h2&gt;There is no any registered users so far.&lt;/h2&gt;\n"; } // close the table $output .= " &lt;/tbody&gt;\n"; $output .= "&lt;/table&gt;\n"; echo $output; //close db connection mysqli_close($dbc); } ?&gt; </code></pre> <p>This is the code from the proccess.php page:</p> <pre><code>&lt;?php //include db configuration file include_once("../test.php"); if ( (isset($_POST["name"]) &amp;&amp; strlen($_POST["name"]) &gt;= 3 &amp;&amp; strlen($_POST["name"]) &lt;= 60) &amp;&amp; (isset($_POST["address"]) &amp;&amp; strlen($_POST["address"]) &gt;= 3 &amp;&amp; strlen($_POST["address"]) &lt;= 50) &amp;&amp; (isset($_POST["city"]) &amp;&amp; strlen($_POST["city"]) &gt;= 3 &amp;&amp; strlen($_POST["city"]) &lt;= 40) ) { //check $_POST["name"] and $_POST["address"] and $_POST["city"] are not empty $name = $_POST["name"]; $address = $_POST["address"]; $city = $_POST["city"]; $q = "INSERT INTO users ( name, address, city) VALUES ('".$name."','".$address."','".$city."')"; $r = mysqli_query($dbc, $q); if ( $r ) { // make the table row $output = "&lt;tr&gt;\n"; $output .= " &lt;td&gt;&lt;input type='checkbox' name='' value='' class='' /&gt;&amp;nbsp;&amp;nbsp;$name&lt;/td&gt;\n"; $output .= " &lt;td&gt;$address&lt;/td&gt;\n"; $output .= " &lt;td&gt;$city&lt;/td&gt;\n"; $output .= " &lt;td&gt;&lt;span class='edit_ico'&gt;&lt;/span&gt;&lt;/td&gt;\n"; $output .= " &lt;td&gt;&lt;span class='delete_ico'&gt;&lt;/span&gt;&lt;/td&gt;\n"; $output .= "&lt;/tr&gt;\n"; //$output = " &lt;td&gt;&lt;input type='checkbox' name='' value='' class='' /&gt;&amp;nbsp;&amp;nbsp;$name&lt;/td&gt;\n"; //$output .= " &lt;td&gt;$address&lt;/td&gt;\n"; //$output .= " &lt;td&gt;$city&lt;/td&gt;\n"; //$output .= " &lt;td&gt;&lt;span class='edit_ico'&gt;&lt;/span&gt;&lt;/td&gt;\n"; //$output .= " &lt;td&gt;&lt;span class='delete_ico'&gt;&lt;/span&gt;&lt;/td&gt;\n"; echo $output; } else { echo 'query error'; } } elseif( isset($_POST["recordToDelete"]) &amp;&amp; strlen($_POST["recordToDelete"]) &gt; 0 &amp;&amp; is_numeric($_POST["recordToDelete"])) { //do we have a delete request? $_POST["recordToDelete"] //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign. $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); //try deleting record using the record ID we received from POST $q = "DELETE FROM users WHERE id=$idToDelete"; $r = mysqli_query($dbc, $q); if(mysqli_affected_rows($dbc) &gt; 1 ) { //If mysql delete query was unsuccessful, output error header('HTTP/1.1 500 Could not delete record!'); exit(); } mysqli_close($dbc); //close db connection } else { echo "error in post array"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:20:57.300", "Id": "43788", "Score": "0", "body": "Is this application tested? keep in mind that unit or integration tests help a lot in the refactorization process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T16:17:39.860", "Id": "53976", "Score": "0", "body": "Using `mysqli_*` is good, but better still is using it with _prepared statements_, which the old `mysql_*` extension did not support\\" } ]
[ { "body": "<p>I would assess what your needs are in terms of refactoring - am I going to attain any benefit from doing so?</p>\n\n<p>In either case, you will want to tidy your code: for example, you are directly placing data inside a SQL statement without escaping it. Use <code>mysql_real_escape_string</code> to escape the data before putting it into the query for execution.</p>\n\n<p>Second, it might be a good idea to separate your concerns into business logic and view logic, consider using an architecture to help you shape the structure of the application. That way, your file isn't a mixture of SQL and echoing content. Bear in mind, that a lot of developers practice DRY - Don't Repeat Yourself i.e make code as generic as possible without compromise. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:26:38.260", "Id": "43987", "Score": "0", "body": "Thanks for answer. But can you elaborate your second suggestion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T20:48:10.633", "Id": "53850", "Score": "3", "body": "`mysql_real_escape_string` is deprecated: don't use it. See: http://php.net/manual/en/function.mysql-real-escape-string.php" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:55:32.910", "Id": "28096", "ParentId": "28069", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T08:56:09.543", "Id": "28069", "Score": "2", "Tags": [ "javascript", "php", "jquery", "html", "mysql" ], "Title": "Managing a user database" }
28069
<p>I am unit testing that the URL that I give to my <code>IRestClient</code> is valid. This client talks to a third party Web API.</p> <p>The test is as below: </p> <pre><code> [Test] [ExpectedException("System.UriFormatException")] public void MakeRequest_EndPointIsInValid_ThrowsUriFormatException() { var stub = new Mock&lt;IRestClient&gt;(); stub.Setup(x =&gt; x.MakeRequest()).Throws&lt;UriFormatException&gt;(); string results = new RestClient("example", "method=payment&amp;params[Key1]=Value1&amp;params[Key2]=Value2&amp;params[Key3]=Value3").MakeRequest(); } </code></pre> <p>The RestClient class under test is</p> <pre><code>public class RestClient : IRestClient { /// &lt;summary&gt; /// Web Api Url End point. /// &lt;/summary&gt; public string EndPoint { get; set; } /// &lt;summary&gt; /// The Post data. /// &lt;/summary&gt; public string PostData { get; set; } /// &lt;summary&gt; /// Do Request. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public string MakeRequest() { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; if (string.IsNullOrWhiteSpace(PostData)) throw new ArgumentNullException("PostData"); if (string.IsNullOrWhiteSpace(EndPoint)) throw new ArgumentNullException("EndPoint"); // I want to test this Uri parsing. Uri uriResult; if (!Uri.TryCreate(EndPoint, UriKind.Absolute, out uriResult) || uriResult.Scheme != Uri.UriSchemeHttps) throw new UriFormatException("EndPoint"); return client.UploadString(uriResult, PostData); } } } </code></pre> <ol> <li><p>How is this test and class under test?</p></li> <li><p>Is my fake object a stub or a mock? I believe it's a stub as I am just forcing the return of a UriFormatException.</p></li> <li><p>Any improvements?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:53:39.843", "Id": "43793", "Score": "0", "body": "Does that code even compile? You are passing in constructor arguments to the RestClient but have no matching constructor defined?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T10:03:40.537", "Id": "43794", "Score": "0", "body": "I omitted the constructor for brevity. It just sets the two properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:37:28.850", "Id": "43812", "Score": "0", "body": "Is the test actually passing? It seems to be you are using two different objects, one mocked, and one sut (service under test), and they are unrelated. Of course, I haven't used Moq before so maybe I'm missing something." } ]
[ { "body": "<p>I think you are confused about what a mock is actually supposed to be used for. A mock is to create a fake object to pass into a parameter, and is very useful when testing systems that use dependency injection exclusively.</p>\n\n<p>Take this for example:</p>\n\n<pre><code>public interface IFoo\n{\n string SomeMethod(IBar bar);\n}\n\n\npublic interfact IBar\n{\n int CalculateSomething();\n}\n\n\npublic class Foo : IFoo\n{\n public string SomeMethod(IBar bar)\n {\n if (bar.CalculateSomething() &gt; 10)\n {\n // insert more code\n\n return \"Completed\";\n }\n\n return string.Empty;\n }\n }\n</code></pre>\n\n<p>One of your tests is to ensure the <code>// insert more code</code> section works. To get into that code you need the IBar.CalculateSomething() to return a value > 10. You also don't want to create an instance of the Bar class, because then you are not testing one unit of code. This is where mocking comes into play. The way to make sure you hit the code is to pass a mock into the method, that is set up to pass the if statement</p>\n\n<pre><code>[Test]\npublic void EnsureThatInserMoreCodeWorks()\n{\n var bar = Mock.Create&lt;IBar&gt;();\n bar.SetUp(b =&gt; b.CalculateSomething()).Returns(15);\n\n var sut = new Foo();\n\n var result = sut.SomeMethod(bar.Object);\n\n Assert.That(result, Is.EqualTo(\"Completed\");\n}\n</code></pre>\n\n<p>This is really simple, and I hope there is more to the <code>// insert more code</code> section to test, but this gives an easy to follow example of using mocks.</p>\n\n<p>To make your test pass, you would simply have to pass in an invalid uri string. No Mock needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T20:20:46.860", "Id": "43845", "Score": "0", "body": "Good point Jeff" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:35:47.743", "Id": "43869", "Score": "0", "body": "Thanks - \"A mock is to create a fake object to pass into a parameter\". This helped me wrap my head around this a bit more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:38:12.470", "Id": "43870", "Score": "0", "body": "One more question; semantically, is the fake a mock or a stub?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:48:43.927", "Id": "28088", "ParentId": "28072", "Score": "4" } }, { "body": "<p>I think I agree with Jeff. So because of this, perhaps you might want to reconsider the design? Do you really want to make RestClient dependant on WebClient or could we make it dependent on an interface instead and decouple it from that side of things? Perhaps this is overkill?</p>\n\n<p>Here's a crack at an alternative for comments:</p>\n\n<p><strong>The testing</strong></p>\n\n<pre><code>[TestMethod]\n[ExpectedException(typeof(System.UriFormatException))]\npublic void Uri_InvalidFormatTest()\n{\n var requestMock = new Mock&lt;IRequestClient&gt;(); \n var client = new RestClient(requestMock.Object);\n\n string address = \"example\";\n string postData = \"method=payment&amp;params[Key1]=Value1&amp;params[Key2]=Value2&amp;params[Key3]=Value3\";\n\n client.MakeRequest(address, postData);\n}\n\n[TestMethod]\n public void Uri_ValidFormatTest()\n {\n var requestMock = new Mock&lt;IRequestClient&gt;(); \n var client = new RestClient(requestMock.Object);\n\n string address = \"https://www.google.co.nz\";\n string postData = \"method=payment&amp;params[Key1]=Value1&amp;params[Key2]=Value2&amp;params[Key3]=Value3\";\n\n requestMock.Setup(x =&gt; x.UploadString(new Uri(address), postData)).Returns(\"Success\");\n\n Assert.AreEqual(\"Success\", client.MakeRequest(address, postData));\n }\n</code></pre>\n\n<p><strong>The abstraction</strong></p>\n\n<pre><code>public interface IRestClient\n{\n string MakeRequest(string endPoint, string postData);\n}\n\npublic interface IRequestClient\n{\n void ContentType(string contentType);\n string UploadString(Uri address, string postData);\n}\n</code></pre>\n\n<p><strong>The implementation</strong></p>\n\n<pre><code>public class RequestClient: IRequestClient\n{\n private string _contentType;\n\n public void ContentType(string contentType)\n {\n _contentType = contentType;\n }\n\n public string UploadString(Uri address, string postData)\n {\n using (WebClient client = new WebClient())\n {\n if (!string.IsNullOrWhiteSpace(_contentType))\n {\n client.Headers[HttpRequestHeader.ContentType] = _contentType;\n }\n\n return client.UploadString(address, postData);\n }\n }\n}\n\npublic class RestClient : IRestClient\n{\n private readonly IRequestClient _client;\n\n public RestClient(IRequestClient client)\n {\n _client = client;\n }\n\n /// &lt;summary&gt;\n /// Do Request.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public string MakeRequest(string endPoint, string postData)\n {\n if (string.IsNullOrWhiteSpace(postData)) throw new ArgumentNullException(\"postData\");\n if (string.IsNullOrWhiteSpace(endPoint)) throw new ArgumentNullException(\"endPoint\");\n\n Uri uriResult;\n if (!Uri.TryCreate(endPoint, UriKind.Absolute, out uriResult) || uriResult.Scheme != Uri.UriSchemeHttps)\n {\n throw new UriFormatException(\"EndPoint\");\n }\n\n _client.ContentType(\"application/x-www-form-urlencoded\");\n return _client.UploadString(uriResult, postData);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:34:36.003", "Id": "43868", "Score": "0", "body": "Thanks for your clear answer. To confirm, we are testing RestClient's interaction with RequestClient? We are forcing the RequestClient to always return \"Success\" and we are testing that RestClient behaves correctly under this situation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T20:56:55.190", "Id": "43998", "Score": "0", "body": "In the cases above we would be testing MakeRequests functionality. By mocking the IRestClient you then ensure you don't have to worry about it's implementation in order to test RestClient. Hence you could of coded RestClient first, put in a test then coded RequestClient knowning RestClient was already test? Hope tha makes sense :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T20:49:31.633", "Id": "28101", "ParentId": "28072", "Score": "2" } } ]
{ "AcceptedAnswerId": "28088", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:41:24.310", "Id": "28072", "Score": "6", "Tags": [ "c#", "unit-testing", "moq", "nunit" ], "Title": "REST Web Api unit test endpoint validity with NUnit and Moq" }
28072
<p>I'm currently writing a REST-tool that connects to a third-party server (duh). They offer a fairly large (if not too large) API in a single wsdl file, as well as separate wsdl's for each specific part of data you want to work on. <br/> When writing my code, I created an abstract <code>Api</code> class, and a number of child classes, one for each subset of the API.</p> <p>Since all requests are available through a single, "master-api", there is only 1 user-password required to connect, so I've created the <code>getClient</code> and <code>setClient</code> methods in the abstract class.<br/> Since it's not unlikely form me to be working with two, or three of these API-classes, I decided to create a private static property in the abstract class. This is to avoid excessive internal method calls, brought along by lazy-loading.<br/> Is this a valid use-case for the <code>static</code> keyword? It's the only time I'm using <code>static</code> in my entire code, and I have this acquired repulsion for using it. </p> <p>Anyway, here's some (grossly oversimplified) version of my code:</p> <pre><code>namespace MyLib; use Tool\Application, Tool\Command;//it's a CLI tool use MyLib\Soap\Client; use \Zend_Config;//can't help but liking the old Zend_Config absctract class Api { //all properties have a getter, which lazy-loads the correct object, where possible //can be injected through constructor, setter or via $this-&gt;command private $app = null; //inject via setter, get from application or command private $config = null; //inject via setter or child constructor private $command = null; /* This is the one */ private static $login; public function __construct(Application $app = null) { $this-&gt;setApplication($app); if (!is_callable(array($this, 'init'))) { throw new \RuntimeException('Impossible, yet somehow '.get_class($this).'::init() cannot be called'); } return $this-&gt;init(); } abstract protected functoin init(); final private function getLogin() { if (self::$login === null) { $config = $this-&gt;getConfig(); $this-&gt;setLogin(array( array( 'login' =&gt; $config-&gt;api-&gt;login, 'pwd' =&gt; $config-&gt;api-&gt;pwd ) ); } return self::$login; } final private function setLogin(array $login) { if (count(array_filter($login) === 2) { self::$login = $login; } return $this; } protected fucntion getClient() { if ($this-&gt;client === null) { $wsdl = $this-&gt;getConfig(); $wsdl-&gt;api-&gt;{$this-&gt;getName()}-&gt;wsdl; $this-&gt;setClient( new Client( $wsdl, $this-&gt;getLogin() ) ); } return $this-&gt;client; } public fucntion setClient(Client $client = null) { if ($this-&gt;client) { $this-&gt;client-&gt;disconnect(); } $this-&gt;client = $client; return $this; } protected function getConfig() { if ($this-&gt;config === null) {//getApplication falls back to $this-&gt;getCommand()-&gt;getApplication() $this-&gt;setConfig( $this-&gt;getApplication()-&gt;getConfig() ); } return $this-&gt;config; } public function setConfig(Zend_Config $config = null) { $this-&gt;config = $config; return $this; } } </code></pre> <p>As for the child classes, they look something like this:</p> <pre><code>namespace MyLib\Apis; use MyLib\Api; use MyLib\Data\Models\Model; class Foo extends Api { public function __construct($mixed = null) { if ($mixed instanceof Command) { $this-&gt;setCommand($mixed); } parent::__construct($mixed instanceof Application ? $mixed : null); } protected function init() { $this-&gt;setName('foo');//&lt;-- init is a tad more complicated, but not relevant here } public function doRequest(Model $data = null) { $client = $this-&gt;getClient(); //worst case here: // parent::getClient getConfig -&gt; getApplication -&gt; getCommand {-&gt;setApplication(command-&gt;getApplication())}-&gt;getConfig &lt;== setConfig of $this here return $client-&gt;getSomething( array( 'param' =&gt; $data-&gt;foobar ) ); } } </code></pre> <p>Every <code>getClient</code> <em>can</em> result in as much as 12 method calls. By creating a static array containing the login data, I can make sure that the maximum number of calls is 12 once, and then, a maximum of 9 calls applies to all instances.<br/> If this is indeed a good use case for statics, I'm thinking of creating a second static (though my heart really is bleeding just thinking about it) that'll hold the <code>Application</code> instance, which, in order for an application to use my lib, it needs to hold the config file, which is what I'm after.</p> <p>If I create those two statics, the theoretical maximum of 12 method calls remains, but after the full 12 calls have been made once, This can be reduced to only 4 when I'm getting the config, 6 upon calling <code>getClient</code> the first time. <br/> Half of the calls I'm currently making, which, could make a difference IMO</p>
[]
[ { "body": "<p>Is it a \"good\" use-case? Not in my opinion. Is it \"decent\"? I think it is decent enough to get the job done if that is how you want to do it. The beauty of it is, anything is \"decent\" enough if it works for you, and things could always be \"better\". I find that I mostly use statics for Singletons and simple utility functions -- otherwise, the benefits rarely outweigh the drawbacks.</p>\n\n<p>Personally, I would not go this route; even though it may make things easier to write initially, it would also make it hard to do any type of unit testing. </p>\n\n<p>It seems like you may also be assuming that no one, ever, for any reason, may have more than one set of login details that they would like to use at the same time. While that might be true, I wouldn't want to make that assumption.</p>\n\n<p>If it were me, I would approach this like any other adapter -- create independent classes with single responsibilities and use dependency injection for configuration/etc. Finally, I would create a facade which implements those responsibilities, and handles the dependencies, in order to provide an \"easy to use\" interface without taking away the user's ability to do things at a lower level.</p>\n\n<p>To me, this would give you the most testability and maintainability, without placing constraints on the how someone else could use the code (and still provide an easy interface as well).</p>\n\n<p>Of course, that is just my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T10:31:42.833", "Id": "43881", "Score": "0", "body": "Well, the use of a static `$login` might indeed prove to be a drawback in time, but a static `$app`? These are _\"services\"_ or _\"helpers\"_, that the application will be using in order for it to get data via the API. The Application cannot run without having the `$config` set, and I can inject the application instance once, set it statically and use it everywhere, can't I. That way, if multiple logins come into play, there still is no issue" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T11:46:43.653", "Id": "43883", "Score": "0", "body": "PS: You talk about dependency injection, but at the same time admit to using Singletons in PHP... Sorry if I'm being obtuse here, but that doesn't make sense IMO" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:04:08.827", "Id": "44166", "Score": "0", "body": "@EliasVanOotegem - To your first comment -- yes and no, in my opinion. While you \"can\" inject everything into a single container which everything references, this leaves no flexibility without complicating your classes. Take, for example, a second configuration or login -- this would require you to now add special code to your classes for determining which \"set\" of information to use. It would be better to allow this information to be passed, which abstracts away the environmental \"choices\" and allows the classes to focus only on accomplishing their tasks. (continued...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:07:21.280", "Id": "44169", "Score": "0", "body": "I know you're probably typing the rest of your reply ATM, but I should point out that the config object is structured in such a way that each component has only accesses a subset of the entire config, based on the abstract class (using its namespace, instance name and task: `app.helpers.db.user_db.login=\"userlogin\"` and so on) so adding new login data for a specific class is doddle, the constructor and init functions take care of that for me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:14:59.597", "Id": "44172", "Score": "1", "body": "To me, there is also nothing wrong with having a `$app` to accomplish bootstrapping and create a facade for your underlying structures. The difference is in passing the `$app` to your individual components and having them make their own choices as to what to do with this larger structure, rather than limiting their responsibilities to solely accomplishing the tasks for which they are intended. Now -- maybe you are using additional patterns within your `$app` which limit this, but I'm just giving my opinion on why I wouldn't approach it that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:22:42.157", "Id": "44174", "Score": "0", "body": "Well, you've got a point there. I wasn't all too clear about this, but the way the `$app` instance is passed about is indeed restricted. I'm using a double service layer. Whereas one service links the application to the business logic, the other is a sort-of service locator that manages the communication between the actual service (and application) and the various helpers and mappers. Based on what part of the application, I pre-set a subset of the config on the instance, prior to setting the app reference, for example. In some cases I can't and for those cases, I'd use that static app ref." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:55:28.947", "Id": "44176", "Score": "0", "body": "To your 2nd comment, Singletons and dependency injection are not mutually exclusive, in my opinion, even though others may disagree. You can't argue with someone who thinks THEIR method of using a hammer is the only way one should EVER drive a nail. To me, overuse, misuse and poor implementation doesn't make a pattern bad, it makes the \"bad\" implementations bad. While I agree that the need for Singletons is rare and that there are always ways to \"get around\" the use of the Singleton Pattern, that doesn't mean the alternative is always the best solution. Just my 2 cents, my friend." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T15:09:13.713", "Id": "44177", "Score": "0", "body": "Your comment, 2nd above, sounds like a lot of complication, which may just be terminology, but it sounds like there is a significant amount of intermingling between your individual classes, the overarching application, configuration and individual service layers/components/helpers/etc. Like I said, \"sounds\" that way -- it may not be. For me, if I have more than a couple dependencies on other classes, need objects within other objects within other objects, or need more than a couple words to explain other classes in order to explain what my class does, I look at whether I need to refactor." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:49:33.070", "Id": "28090", "ParentId": "28074", "Score": "2" } } ]
{ "AcceptedAnswerId": "28090", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T10:48:54.243", "Id": "28074", "Score": "4", "Tags": [ "php", "static" ], "Title": "A decent use-case for static property" }
28074
<p>I have a site were we sell unique items. When a user clicks to buy an item we have to reserve it. This prevents other buyers from purchasing the item while the first buyer is checking out.</p> <p>When a buyer clicks the "Buy" button, he is redirected to the orders controller. The orders controller executes the following steps:</p> <ol> <li>Verify item is available (not reserved, or sold). <ol> <li>If available, the item is marked as reserved, and its <code>id</code> is stored in the session.</li> <li>If no, check if it is reserved, and if the current session has the item id (meaning the current user has made the reservation). If both conditions are true the buyer can complete his purchase. Otherwise, the buyer notified and presented with alternatives.</li> </ol></li> <li>If buyer navigates away from the orders controller, the item is released back to the catalogue.</li> </ol> <p>Are there any obvious pitfalls in my approach?</p> <p>I have reservations about using the session to indicate the current user has reserved an item. Users don't have to register to check out. </p> <p>I also feel like I'm repeating myself with <code>@item.reserve!</code>, the <code>reserve!</code> in <code>item_reserver.rb</code>.</p> <p>Thoughts? Feedback?</p> <p>application_controller.rb</p> <pre><code>include ItemReservation before_action :release_item </code></pre> <p>items_controller.rb</p> <pre><code># ensures item is available before_action :verify_item_is_available, only: :show </code></pre> <p>orders_controller.rb</p> <pre><code># ensures item is available before_action :verify_item_is_available, only: [:new, :create] def new reserve! @item @order = Order.new end </code></pre> <p>controllers/concerns/item_reserver.rb</p> <pre><code># before filter def verify_item_is_available unless @item.available? redirect_to similar_item_path(@item) unless @item.reserved? &amp;&amp; session[:reserved_item_id] == @item.id end end # before filter def release_item if session[:reserved_item_id].present? &amp;&amp; controller_name != 'orders' release! session[:reserved_item_id] end end def reserve!(item) if item.available? session[:reserved_item_id] = item.id if item.reserve! end end def release!(item_id) item = Item.find(item_id) if item.reserved? session[:reserved_item_id] = nil if item.release! end end </code></pre> <p>item.rb</p> <pre><code> def reserve! update!(availability: 'reserved') end def release! update!(availability: 'available') end def purchase! update!(availability: 'sold') end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T15:25:56.957", "Id": "43800", "Score": "0", "body": "Don't know much about ruby, but what happens if the customer does a reservation and doesn't go further with the purchase ? This is typically a [semaphore design pattern](http://en.wikipedia.org/wiki/Semaphore_(programming)) problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:26:53.437", "Id": "43820", "Score": "0", "body": "If he navigates away from the orders controller, the `release_item` filter is trigger. This makes `item.availability = 'available'` and clears `item.id` from the user session." } ]
[ { "body": "<p>If you are looking for pitfalls or errors that could happen depending of the different cases you can have, I strongly recommend writing some specs.</p>\n\n<p>Otherwise, the code looks good to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T16:18:22.667", "Id": "28135", "ParentId": "28077", "Score": "1" } }, { "body": "<p>Placing locks is inherently fragile, especially on a website. HTTP is stateless, and a user could walk away or close the browser at any time, leaving a lock in place forever.</p>\n\n<p>I would create a table of Lock objects, where each Lock refers to an item, states the quantity, and most importantly has a creation timestamp. Locks that are too old can easily be purged or ignored.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T10:28:35.293", "Id": "30910", "ParentId": "28077", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T13:35:16.687", "Id": "28077", "Score": "1", "Tags": [ "ruby", "locking" ], "Title": "Is this a good way of handling item reservations?" }
28077
<p><strong>Overarching Problem</strong></p> <p>I am creating a threadsafe queue that will act as a shared buffer between two threads for a game I am developing. I need it to be threadsafe so that one thread can throw messages into the queue, and second thread can take them out for processing in real time. I have decided in order to really learn about concurrency and threading I would like to create my own threading library with the required synchronization structures(starting off with a mutex that is implemented as a spinlock). For now I am using the Poco Threading library in order to test and develop my mutex. I will move forward to creating a Windows/Linux threading environment after I have my basic synchronization structures.</p> <p><strong>Proposed Solution (mutex/spinlock)</strong></p> <p><strong>Note:</strong> Sender and Receiver do not actually do any sending or receiving, or any queue work, they are just simply operating on numbers in tight for-loops to simulate work. I did not want to add extra variables to the test before I verified that my mutex implementation was working as expected.</p> <p><strong>Mutex.hpp</strong></p> <pre><code>#ifdef WIN32 #include &lt;Windows.h&gt; #define TARG_PLATFORM_WINDOWS #else #include &lt;unistd.h&gt; #define TARG_PLATFORM_LINUX #endif //Constant values const int MUTEX_LOCKED = 1; const int MUTEX_UNLOCKED = 0; class Mutex { private: volatile unsigned long long interlock; public: Mutex(); ~Mutex(); void lock(); void unlock(); }; </code></pre> <p><strong>Mutex.cpp</strong></p> <pre><code>#include "Mutex.hpp" Mutex::Mutex() { interlock = 0; } Mutex::~Mutex() { } void Mutex::lock() { #ifdef TARG_PLATFORM_WINDOWS while(this-&gt;interlock == 1 || InterlockedCompareExchange(&amp;this-&gt;interlock, 1, 0) == 1); #endif #ifdef TARG_PLATFORM_LINUX while(this-&gt;interlock == 1 || __sync_lock_test_and_set(&amp;this-&gt;interlock, 1) == 1); #endif } void Mutex::unlock() { this-&gt;interlock = 0; #ifdef TARG_PLATFORM_WINDOWS #endif #ifdef TARG_PLATFORM_LINUX #endif } </code></pre> <p><strong>Testing code</strong> Note: For easy reading I simply included one threads test code. The other thread has the exact same code except it is the "Receiver" and it only simply locks and unlocks no <code>sleep()</code> is called in thread 2. This should make it so they are both in similar starting areas when the work begins. Basically I am trying to make each thread do some work and then unlock the mutex to allow the other thread to do some work.</p> <pre><code>virtual void run() { int table[2000000]; std::cout&lt;&lt;"Thread1 Started"&lt;&lt;std::endl; mutex-&gt;lock(); sleep(3) //Allow threads to both catch up to eacother mutex-&gt;unlock(); mutex-&gt;lock(); for(int i = 0; i &lt; 2000000; i++) { table[i] = i/2; } std::cout&lt;&lt;"Sender block 1 done"&lt;&lt;std::endl; mutex-&gt;unlock(); mutex-&gt;lock(); for(int i = 0; i &lt; 2000000; i++) { table[i] = i/2; } std::cout&lt;&lt;"Senderblock 2 done"&lt;&lt;std::endl; mutex-&gt;unlock(); mutex-&gt;lock(); for(int i = 0; i &lt; 2000000; i++) { table[i] = i/2; } std::cout&lt;&lt;"Sender block 3 done"&lt;&lt;std::endl; mutex-&gt;unlock(); //dequeue a msg } </code></pre> <p><strong>My Concerns</strong></p> <p>When I run the test, the threads seem to execute in order and not taking turns:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Thread1 started Thread2 started Sender Block 1 done Sender block 3 done Sender block 2 done Receiver block 2 done Receiver Block 1 done Receiver block 3 done </code></pre> </blockquote> <p>I thought thread 2 would be able to acquire the lock before thread 1 could <code>unlock()</code> and <code>lock()</code> the mutex again. For the sake of testing I added a sleep for 100 milliseconds in the <code>unlock()</code> function in order to give the other thread time to acquire the lock. This worked and they alternated with the following output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Thread1 started Thread2 started Sender Block 1 done Receiver Block 1 done Sender block 2 done Receiver block 2 done Sender block 3 done Receiver block 3 done </code></pre> </blockquote> <p>It seems that the re-locking is too fast for the threads to take turns and I am concerned this may starve thread2 in a real application. But I do not want a sleep() in the unlock() function as this is a huge performance hit and causes context switching.</p> <p>I did some reading and some people did performance tests of locking and relocking their mutex object so I tried the same for mine. It took 8-10 milliseconds for it to lock and unlcok 1 million times in a tight for loop. This seems to fast compared to other things I have read. Perhaps I am missing something?</p> <p><strong>Ultimate Questions</strong></p> <p>Should I be using a different type of lock? Is something off with my Mutex implementation? Is something invalidating the test I have written? If so what kind of test would you recommend?</p> <p><strong>Note</strong> I know this seems kind of like a Stack Overflow question but I figured since I had a solution and I wanted more of a review and possible suggestions on a solution that involves modifying code already written, this would be a better place for the question.</p>
[]
[ { "body": "<p>A mutex just protects against concurrent access but does not control what order things will happen in. That has more to do with the thread scheduling algorithm.</p>\n\n<p>As far as the UNIX implementation is concerned, a thread that finds the mutex locked will busy-loop waiting for it to be free. This is very wasteful of CPU time. A better approach is to suspend the calling thread until the mutex is free. You would perhaps be better using POSIX threads, which will do that for you. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:33:23.520", "Id": "43822", "Score": "0", "body": "I like the idea and I plan on building on top of both Pthreads and win32 threads. But it seems like what you are suggesting would require use of signals (so I know when the mutex is free). I am okay with it spinning for now. It is not a huge deal performance-wise currently. If it does get to be a big deal I can always go back and add complexity(e.g. extra code for signal-like behavior) to up the performance.\n\nI just want to make sure both threads are able to enqueue and dequeue their data as needed with no starvation. I guess I will put together a full test with Queues to see if its an issue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:12:41.300", "Id": "43839", "Score": "0", "body": "There is no need for signals. `pthread_mutex_lock` will return once the lock has been obtained, suspending the thread in the meantime. You might also want to look at using condition variables with mutexes to coordinate writers and readers of your queue (eg `pthread_cond_wait`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:46:43.513", "Id": "43842", "Score": "1", "body": "I guess I am mixing up my thought process between high and lower level stuff. I need to settle on one level and implement from there. In my case I was wanting to implement something like the function pthread_mutex_lock itself. If I were to look underneath this abstraction there must be some sort of callback, interrupt, or signal happening for it to obtain a lock. If its suspended it has to be woken up properly to avoid spinning.\nRegardless, Linux and Windows both have sufficient locks and Thread API's. I will just wrap a framework around them and implement higher level abstractions. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:47:15.360", "Id": "43843", "Score": "0", "body": "Also, +1 and +Checkmark in a few days if no other answers come along." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:13:16.857", "Id": "28087", "ParentId": "28083", "Score": "4" } }, { "body": "<p>@William Morris mentioned the spinning on a lock issue (busy wait). This is a real problem that you should address.</p>\n\n<p>Empty block at the end of while is non obvious to read.<br>\nYou should comment on it so that people don't think it is a mistake:</p>\n\n<pre><code>while(this-&gt;interlock == 1 || InterlockedCompareExchange(&amp;this-&gt;interlock, 1, 0) == 1);\n\n// I would do:\n\nwhile(this-&gt;interlock == 1 || InterlockedCompareExchange(&amp;this-&gt;interlock, 1, 0) == 1)\n{ /* Do Nothing. While we wait to get the lock */\n}\n</code></pre>\n\n<p>Your lock is not exception safe:<br>\nUse RAII to guarantee that locks are correctly locked/unlocked in the presence of exceptions:</p>\n\n<pre><code>class Mutex\n{\n private:\n volatile unsigned long long interlock;\n public:\n Mutex();\n ~Mutex();\n private:\n // These should be private to prevent locks being obtained\n // in a way that makes them exception unsafe.\n void lock();\n void unlock();\n\n // Need a friend that can lock and unlock the Mutex safely and correctly.\n friend class Locker;\n};\n\nclass Locker\n{\n Mutex&amp; m;\n public:\n Locker(Mutex&amp; m): m(m) {m.lock();}\n ~Locker() {m.unlock();}\n};\n\n// Usage\nint main()\n{\n Mutex m;\n for(;;)\n {\n Locker lock(m); // Locks the mutex (and gurantees it will be released)\n // Even if there is an exception\n }\n}\n</code></pre>\n\n<p>There are more than two types of platform.<br>\nYou should make sure these are covered. If the code does not fall into a particular type then you should generate an error: <a href=\"http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system\">http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system</a></p>\n\n<pre><code>#if defined(WIN32)\n #include &lt;Windows.h&gt;\n #define TARG_PLATFORM_WINDOWS\n#elif defined(__unix)\n #include &lt;unistd.h&gt;\n #define TARG_PLATFORM_LINUX\n#else\n // Fail if this is a system you have not compensated for:\n #error \"Unknown System Type\"\n#endif\n</code></pre>\n\n<p>Don't put conditional code into functions:</p>\n\n<pre><code>void Mutex::unlock()\n{\n this-&gt;interlock = 0;\n #ifdef TARG_PLATFORM_WINDOWS\n #endif\n #ifdef TARG_PLATFORM_LINUX\n #endif\n\n}\n</code></pre>\n\n<p>You should define macros based on your conditional tags in the header file. Use the macros in your code. This should make it clear what you are trying to achieve.</p>\n\n<pre><code>void Mutex::unlock()\n{\n this-&gt;interlock = 0;\n UNLOCK_MY_MUTEX(interlock);\n}\n</code></pre>\n\n<p>Then in the header file:</p>\n\n<pre><code> #ifdef TARG_PLATFORM_WINDOWS\n #define UNLOCK_MY_MUTEX(x) WindowsUnlockCode(x)\n #endif\n #ifdef TARG_PLATFORM_LINUX\n #define UNLOCK_MY_MUTEX(x) /* Nothing required */ do {} while(false)\n // see http://codereview.stackexchange.com/a/1686/507\n #endif\n</code></pre>\n\n<p>You better have a good reason fir using a pointer:</p>\n\n<pre><code>mutex-&gt;lock();\n</code></pre>\n\n<p>Final Note:</p>\n\n<p>Use an already implemented locking mechanism rather than rolling your own.</p>\n\n<pre><code>pthread_mutex // Valid on Windows and Unix (if you get the libraries).\n\nboost::spinlock // http://www.boost.org/doc/libs/1_38_0/boost/detail/spinlock.hpp\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T02:56:16.537", "Id": "44006", "Score": "0", "body": "Awesome answer. I like the level of detail presented for everything. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T21:30:33.713", "Id": "28103", "ParentId": "28083", "Score": "8" } }, { "body": "<p>This answer is a bit late but I felt there were a few oversights that should be mentioned.</p>\n\n<p>@William Morris is quite correct about the spinlock. You will find that this is an unacceptable way to implement a critical low level function that you would want to base the environment of your project. Some platforms do supply a type of spinlock but even those will put the thread to sleep.</p>\n\n<p>@Loki Astari is also quite correct about using the native mutex libraries for your platform.</p>\n\n<p>These are the issues I see with your code.</p>\n\n<ol>\n<li><p>\"unsigned long long\" Never ever use this. It is a MS/Windows type for an unsigned 64 bit integer. It is not cross-platform. It's \"unsigned long\" on some and I've used systems where it's 128 bit to undefined. On one system you can cast a negative value (-1) and do a compare and on the other you can't because the sign extension will be different.</p></li>\n<li><p>Your example is not thread safe at all. Any thread can call the unlock whether they locked it first or not.</p></li>\n<li><p>Your example does not handle recursion. This is an essential mutex type. Subroutines may need to work on data and cannot assume they were not called from a process that either did or did not call the lock.</p></li>\n</ol>\n\n<p>To create your own mutex class to be used in a real world project such as your game, it is going to need to support most of the same functionality of existing libraries. Your mutex needs to store the ID of the locking thread, and lock count if it's recursive.</p>\n\n<p>Another thing about your spinlock and why it's more than a bad idea. Your assumption is that the other thread holds the mutex and it will eventually free it while you spin wait. That is a big assumption. For that to work, you must be running on a multi-core CPU and your other thread must be assigned to a different core or your busy wait will spin forever starving the other thread from processing. Depending on the OS, it may time slice multithreading or it may be cooperative. And lastly, you say you're planning on putting this in a game. Most games these days don't have spare CPU cycles they can afford to burn and run some of the most time critical code there is.</p>\n\n<p>In addition to recommending using the native libraries for each system. I would also recommend that you spend some time learning the quirks of each and create your own cross platform class based on them. Your goal of having a cross-platform class is still a very good idea. In your shoes, I would want to make as much of the code as platform agnostic as is reasonable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-18T03:44:19.703", "Id": "63219", "ParentId": "28083", "Score": "5" } } ]
{ "AcceptedAnswerId": "28103", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T14:29:43.097", "Id": "28083", "Score": "7", "Tags": [ "c++", "multithreading", "concurrency" ], "Title": "Mutex implementation" }
28083
<p>I'm still learning Android, I need to have a spinner and for it to display a list of string values. However, when I submit that data later on I need a corresponding integer value. Similarly to how a HTML Select uses <code>&lt;option value="2"&gt;BlahBlah&lt;/option&gt;</code>.</p> <p>From searching I've come up with a method which works, just wondering if anyone had any suggestions for improving the code?</p> <p>I've got the two variables setup:</p> <pre><code>private String[] arrMuppetNames = {"Kermit","Gonzo","Fuzzy","Animal"}; HashMap&lt;String, Integer&gt; hashMuppets = new HashMap&lt;String, Integer&gt;(); </code></pre> <p><code>hashMuppets</code> is built up with a simple set of "Kermit":1,"Gonzo":2 etc. Then to stop the code running on load I've added a <code>"--please select--"</code> to index 0.</p> <pre><code>//Add "please select" to spinner arrNewArray[0] = this.getString(R.string.muppet_select); for(int i=0; i &lt; arrMuppets.length; i++){ arrNewArray[i+1] = arrMuppets[i]; } </code></pre> <p>Obviously I add this array <code>arrNewArray</code> to the spinner using <code>ArrayAdapter</code>. Then use the <code>OnItemSelectedListener</code>.</p> <pre><code>private Spinner.OnItemSelectedListener spinnerListener = new Spinner.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView&lt;?&gt; arg0, View arg1,int arg2, long arg3) { Spinner spinner = (Spinner) findViewById(R.id.muppet_spinner); //Arg 3 is selected index. Lets ensure we didn't select our "Please select" if(arg3 != 0){ //Get Selected Item and convert to corresponding value using hashMap String strSelectedMuppet = spinner.getSelectedItem().toString(); int intCatID = hashMuppets.get(strSelectedMuppet); //Show toast of value Toast.makeText(getApplicationContext(), String.valueOf(intCatID), Toast.LENGTH_SHORT).show(); } } @Override public void onNothingSelected(AdapterView&lt;?&gt; arg0) { //Do nothing } }; </code></pre> <p>If anyone has any suggestions or pointers I'd very much appreciate it. I'm happy to post the full code if you'd like, but I'm hoping the above short example is pretty self explanatory.</p> <p>Thanks</p>
[]
[ { "body": "<p>As long as you are hard-coding the values, I would go with an <code>enum</code></p>\n\n<pre><code>public enum Muppets {\n Kermit, Gonzo, Fozzie, Animal, Swedish_Chef, Miss_Piggy,\n Statler, Waldorf, Beaker, Beauregard, Dr_Benson_Honeydew,\n Crazy_Harry, Rowlf, Dr_Teeth, Zoot, Janice, Floyd;\n // Sorry, I just thought your list of muppets was way too short\n\n public int getNumber() {\n return this.ordinal() + 1;\n }\n @Override\n public String toString() {\n return super.toString().replaceAll(\"_\", \" \");\n }\n}\n</code></pre>\n\n<p>(To make things easier for you, you can also add your <code>Please Select</code> as a muppet and override the <code>toString</code> method to return a custom string if <code>this == PLEASE_SELECT</code>, this would also remove the need for adding one in <code>getNumber</code>, and would greatly simplify adding the items to the adapter)</p>\n\n<p>Then I would use the <code>ArrayAdapter</code> as <code>ArrayAdapter&lt;Muppet&gt;</code>, so that you can get the selected item like this:</p>\n\n<pre><code>Muppet selectedMuppet = spinner.getSelectedItem();\nint value = selectedMuppet.getNumber();\n</code></pre>\n\n<p>To get an array of all the muppet enums, use <code>Muppets.values()</code>.</p>\n\n<p>If you want the possibility to add muppets dynamically at run-time, I would make a <code>List&lt;String&gt;</code> and get the position of an item using <code>list.indexOf(muppetName)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T20:35:27.957", "Id": "36075", "ParentId": "28089", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T16:49:20.643", "Id": "28089", "Score": "2", "Tags": [ "java", "android" ], "Title": "Using a spinner like a HTML select to display string but return int value" }
28089
<p>I don't really have experience in factoring. My code is really long, i don't use functions because i don't know if it needs to be a function. I hope you could give me tips so i could clean up my code.</p> <pre><code>&lt;?php # Required files include("simple-html-dom.php"); require("{$_SERVER['DOCUMENT_ROOT']}/config/pipeline-x.php"); # Define variables $fn = urlencode($_REQUEST['fn']); $ln = urlencode($_REQUEST['ln']); # Connect to database $db = new px_dbasei(); $db-&gt;connect("192.168.50.70", "****", "****", "piasdgeline_tesh45t"); # Query database if a record exist $sql = "SELECT * FROM linkedin_parse " ."WHERE " ."`first_name` = '{$fn}' AND " ."`last_name` = '{$ln}' "; $results = $db-&gt;query($sql); # If there is no result if($results-&gt;num_rows == 0): # Search linkedin and download page $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.linkedin.com/pub/dir/?first={$fn}&amp;last={$ln}&amp;search=Search"); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_TIMEOUT, 8); $res = curl_exec($ch); curl_close($ch); $html = str_get_html($res); # Parse records from the download page foreach($html-&gt;find('li.vcard') as $vcard): $table = array(); foreach($vcard-&gt;find('span.given-name') as $given_name): $table['first_name'] = (trim(addslashes($given_name-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('span.family-name') as $family_name): $table['last_name'] = (trim(addslashes($family_name-&gt;plaintext)," ")); endforeach; foreach($vcard-&gt;find('span.location') as $location): $table['location'] = (trim(addslashes($location-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('span.industry') as $industry): $table['industry'] = (trim(addslashes($industry-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('dd.current-content') as $headline): $table['headline'] = (trim(addslashes($headline-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('a.btn-primary') as $url): $table['url'] = addslashes($url-&gt;href); endforeach; # Insert generated results to the database $sql = "INSERT INTO linkedin_parse (`first_name`,`last_name`,`location`,`industry`,`headline`,`url`) " ."VALUES " ."('{$table['first_name']}'," ."'{$table['last_name']}'," ."'{$table['location']}'," ."'{$table['industry']}'," ."'{$table['headline']}'," ."'{$table['url']}')"; $db-&gt;query($sql); # Get last insert id and query database again $new_id = $db-&gt;insert_id(); $sql2 = "SELECT * FROM linkedin_parse WHERE `linkedin_parse_id` = '{$new_id}'"; $result = $db-&gt;query($sql2); # Display results in HTML ?&gt; &lt;ol&gt; &lt;?php while($row = $result-&gt;fetch_assoc()): ?&gt; &lt;li class="vcard"&gt; &lt;span class="given-name"&gt;&lt;?php echo $row['first_name'] ?&gt;&lt;/span&gt; &lt;span class="family-name"&gt;&lt;?php echo $row['last_name'] ?&gt;&lt;/span&gt; &lt;span class="location"&gt;&lt;?php echo $row['location'] ?&gt;&lt;/span&gt; &lt;span class="industry"&gt;&lt;?php echo $row['industry'] ?&gt;&lt;/span&gt; &lt;dd class="current-content"&gt; &lt;span&gt;&lt;?php echo $row['headline'] ?&gt;&lt;/span&gt; &lt;/dd&gt; &lt;a href="&lt;?php echo $row['url'] ?&gt;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ol&gt; &lt;?php endforeach; else: # Query database if record is 30 days old $sql = "SELECT * FROM linkedin_parse " ."WHERE " ."`first_name` = '{$fn}' AND" ."`last_name` = '{$ln}' AND" ."`date_inserted` &gt;= DATE_SUB(NOW(), INTERVAL 30 DAY)"; $results = $db-&gt;query($sql); if($results-&gt;num_rows != 0): # Retrieve from database $sql = "SELECT * FROM linkedin_parse " ."WHERE " ."`first_name` = '{$fn}' AND" ."`last_name` = '{$ln}' "; $result = $db-&gt;query($sql); # Display results in HTML ?&gt; &lt;ol&gt; &lt;?php while($row = $result-&gt;fetch_assoc()): ?&gt; &lt;li class="vcard"&gt; &lt;span class="given-name"&gt;&lt;?php echo $row['first_name'] ?&gt;&lt;/span&gt; &lt;span class="family-name"&gt;&lt;?php echo $row['last_name'] ?&gt;&lt;/span&gt; &lt;span class="location"&gt;&lt;?php echo $row['location'] ?&gt;&lt;/span&gt; &lt;span class="industry"&gt;&lt;?php echo $row['industry'] ?&gt;&lt;/span&gt; &lt;dd class="current-content"&gt; &lt;span&gt;&lt;?php echo $row['headline'] ?&gt;&lt;/span&gt; &lt;/dd&gt; &lt;a href="&lt;?php echo $row['url'] ?&gt;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ol&gt; &lt;?php else: # Search linked-in for updated records $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.linkedin.com/pub/dir/?first={$fn}&amp;last={$ln}&amp;search=Search"); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); curl_setopt($ch, CURLOPT_TIMEOUT, 8); $res = curl_exec($ch); curl_close($ch); $html = str_get_html($res); # Parse records from the download page foreach($html-&gt;find('li.vcard') as $vcard): $table = array(); foreach($vcard-&gt;find('span.given-name') as $given_name): $table['first_name'] = (trim(addslashes($given_name-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('span.family-name') as $family_name): $table['last_name'] = (trim(addslashes($family_name-&gt;plaintext)," ")); endforeach; foreach($vcard-&gt;find('span.location') as $location): $table['location'] = (trim(addslashes($location-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('span.industry') as $industry): $table['industry'] = (trim(addslashes($industry-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('dd.current-content') as $headline): $table['headline'] = (trim(addslashes($headline-&gt;plaintext), " ")); endforeach; foreach($vcard-&gt;find('a.btn-primary') as $url): $table['url'] = addslashes($url-&gt;href); endforeach; # Update records $sql = "UPDATE linkedin_parse " ."SET " ."`date_inserted` = now()," ."`first_name` = '{$table['first_name']}'," ."`last_name` = '{$table['last_name']}', " ."`location` = '{$table['location']}', " ."`industry` = '{$table['industry']}', " ."`headline` = '{$table['headline']}', " ."`url` = '{$table['url']}' " ."WHERE " ."`first_name` = '{$table['first_name']}' AND" ."`last_name` = '{$table['last_name']}' AND " ."`location` = '{$table['location']}' "; $result = $db-&gt;query($sql); ?&gt; &lt;ol&gt; &lt;?php while($row = $result-&gt;fetch_assoc()): ?&gt; &lt;li class="vcard"&gt; &lt;span class="given-name"&gt;&lt;?php echo $row['given-name'] ?&gt;&lt;/span&gt; &lt;span class="family-name"&gt;&lt;?php echo $row['family-name'] ?&gt;&lt;/span&gt; &lt;span class="location"&gt;&lt;?php echo $row['location'] ?&gt;&lt;/span&gt; &lt;span class="industry"&gt;&lt;?php echo $row['industry'] ?&gt;&lt;/span&gt; &lt;dd class="current-content"&gt; &lt;span&gt;&lt;?php echo $row['headline'] ?&gt;&lt;/span&gt; &lt;/dd&gt; &lt;a href="&lt;?php echo $row['url'] ?&gt;"&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ol&gt; &lt;?php endforeach; endif; endif; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:39:39.433", "Id": "43823", "Score": "0", "body": "[Link to on hold StackOverflow Question](http://stackoverflow.com/questions/17434610/refactoring-tips/17435597?noredirect=1#comment25356744_17435597) -- I will add my answer here for others to consider as well, in case they may wish to improve it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T12:29:41.357", "Id": "43886", "Score": "0", "body": "You appear to loop through a returned page, assigning every occurrence of given-name to first_name. Each time you do this you will over write the previous one, so you will only have the last one. You then insert all these last found fields into linkedin_parse, but that will only insert a single record, returning the id field. You then select everything from that table for that row id. As there is only a single record and you already have all the details in the script there seems to be no point to this select." } ]
[ { "body": "<p>As a general concept, I would recommend a few things: </p>\n\n<ul>\n<li>\"DRY\" or \"Don't Repeat Yourself\" is a good concept to start with, as others have mentioned. If you do something more than once, chances are that it deserves its own function or can be simplified.</li>\n<li>While typically applied to object-oriented programming, the \"single responsibility principle\" can be well applied to functions for their maintainability, but you should also avoid creating functions just because you can (function calls require overhead). Eventually, collections of functions often end up in reusable classes.</li>\n<li>\"KISS\" or \"Keep it simple, stupid\" (note: this is better looked at as a self-referencing \"stupid\", like when someone says, \"I'm such an idiot!\" when they figure something out) -- Simplify your logic and code whenever you can. <em>\"The simplest explanation is usually the correct one.\"</em></li>\n</ul>\n\n<p>To apply these concepts, here is how I would re-structure (<em>not how I would write</em>) your script:</p>\n\n<ol>\n<li>Query whether any profiles match that are less that 30 days old, since you are updating the profiles when none exist or all are more than 30 days old.</li>\n<li>If you didn't return any rows: \n<ul>\n<li>Query whether any profiles match at all, to determine updates vs inserts.</li>\n<li>Download and parse the page.</li>\n<li>Save the new/updated records.</li>\n<li>Keep the matches you parsed, rather than downloading from the database what you just inserted/updated.</li>\n</ul></li>\n<li>Finally, display your matches (regardless of whether they came from database or parsing).</li>\n</ol>\n\n<p>By restructuring your code this way:</p>\n\n<ul>\n<li>You eliminate most of the duplication and potential confusion</li>\n<li>You simplify your codepath</li>\n<li>You group your logical components (search, parse/store if necessary, display)</li>\n<li>All of your HTML can be placed at the end of your script, which is more readable (or can be easily placed in a separate file)</li>\n<li>The places where a function will make sense will be more apparent, such as your parsing loops.</li>\n</ul>\n\n<p>Last note -- you should place an emphasis on security whenever you process data from an \"unknown source\" (user, website, provided file, etc.). While <code>addslashes()</code> and <code>urlencode()</code> are a nice idea, there are a number of resources that can help you understand how to avoid SQL Injection, cross-site scripting and other potential threats. An example of a risk in your code is the use of $_REQUEST without escaping your database query. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:47:08.127", "Id": "43824", "Score": "0", "body": "Sir jacob, im currently doing this script. On number. I already made an if statement that if there no rows return then perform an INSERT, else UPDATE. Now on download/parse, how would i construct my function for it?." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:56:32.823", "Id": "43830", "Score": "0", "body": "I would start by writing a single function that could be called during parsing for each array of items, which would return an array of (items[item]->plaintext) including any processing you wish to do, rather than multiple \"foreach\" loops. Then just continue simplifying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T18:10:29.863", "Id": "43832", "Score": "0", "body": "This is my new script currently not yet finished, just up until the parsing occurs.\nhttp://pastebin.com/Lkkpc3kx --- Now my problem is the function on parsing. This is what it looks like now, but when i print_r($table) it doesn't return something, even though i put a return $table=array() on the function here http://pastebin.com/GMG9FfFS" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:45:21.790", "Id": "43841", "Score": "0", "body": "@AjVillalobos -- Unfortunately, Code Review is not the correct location for your continued questions. In addition, many of your issues seem to be from a lack of understanding of the PHP language. I recommend that you spend additional time learning PHP, rather than hoping that the StackExchange community will eventually write and debug your code. Good luck!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:40:24.110", "Id": "28094", "ParentId": "28091", "Score": "2" } } ]
{ "AcceptedAnswerId": "28094", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:06:26.547", "Id": "28091", "Score": "0", "Tags": [ "php", "mysql" ], "Title": "Refactoring tips" }
28091
<p>Battleship.py</p> <pre><code># -*- coding: utf-8 -*- import numpy import operator import commands import random import sys import os from time import sleep from grid import grid from fleet import fleet def setupNavy(setupSelection,gridClass,sortedShipList): used="no" shipCoordList=[] for shipData in sortedShipList: shipName=shipData[0] shipSize=shipData[1] if setupSelection=="manual": header= "Ship placement: %s size is: %s\n"%(shipName,shipSize) sys.stdout.write(header) con="yes" while con=="yes": if setupSelection=="manual": start=raw_input("Enter start point: ") else: randomX=random.randrange(0,gridClass.xGridSize) randomY=random.randrange(0,gridClass.yGridSize) xLetter=gridClass.alphDict[randomX] start="%s%d"%(xLetter,randomY) coordStatus=gridClass.checkDataPointValue(start) if coordStatus=="E": con="no" if setupSelection=="manual": placement=raw_input("Place Vertical (V) or Horizontal (H): ") else: placement=random.choice("VH") end=gridClass.determineEndPoint(start,shipSize,placement) if end=="F": if setupSelection=="manual": error= "Datapoint: %s will place %s off the grid \n"% (start,shipName) sys.stdout.write(error) used="yes" else: shipCoordList=gridClass.determineFullLocation(start,end) gridClass.shipLocationDict[shipName]=shipCoordList for coord in shipCoordList: coordList=coord.split(',') dataPoint="%s%s"%(gridClass.alphDict[int(coordList[0])],coordList[1]) coordStatus=gridClass.checkDataPointValue(dataPoint) if coordStatus=='T': if setupSelection=="manual": error= "Datapoint: %s is already used \n"% dataPoint sys.stdout.write(error) used="yes" if used=="no": gridClass.gridValuesUsed+=shipCoordList else: if setupSelection=="manual": error= "Datapoint: %s is already used \n"% dataPoint sys.stdout.write(error) con="yes" if used=="yes": con="yes" used="no" os.system('clear') gridClass.shipPlacement(start,end,shipCoordList) gridDict=gridClass.populateGrid() if setupSelection=="manual": gridClass.displayGrid() sleep(0.25) os.system('clear') return def attackShip(whosTurn,attackerGridClass,defenderGridClass,defenderFleetClass): newAttack="Y" numShipsInFleet=len(defenderFleetClass.shipStatusDict) while newAttack=="Y": if whosTurn=="player": attackCoords=raw_input("Input attack coordinates: ") xLetter=attackCoords[:1] xValue=int((ord(xLetter)%32)-1) yValue=int(attackCoords[1:]) startLocation="%s,%s"%(xValue,yValue) else: if len(attackerGridClass.attackList)!=0: startLocation=random.choice(attackerGridClass.attackList) sList=startLocation.split(',') start="%s%s"%(attackerGridClass.alphDict[int(sList[0])],sList[1]) end='' else: if len(attackerGridClass.searchList)&gt;0: startLocation=random.choice(attackerGridClass.searchList) else: startLocation=random.choice(attackerGridClass.validPoints) xyList=startLocation.split(',') x=int(xyList[0]) y=int(xyList[1]) start="%s%s"%(attackerGridClass.alphDict[x],y) if startLocation in attackerGridClass.validPoints: attackerGridClass.validPoints.remove(startLocation) startList=startLocation.split(',') xValue=int(startList[0]) yValue=int(startList[1]) if startLocation in attackerGridClass.attackList: attackerGridClass.attackList.remove(startLocation) if startLocation not in attackerGridClass.hitList and startLocation not in attackerGridClass.missedList: newAttack="N" print "Attacking at %s (%s)"%(start,startLocation) sleep(.75) if startLocation in defenderGridClass.gridValuesUsed: print "BOOM!! Direct Hit" sleep(1.25) os.system('clear') #hit='■' hit='×' defenderHit='×' #Displays when a enemys ship is hit. attackerGridClass.gridValuesAttacked[xValue][yValue]="[%s]"%hit #Displays when a ship is hit. shows and x in the place of the ship defenderGridClass.gridValues[xValue][yValue]="[%s]"%defenderHit attackerGridClass.hitList.append(startLocation) for ship, locationList in defenderGridClass.shipLocationDict.iteritems(): hitsTaken=0 shipSize=defenderFleetClass.shipFleetDict[ship] if defenderFleetClass.shipStatusDict[ship]=="active": for location in locationList: if location in attackerGridClass.hitList: hitsTaken+=1 if hitsTaken==shipSize: print "%s sunk a %s"%(whosTurn,ship) sleep(1.25) defenderFleetClass.shipStatusDict[ship]="sunk" defenderFleetClass.numberSunkShips+=1 shipsLeft=numShipsInFleet-defenderFleetClass.numberSunkShips attackerGridClass.hitList.append(startLocation) if startLocation in attackerGridClass.attackList: attackerGridClass.attackList.remove(startLocation) left=x-1 below=y-1 right=x+1 above=y+1 if left&gt;=0: leftValue="%s,%s"%(left,y) leftLetter="%s%s"%(attackerGridClass.alphDict[left],y) if leftValue not in attackerGridClass.attackList and leftLetter not in attackerGridClass.hitList and leftLetter not in attackerGridClass.missedList: attackerGridClass.attackList.append(leftValue) if below&gt;=1 or below==1: belowValue="%s,%s"%(x,below) belowLetter="%s%s"%(attackerGridClass.alphDict[x],below) if belowValue not in attackerGridClass.attackList and belowLetter not in attackerGridClass.hitList and belowLetter not in attackerGridClass.missedList: attackerGridClass.attackList.append(belowValue) if right&lt;=(defenderGridClass.xGridSize-1): rightValue="%s,%s"%(right,y) rightLetter="%s%s"%(attackerGridClass.alphDict[right],y) if rightValue not in attackerGridClass.attackList and rightLetter not in attackerGridClass.hitList and rightLetter not in attackerGridClass.missedList: attackerGridClass.attackList.append(rightValue) if above&lt;=(defenderGridClass.yGridSize-1) or above==defenderGridClass.yGridSize-1: aboveValue="%s,%s"%(x,above) aboveLetter="%s%s"%(attackerGridClass.alphDict[x],above) if aboveValue not in attackerGridClass.attackList and aboveLetter not in attackerGridClass.hitList and aboveLetter not in attackerGridClass.missedList: attackerGridClass.attackList.append(aboveValue) else: attackerGridClass.missedList.append(startLocation) print "Missed %s %s" % (start,startLocation) sleep(1.25) os.system('clear') attackResult="[M]" #miss='Ø' miss='ø' attackResult="[%s]"%miss #attackResult="[M]" attackerGridClass.gridValuesAttacked[xValue][yValue]="[%s]"%miss attackerGridClass.missedList.append(startLocation) if startLocation in attackerGridClass.attackList: attackerGridClass.attackList.remove(startLocation) else: hitOrMiss="Miss" if startLocation in attackerGridClass.hitList:hitOrMiss="HIT" if whosTurn=="player": print "You already attacked %s%d which was a %s "%(xLetter,yValue,hitOrMiss) if defenderFleetClass.numberSunkShips==numShipsInFleet: gameOver(attackerGridClass.gridName) displayGameStats() sys.exit() return return def determineMaxMoves(xGrid,yGrid,player): i=0;turnList=[] maxTurns=(xGrid*yGrid)*2 while i &lt; maxTurns: if i%2==0: #turnList.append('player') turnList.append(player) else: turnList.append('Joshua') i+=1 return turnList def gameOver(winner): if winner=="USA": print "\n******** %s WINS******** \n" %winner #print u'{:─^10}'.format(u'') print """ ____________________________________________ |* * * * * * * * * * |_______________________| |* * * * * * * * * * |_______________________| |* * * * * * * * * * |_______________________| |* * * * * * * * * * |_______________________| |* * * * * * * * * * |_______________________| |____________________________________________| |____________________________________________| |____________________________________________| |____________________________________________| |____________________________________________| """ else: print "Better luck next time.. %s WINS \n" %winner print "GAME OVER" def displayGameStats(): print " Results \n" print "Number of attacks: %s"%enemyGridClass.attackCounter print "\n" print "%s BATTLEFIELD"% enemyGridClass.gridName enemyGridClass.populateGrid() enemyGridClass.displayGrid() print "\n" for shipName,shipStatus in enemyFleetClass.shipStatusDict.iteritems(): print shipName,shipStatus print "\n" """ print "Hits \n" for coord in enemyGridClass.hitList: coordList=coord.split(',') dataPoint="%s%s"%(enemyGridClass.alphDict[int(coordList[1])],coordList[0]) print "%s " % dataPoint """ #for coord in enemyGridClass.missedList: # coordList=coord.split(',') # dataPoint="%s%s"%(gridClass.alphDict[int(coordList[1])],coordList[0]) # print "Missed: %s " % dataPoint print "%s BATTLEFIELD"% myGridClass.gridName myGridClass.populateGrid() myGridClass.displayGrid() print "\n" for shipName,shipStatus in myFleetClass.shipStatusDict.iteritems(): print shipName,shipStatus print "\n" """ print "Hits \n" for coord in myGridClass.hitList: coordList=coord.split(',') dataPoint="%s%s"%(myGridClass.alphDict[int(coordList[1])],coordList[0]) print "HIt: %s " % dataPoint """ def displayMessage(msg): for letter in msg: sys.stdout.write(letter) sys.stdout.flush() sleep(.085) ####################### #Display welcome message user=commands.getoutput("whoami") msg= "Greetings %s my name is Joshua.. Shall we play a game? " % user displayMessage(msg) playGame=raw_input("Y or N ") if playGame.upper()=="Y": msg="Number of players 0 or 1" displayMessage(msg) numberOfPlayers=int(raw_input(" ")) if numberOfPlayers==0: player="Professor Flakner" else: player=user msg="How about Global Thermonuclear War?......" displayMessage(msg) sleep(2.0) msg="My apologies.\nThat game has been removed from my system. Lets play BattleShip\n\n" displayMessage(msg) countryList=['China','Russia','SouthKorea','India','France','Mexico','Taiwan','Turkey','NorthKorea'] if numberOfPlayers==1: msg="Which country would you like to play?\n" displayMessage(msg) for country in countryList: msg="%s \n"%country displayMessage(msg) enemy=raw_input(": ") msg="Very well.\n" msg="Please be patient as battle tatics and anaylsis are loaded\n" displayMessage(msg) for i in range(21): sys.stdout.write('\r') sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i)) sys.stdout.flush() sleep(0.25) print "\n\n" else: msg="A Strange Game.\nThe only winning move is not to play..\nHow about a nice game of chess.." displayMessage(msg) sys.exit() gridSelection=raw_input("Would you like to define the size of of the grid ('Y' or 'N')? " ) if gridSelection.upper()=="Y": inputValuesValid="False" while inputValuesValid=="False": gridSize=int(raw_input("Input size of X and Y axis (Min:6 Max:26)? " )) if gridSize &lt;6: print "Biggest ship is 6 units.. Will not fit on grid." if gridSize &gt;26: print "Nah dude..Max x and y xis size is 26 " if gridSize &gt;6 or gridSize &lt;= 26: inputValuesValid="True";xGrid=gridSize;yGrid=gridSize else: xGrid=10 yGrid=10 myGridClass=grid('USA',xGrid,yGrid) if numberOfPlayers==0: enemyGridClass=grid(random.choice(countryList),xGrid,yGrid) else: enemyGridClass=grid(enemy,xGrid,yGrid) turnList=determineMaxMoves(xGrid,yGrid,player) myFleetClass=fleet() enemyFleetClass=fleet() #Set up grid values enemyGridValues=enemyGridClass.gridValues myGridValues=myGridClass.gridValues #Sort our ships by size. sortedShipList=sorted(myFleetClass.shipFleetDict.iteritems(), key=operator.itemgetter(1),reverse=True) #populate Computer/enemy grid setupNavy('random',enemyGridClass,sortedShipList) enemyGridClass.populateGrid() #setup the layout of our ships #print "\n %s has declared war!!\n\n" %enemyGridClass.gridName if numberOfPlayers==1: choiceForSetup=raw_input("Would you like to manually place your ships ('Y' or 'N')?" ) else: choiceForSetup="N" if choiceForSetup.upper()=='Y': #display empty grid myGridClass.populateGrid() myGridClass.displayGrid() setupNavy('manual',myGridClass,sortedShipList) myGridClass.populateGrid() else: setup='Y' while setup=="Y": setupNavy('random',myGridClass,sortedShipList) myGridClass.populateGrid() myGridClass.displayGrid() if numberOfPlayers==1: con=raw_input("Are you satisfied with your location of your ships ('Y' or 'N')? ") else: con="Y" if con.upper()=="Y": setup="N" else: myGridClass.gridValuesUsed=[] myGridValues=myGridClass.resetGridValues() for whosTurn in turnList: print "\n\n%s turn"%whosTurn if whosTurn!="Joshua": if int(numberOfPlayers) ==1: whosTurn='player' attackShip(whosTurn,myGridClass,enemyGridClass,enemyFleetClass) myGridClass.attackCounter+=1 else: attackShip(whosTurn,enemyGridClass,myGridClass,myFleetClass) enemyGridClass.attackCounter+=1 print "\n MY BATTLEFIELD" myGridClass.populateGrid() myGridClass.displayGrid() print "\n MY ATTACKS" myGridClass.populateEnemyGrid() myGridClass.displayEnemyGrid() </code></pre> <p>Fleet.py</p> <pre><code>class fleet: def __init__(self): #List of current ships of the United States Navy #Ship name | Size #-------------------------------------- #airCraftCarrier 6 #battleShip 5 #submarine 4 #cruiser 3 #destroyer 2 self.shipFleetDict={'airCraftCarrier':6, 'battleship':5, 'submarine':4, 'cruiser':3, 'destroyer':2} self.shipStatusDict={'airCraftCarrier':'active', 'battleship':'active', 'submarine':'active', 'cruiser':'active', 'destroyer':'active'} self.numberSunkShips=0 </code></pre> <p>grid.py</p> <pre><code>import sys class grid: def __init__(self,name,xSize,ySize): self.gridName =name self.attackCounter=0 self.hitList=[] self.missedList=[] self.gridValuesUsed=[] self.attackList=[] self.displayGridDict={} self.displayEnemyGridDict={} self.shipLocationDict={} self.xGridSize=xSize self.yGridSize=ySize self.gridValues=[ [ '[ ]' for i in range(self.yGridSize) ] for j in range(self.xGridSize) ] self.gridValuesAttacked=[ [ '[ ]' for i in range(self.yGridSize) ] for j in range(self.xGridSize) ] self.validPoints=self.defineValidPoints() self.alphList=map(chr, range(65, 91)) #create a list A-Z self.alphDict=self.generateDict() self.searchList=self.defineSearchList() def defineSearchList(self): searchList=[];start=0 z=0 row=1 for item in self.validPoints: if row%2==1 and z%2==0: searchList.append(item) if row%2==0 and (z-self.xGridSize)%2==1: searchList.append(item) if z%((self.xGridSize*row)-1)==0 and z&gt;0: row+=1 z+=1 return searchList def defineValidPoints(self): validPoints=[] x=0 while x &lt; self.xGridSize: y=0 while y &lt; self.yGridSize: validPoints.append("%s,%s"%(x,y)) y+=1 x+=1 return validPoints def generateDict(self): alphDict={} i=0 for i in range(0, len(self.alphList)): alphDict[(ord(self.alphList[i])%32)-1] = self.alphList[i] return alphDict def resetGridValues(self): self.gridValues=[ [ '[ ]' for i in range(self.yGridSize) ] for j in range(self.xGridSize) ] return self.gridValues def checkDataPointValue(self,dataPoint): xValue=dataPoint[:1] yValue=int(dataPoint[1:]) xValue=int((ord(xValue)%32)-1) coords="%s,%s"%(xValue,yValue) if coords in self.gridValuesUsed: return "T" else: return "E" def determineEndPoint(self,start,size,placement): x=start[:1] y=start[1:] if placement.upper()=='V': yEnd=(int(y)+size)-1 if yEnd &gt; self.yGridSize-1: return "F" endPoint="%s%s"%(x,str(yEnd)) else: xValueNumber=(ord(x)%32)-1 xEnd=xValueNumber+size-1 if xEnd &gt; self.xGridSize-1: return "F" endPoint="%s%s"%(self.alphList[xEnd],y) return endPoint def determineFullLocation(self,start,end): xValueStart=start[:1] yValueStart=int(start[1:]) xValueEnd=end[:1] yValueEnd=int(end[1:]) shipCoordList=[] if xValueStart==xValueEnd: #placing vertical xValueNumber=(ord(xValueStart)%32)-1 i=yValueStart while i &lt;= yValueEnd: #shipCoordList.append('%s,%s'%(i,xValueNumber)) shipCoordList.append('%s,%s'%(xValueNumber,i)) i+=1 else: xValueStart=(ord(xValueStart)%32)-1 xValueEnd=(ord(xValueEnd)%32)-1 i=xValueStart while i &lt;= xValueEnd: #shipCoordList.append('%s,%s'%(yValueStart,i)) shipCoordList.append('%s,%s'%(i,yValueStart)) i+=1 return shipCoordList def shipPlacement(self,start,end,shipCoordList): xValueStart=start[:1] xValueEnd=end[:1] #block='█' block='■' if xValueStart==xValueEnd: #placing vertical for coord in shipCoordList: coordList=coord.split(',') #yValue=int((ord(coordList[0])%32)-1) xValue=int(coordList[0]) yValue=int(coordList[1]) displayVal="[%s]"%block #displayVal="[*]" self.gridValues[xValue][yValue]=displayVal else: #placing horizontal i=1 size=len(shipCoordList) for coord in shipCoordList: coordList=coord.split(',') xValue=int(coordList[0]) yValue=int(coordList[1]) if i ==1: #displayVal="[* " displayVal="[%s "%block elif i==size: #displayVal=" *]" displayVal=" %s]"%block else: #displayVal=" * " displayVal=" %s "%block self.gridValues[xValue][yValue]=displayVal i+=1 return def populateGrid(self): y=0 #gridDict={} numElements=len(self.gridValues) while y &lt; self.yGridSize: values=[] x=0 while x &lt; self.xGridSize: values.append(self.gridValues[x][y]) x+=1 #YGRID if numElements&gt;9: yDisplay="%02d" % (y,) self.displayGridDict[yDisplay]=values else: self.displayGridDict[y]=values values=[] y+=1 return def displayGrid(self): row=0 header="" numElements= len(self.displayGridDict) x=0 while x&lt;numElements: header+="[%s]"%self.alphList[x] x+=1 numElements=len(self.displayGridDict) for key in sorted(self.displayGridDict.iterkeys()): value=self.displayGridDict[key] if row==0: if numElements&gt;9: displayStr=" %s\n"%(header) else: displayStr=" %s\n"%(header) sys.stdout.write(displayStr) displayStr="" displayStr+="%s"%key for cell in value: displayStr+="%s"%cell displayStr+="\n" sys.stdout.write(displayStr) displayStr="" row+=1 def populateEnemyGrid(self): y=0 #gridDict={} numElements=len(self.gridValuesAttacked) while y &lt; self.yGridSize: values=[] x=0 while x &lt; self.xGridSize: values.append(self.gridValuesAttacked[x][y]) x+=1 if numElements&gt;9: yDisplay="%02d" % (y,) self.displayEnemyGridDict[yDisplay]=values else: self.displayEnemyGridDict[y]=values values=[] y+=1 return def displayEnemyGrid(self): row=0 header="" numElements= len(self.displayEnemyGridDict) x=0 while x&lt;numElements: header+="[%s]"%self.alphList[x] x+=1 numElements=len(self.displayEnemyGridDict) for key in sorted(self.displayEnemyGridDict.iterkeys()): value=self.displayEnemyGridDict[key] if row==0: if numElements&gt;9: displayStr=" %s\n"%(header) else: displayStr=" %s\n"%(header) sys.stdout.write(displayStr) displayStr="" displayStr+="%s"%key for cell in value: displayStr+="%s"%cell displayStr+="\n" sys.stdout.write(displayStr) displayStr="" row+=1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-07T01:11:09.393", "Id": "190029", "Score": "0", "body": "I have rolled back Rev 2. Please see *[What to do when someone answers](http://codereview.stackexchange.com/help/someone-answers)*." } ]
[ { "body": "<ul>\n<li><p>Get rid of magic numbers and magic strings (see also second point).</p></li>\n<li><p>Use relevant types (and not just strings).</p></li>\n</ul>\n\n<p>If you want to have a variable with two different status (yes/no, true/false, active/sunk, etc), it would probably make sense to use booleans.</p>\n\n<p>If you want to have a variable with a limited number of different values, you might want to use something better than string (you could <a href=\"https://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python\">use or emulate enums</a>).</p>\n\n<ul>\n<li>Organise your code in a better way.</li>\n</ul>\n\n<p>You've started to create classes which is probably a good idea. However, I am not quite sure that it makes sense to make things that complicated. Also, the dependency between the different parts of the code suggest that the definition is not as good as it could be.</p>\n\n<p>I might be missing something but things could be pretty simple :</p>\n\n<p>A game is a list of players and the record of the player who is supposed to play.</p>\n\n<p>A player is just a name, a type of user (bot or player) and a board</p>\n\n<p>A board is just a table of cells.</p>\n\n<p>Each cell contains two pieces of information : what it contains (airCraftCarrier, battleship, submarine, cruiser, destroyer or water) and whether is has been bombed.</p>\n\n<p>As most of these concepts are basically just container with no or little logic, it might or might not make sense to use classes for them. This is up to you.</p>\n\n<ul>\n<li>Don't repeat yourself.</li>\n</ul>\n\n<p>Whenever you are writing the same piece of code twice, you are punishing your future self. If one of them needs to be updated, the other will need to be too which is going to be boring in the best case, forgotten and lead to weird bugs in the worst case. </p>\n\n<ul>\n<li>Let's do things in a pythonic way</li>\n</ul>\n\n<p>You've written :</p>\n\n<pre><code>i=0;turnList=[]\nmaxTurns=(xGrid*yGrid)*2\nwhile i &lt; maxTurns:\n if i%2==0:\n #turnList.append('player')\n turnList.append(player)\n else:\n turnList.append('Joshua')\n i+=1\nreturn turnList\n</code></pre>\n\n<p>which becomes, after using <code>range</code> (or <code>xrange</code>), removing useless parenthesis useless comments and useless variables and using the ternary operator (which is a good way to remove duplicated code) :</p>\n\n<pre><code>turnList=[]\nfor i in range(xGrid*yGrid*2):\n turnList.append('Joshua' if i%2 else player) \nreturn turnList\n</code></pre>\n\n<p>which now looks like a good candidate for list comprehension :</p>\n\n<pre><code>return [('Joshua' if i%2 else player) for i in range(xGrid*yGrid*2)]\n</code></pre>\n\n<p>The same kind of idea applies to :</p>\n\n<pre><code> validPoints=[]\n x=0\n while x &lt; self.xGridSize:\n y=0\n while y &lt; self.yGridSize:\n validPoints.append(\"%s,%s\"%(x,y))\n y+=1\n x+=1\n return validPoints\n</code></pre>\n\n<p>becomes :</p>\n\n<pre><code> validPoints=[]\n for x in range(self.xGridSize): \n for y in range(self.yGridSize):\n validPoints.append(\"%s,%s\"%(x,y))\n return validPoints\n</code></pre>\n\n<p>and could then be transformed with list comprehension. However, I'd like to point out that this method : 1) probably shouldn't be doing the string conversion itself 2) doesn't seem that useful.</p>\n\n<p>I don't have more time to continue but I guess that's already a good amount of comments to start with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T21:43:11.047", "Id": "28104", "ParentId": "28092", "Score": "1" } } ]
{ "AcceptedAnswerId": "28104", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T17:06:58.427", "Id": "28092", "Score": "1", "Tags": [ "python", "game", "console" ], "Title": "Battleship game written in python" }
28092
<p>This is working now, but it looks very inelegant. I'm sure there is a nicer way of doing this.</p> <pre><code># Get the outliers of both the dates and values maxDate = [] minDate = [] maxVal = [] minVal = [] for k, v of series for d, i in v series[k][i][1] = nearZero if d[1] is 0 series[k] = v = _.filter v, (d) -&gt; not _.isNull d[1] maxDate.push _.max v, (d) -&gt; d[0] minDate.push _.min v, (d) -&gt; d[0] maxVal .push _.max v, (d) -&gt; d[1] minVal .push _.min v, (d) -&gt; d[1] maxDate = _.max _.map maxDate, (d) -&gt; d[0] minDate = _.min _.map minDate, (d) -&gt; d[0] maxVal = _.max _.map maxVal, (d) -&gt; d[1] minVal = _.min _.map minVal, (d) -&gt; d[1] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T21:01:52.583", "Id": "43929", "Score": "0", "body": "It would be good for people to test if you could add example values for `series` and `nearZero`." } ]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li><p>I know many programmers like it, but this kind of perfectly aligned code looks pretty weird to me. Maybe my problem is that it's usually a sign that there is a repeated pattern that could be abstracted but has been prettified instead.</p></li>\n<li><p><code>maxDate = []</code>. Using imperative programming in JS/CS is very common, indeed, but I'd definitely take a functional approach when doing maths or logic (not that I know of any coding that does <em>not</em> deal with maths or logic ;-)).</p></li>\n<li><p><code>(d) -&gt; d[0]</code>: Note that you can de-structure arrays: <code>([x, y]) -&gt; x</code>.</p></li>\n<li><p><code>_.map maxDate, (d) -&gt; d[0]</code>. In my opinion list-comprehensions are more declarative than maps that use lambdas: <code>(d[0] for d in maxDate)</code>.</p></li>\n<li><p>Don't reuse variables: Those 4 accumulators hold two completely different structures in the course of the computation, that's not a good practice. Not even in imperative programming.</p></li>\n</ul>\n\n<p>As I said, I'd write it in functional style, inmutable variables all the way through. It's a pity that CS has no <em>real</em> list-comprehensions and the results of nested loops must be flattened, but we'll have to live with it (<code>_.flatten(xs, true)</code> comes in handy as a one-level flattener). It would look something like this (you say you really need the modified series, so I'll use <code>mash</code> from my <a href=\"https://gist.github.com/1222480\" rel=\"nofollow\">mixin</a>):</p>\n\n<pre><code>nested_date_value_pairs =\n for key, pairs of series\n for [date, val] in pairs when val isnt null\n [date, if val is 0 then nearZero else val]\nmodified_series = _.mash(_.zip(_.keys(series), nested_date_value_pairs)) \ndates_values = _.zip(_.flatten(nested_date_value_pairs, true)...)\n[[minDate, maxDate], [minVal, maxVal]] = ([_.min(xs), _.max(xs)] for xs in dates_values)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T16:31:29.680", "Id": "44182", "Score": "0", "body": "The only problem I have with this is that `series` does not get altered in your version. Its an unfortunately needed side-effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T19:24:00.730", "Id": "44197", "Score": "0", "body": "@Fresheyeball: In-place updated aren't compulsory, you can always create a new object. Is a bit harder? yes, but the algorithm is saner. Updated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T22:17:16.990", "Id": "44206", "Score": "0", "body": "Thank you @tokland. Your coffee knowledge is formidably idomatic!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T21:40:22.403", "Id": "28150", "ParentId": "28097", "Score": "4" } }, { "body": "<p>For the max/min part of the problem, a solution using list comprehensions might be:</p>\n\n<pre><code>foo1 = (fn, i) -&gt;\n # apply fn to i'th term of nested pairs\n fn((fn(x[i] for x in v) for k, v of series))\n\n[maxDate, minDate, maxVal, minVal] = \n [foo1(_.max, 0), foo1(_.min, 0), foo1(_.max, 1), foo1(_.min, 1)]\n</code></pre>\n\n<p>or without underscore</p>\n\n<pre><code>foo2 = (fn, i) -&gt;\n fn((fn((x[i] for x in v)...) for k, v of series)...)\nconsole.log (foo2(fn, i) for fn in [Math.max, Math.min] for i in [0,1])\n</code></pre>\n\n<p>Another with chaining:</p>\n\n<pre><code>wseries = _(series)\nfoo4 = (i)-&gt;\n wseries.map((v)-&gt;_.map(v,i)).flatten().value()\n\n[[maxDate, minDate], [maxVal, minVal]] = \n (fn(foo4(i)) for fn in [_.max, _.min] for i in [0,1])\n</code></pre>\n\n<p>These were tested with:</p>\n\n<pre><code>series = {\n 1: [[0, .5],[4, -.1]],\n 2: [[1, .4]],\n 3: [[2, .2],[0, 0],[3, .7]]\n}\nnearZero = 0.1\n</code></pre>\n\n<p>producing</p>\n\n<pre><code>[ [ 4, 0 ], [ 0.7, -0.1 ] ]\n</code></pre>\n\n<p>for the initial filtering task, this appeals to my sense of aesthetics:</p>\n\n<pre><code>bar = (x)-&gt;\n [x[0], (if x[1] is 0 then nearZero else x[1])]\nfor k, v of series\n v = (bar(x) for x in v when x[1]!=null)\n series[k] = v\n</code></pre>\n\n<p>though with large dimensions, and sparse changes I can imagine being more selective about changing v.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-28T23:18:27.143", "Id": "29098", "ParentId": "28097", "Score": "2" } } ]
{ "AcceptedAnswerId": "28150", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T19:15:26.603", "Id": "28097", "Score": "3", "Tags": [ "javascript", "datetime", "coffeescript" ], "Title": "Getting the outliers of both dates and values" }
28097
<p>For my application, I was using <code>array_diff_assoc</code>, when I noticed it was returning the wrong value. I was using multidimensional arrays, therefore I needed a <code>array_diff_assoc_recursive</code> method.</p> <p>I Googled around and found a few, but they all only took 2 parameters. The official <code>array_diff_assoc</code> can take an infinite number of params. I wanted mine to, so I wrote my own <code>array_diff_assoc_recursive</code> function.</p> <pre><code>&lt;?php class Tools{ /** * Recursive version of array_diff_assoc * Returns everything from $a that is not in $b or the other arguments * * @param $a The array to compare from * @param $b An array to compare against * @param ... More arrays to compare against * * @return An array with everything from $a that not in $b or the others */ public static function array_diff_assoc_recursive($a, $b){ // Get all of the "compare against" arrays $b = array_slice(func_get_args(), 1); // Initial return value $ret = array(); // Loop over the "to" array and compare with the others foreach($a as $key=&gt;$val){ // We should compare type first $aType = gettype($val); // If it's an array, we recurse, otherwise we just compare with "===" $args = $aType === 'array' ? array($val) : true; // Let's see what we have to compare to foreach($b as $x){ // If the key doesn't exist or the type is different, // then it's different, and our work here is done if(!array_key_exists($key, $x) || $aType !== gettype($x[$key])){ $ret[$key] = $val; continue 2; } // If we are working with arrays, then we recurse if($aType === 'array'){ $args[] = $x[$key]; } // Otherwise we just compare else{ $args = $args &amp;&amp; $val === $x[$key]; } } // This is where we call ourselves with all of the arrays we got passed if($aType === 'array'){ $comp = call_user_func_array(array(get_called_class(), 'array_diff_assoc_recursive'), $args); // An empty array means we are equal :-) if(count($comp) &gt; 0){ $ret[$key] = $comp; } } // If the values don't match, then we found a difference elseif(!$args){ $ret[$key] = $val; } } return $ret; } } </code></pre> <p>I was wondering what you thought of my attempt. It seems to work ok for my application, and in the few tests I tried with it.</p> <p>DEMO: <a href="http://ideone.com/5GZ8Tn" rel="nofollow">http://ideone.com/5GZ8Tn</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T14:04:39.140", "Id": "485023", "Score": "1", "body": "Please clarify your expected result from this demo: https://3v4l.org/E3Nol What qualifies as a \"difference\"? Is it a diff if one subsequent array is missing/mismatching a respective value? Is it is a diff only if all of the respective values are missing or a mismatch?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T15:37:57.037", "Id": "485027", "Score": "0", "body": "@mickmackusa Oh! You seemed to have broken my code :-P That's clearly a case I didn't consider. This question is 7 years old, and I don't even remember why I needed a `array_diff_assoc_recursive` method. I don't think I am still working on the project that this was used in. Though, as you've shown the code does need a bit of work to do what it's supposed to do. Maybe if I am bored later, I can try to fix it. Whatever I was using this for, it seemed to be ok there, but I don't remember exactly what this was being used for :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:07:46.810", "Id": "485061", "Score": "1", "body": "_You_ don't necessarily need to fix it. This is a fun thought exercise. Just tell me the intended behaviour/outcome. I spent a few hours yesterday refining your static method and implementing some modern techniques ...and only discovered the issue when testing my code. It was only at that point that I tested your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T15:01:22.670", "Id": "485171", "Score": "0", "body": "@mickmackusa I guess the intended outcome would be whatever the official `array_diff_assoc` does, but then digs into arrays and compares individual elements using the same `array_diff_assoc` logic..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T17:43:57.317", "Id": "485529", "Score": "0", "body": "The docs for `array_diff_assoc` say \"the values from array1 that are not present in any of the other arrays.\" So, if it finds the value in any of the comparative arrays, it's removed from the first array. With my `array_diff_assoc_recursive` method if it sees an array as a value, it calls itself again. I'd think that your data should just be `[8,10]`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T20:22:07.667", "Id": "485537", "Score": "0", "body": "Excellent. I'll go for that then." } ]
[ { "body": "<p>The logic looks good but I would like to suggest a few tips to enhance readability and maintainability of your code.</p>\n\n<p><strong>First off</strong>: name your variables accordingly <code>$a</code> doesn't say anything to any random person when reading the code. He will have to scroll up and down figuring out what is what.</p>\n\n<p><strong>Second</strong>: Split your function into multiple methods. This will enhance readability and will keep an overview of your code. Now you have one very large method which will take a random person at least half an hour to figure out what it all does exactly.</p>\n\n<p><strong>Third</strong>: Try to avoid things like <code>continue 2;</code>, <code>break;</code> and more. They don't mean anything when you read code and can be avoided in most cases.</p>\n\n<p><strong>Fourth</strong>: Comments rot very quickly! Try and make sure that your methods are selfexplanatory so that you dont need to put comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-14T22:40:38.073", "Id": "121494", "Score": "1", "body": "Suggestion 2 is good and makes suggestion 1 less important. Suggestion 3 is wrong - however you can use a break variable and check for it instead.. may be friendlier on the eye for people who can't see the level control your code used. Suggestion 4 is valid, sadly, but still put comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T10:12:03.703", "Id": "28546", "ParentId": "28098", "Score": "4" } } ]
{ "AcceptedAnswerId": "28546", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T20:00:00.997", "Id": "28098", "Score": "2", "Tags": [ "php", "array", "recursion" ], "Title": "Pure PHP array_diff_assoc_recursive function" }
28098
<p>I have this class that I've been working on for the past 2 or 3 days, now it's working I just want to know what you think about it, what other methods should I add, are the basic security checks impplemented correctly? etc etc</p> <pre><code> /* * * Author: Carlos Arturo Alaniz * Contact info: caag1993@gmail.com; @alaniz93; caag1993.wordpress.com * Last Modified date: 06 /03 /2013 * * Description: * This class replaces the standard php session managment system * it uses a Mysql Database to stor the session info * * The data encryopptuion can be turned off by passing a NULL encription * key, the cookies and session can be set to be permanent by passing a * true value to the start session method. * * It requieres a PDO object to stablish the connection to the DB * it also implements 2 very basic security checks to prevent session * related attacks * it store the SERVER_USER_AGENT with every newly opened session to be * later compared, it also stores a cookie counter on the client side and * session counter on the server side both of them must be syncronized * the data its encrypted with a private key and it sets the php.ini * file to a secure configuration. * */ class _session { private $key = NULL; private $permanent = FALSE; private $lifetime = 0; public function __construct(&amp;$connecion_settings, $key = NULL) { $this-&gt;key = $key; $this-&gt;pdo = $connecion_settings; //set our new session handler session_set_save_handler( array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc') ); //Set php.in to secure setting. //This will tell PHP not to include the identifier in the URL, and not to read the URL for identifiers. if (ini_get('session.use_trans_sid')) ini_set('session.use_trans_sid', 0); //This will tell PHP to never use URLs with session identifiers. if (!ini_get('session.use_only_cookies')) ini_set('session.use_only_cookies', 1); //Using a strong session hash identifier //PHP &lt;= 5.3 // ini_set('session.hash_function', 1); // PHP &gt; 5.3 ini_set('session.hash_function', 'sha256'); // Send a strong hash ini_set('session.hash_bits_per_character', 5); } public function start_session($sessionName = NULL, $permanent = FALSE) { if ($permanent) { $this-&gt;permanent = $permanent; $this-&gt;lifetime = time() + 86400 * 365 * 2; //2 years session_set_cookie_params($this-&gt;lifetime); } if ($sessionName != NULL) session_name($sessionName); session_start(); if (!isset($_SESSION['_userAgent'])) $_SESSION['_userAgent'] = $_SERVER['HTTP_USER_AGENT']; if (!isset($_SESSION['_counter'])) { $_SESSION['_counter'] = 0; setcookie("sessionCounter", "", time() - 7200); //unset cookie setcookie('sessionCounter', 0, $this-&gt;lifetime, '/', NULL, NULL, 1); } } private function updateCounter() { $cookieCount = $_COOKIE['sessionCounter'] + 1; $_SESSION['_counter'] += 1; setcookie("sessionCounter", "", time() - 7200); //unset cookie setcookie('sessionCounter', $cookieCount, $this-&gt;lifetime, '/', NULL, NULL, 1); //set new value } /* //This function implements some basic sessions security checks //it checks for anychange in the user agent variable and the one stored in the session //it implements a counter on the server side and one on the client side //both of them must be the same. */ public function securityCheck() { $this-&gt;updateCounter(); if (($_SESSION['_userAgent'] != $_SERVER['HTTP_USER_AGENT']) || ($_SESSION['_counter'] != ($_COOKIE['sessionCounter'] + 1)) ) { session_destroy(); session_write_close(); //Prompt for password or do something //echo "DUH!"; } // else // echo "wereGood"; } public function open() { //This should be a contructor but the connection 'open' //settings are in the $connetion variable return 0; } public function close() { return session_write_close(); } public function read($sessionId) { $qry = "SELECT data FROM sessions WHERE id = :id"; //We want to only prepare the statement once if (!isset($this-&gt;rStatement)) { $this-&gt;rStatement = $this-&gt;pdo-&gt;prepare($qry); } $this-&gt;rStatement-&gt;bindParam(':id', $sessionId, PDO::PARAM_INT); if ($this-&gt;rStatement-&gt;execute()) { $row = $this-&gt;rStatement-&gt;fetch(PDO::FETCH_ASSOC); if ($this-&gt;key != NULL) return $this-&gt;decrypt($row['data']); else return $row['data']; } else { return false; } } public function write($sessionId, $data) { if ($this-&gt;key != NULL) $data = $this-&gt;encrypt($data); $qry = "REPLACE INTO sessions (id, set_time, data, permanent) VALUES (:id, :time, :data, :permanent)"; $time = time(); //We want to only prepare the statement once if (!isset($this-&gt;wStatement)) { $this-&gt;wStatement = $this-&gt;pdo-&gt;prepare($qry); } $this-&gt;wStatement-&gt;bindParam(':id', $sessionId, PDO::PARAM_STR); $this-&gt;wStatement-&gt;bindParam(':time', $time, PDO::PARAM_INT); $this-&gt;wStatement-&gt;bindParam(':data', $data, PDO::PARAM_STR); $this-&gt;wStatement-&gt;bindParam(':permanent', $this-&gt;permanent, PDO::PARAM_BOOL); if ($this-&gt;wStatement-&gt;execute()) { return true; } else { echo "error"; return false; } } public function destroy($sessionId) { $qry = "DELETE FROM sessions WHERE id = :id"; //We want to only prepare the statement once if (!isset($this-&gt;dStatement)) { $this-&gt;dStatement = $this-&gt;pdo-&gt;prepare($qry); } $this-&gt;dStatement-&gt;bindParam(':id', $sessionId, PDO::PARAM_INT); if ($this-&gt;dStatement-&gt;execute()) { unset($_SESSION); //unset session variables setcookie("sessionCounter", "sdf", time() - 7200); //unset cookie return true; } else { return false; } } public function gc($max) { $qry = "DELETE FROM sessions WHERE set_time &lt; :max AND permanent = 0"; //We want to only prepare the statement once if (!isset($this-&gt;gcStatement)) { $this-&gt;gcStatement = $this-&gt;pdo-&gt;prepare($qry); } $this-&gt;gcStatement-&gt;bindParam(':max', $max, PDO::PARAM_INT); if ($this-&gt;gcStatement-&gt;execute()) { return 'true'; } else { return false; } } private function encrypt($data) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $en = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this-&gt;key, $data, MCRYPT_MODE_ECB, $iv)); return $en; } private function decrypt($data) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $des = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this-&gt;key, base64_decode($data), MCRYPT_MODE_ECB, $iv); return $des; } } </code></pre> <p><a href="http://pastebin.com/JZ7tuLb0" rel="nofollow">http://pastebin.com/JZ7tuLb0</a></p>
[]
[ { "body": "<p>If you are using PHP >= 5.4, you can look at the <a href=\"http://php.net/manual/en/class.sessionhandlerinterface.php\" rel=\"nofollow\">SessionHandlerInterface</a>, which will allow you to interface and extend PHP's default session handling mechanism.</p>\n\n<p>Your code looks good, you are using PDO which is advisable. You may have to perform type hinting in the constructor on the PDO connection, so the class knows what to expect. Further, there is no benefit from passing the connection in by reference. You may want to declare <code>private $pdo = null;</code> as well. </p>\n\n<p>The script has some documentation in, however could benefit from DocBlocks. You may want to check that there unnecessary <code>echo</code> where a method is returning a boolean, and be careful in using <code>return 'true';</code> vs <code>return true;</code> - note that they are not the same. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T22:55:08.703", "Id": "43852", "Score": "0", "body": "thanks for the feedback, I'll clean the script a little bit more before implementing it, i've just adden a comment blokc in the top with a description. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T22:41:51.167", "Id": "28106", "ParentId": "28099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T20:08:47.733", "Id": "28099", "Score": "1", "Tags": [ "php", "sql", "security" ], "Title": "PHP/SQL session managment" }
28099
<p>Can this be optimized?</p> <pre><code>static internal Point3D[] _data; static internal Point3dTree _kd; static internal int _interpolation_count = 0; static internal int _iteration_count = 0; static Dictionary&lt;int, Point3D&gt; Interpolated_Values = new Dictionary&lt;int, Point3D&gt;(); static internal int _threasindex; static internal double[] _threasholds = new double[] { 0.5, 1.0, 1.5, 20.5 }; static internal double Interpolate(double x, double x0, double x1, double y0, double y1) { if ((x1 - x0) == 0) return (y0 + y1) / 2; return y0 + (x - x0) * (y1 - y0) / (x1 - x0); } static void Main(string[] args) { using (new ProceduralTimer("Loading data")) _data = LasReader.GetData(@"C:\WindowsLP\SAMPLE_PROJECT\brisport2\area_cov.las"); using (new ProceduralTimer("Bulding Kd tree")) _kd = new Point3dTree(_data, false); List&lt;Point3D&gt; InterpolatedData = _data.ToList(); _data = null; using (new ProceduralTimer("Processing")) { int i = 0; var neighbours = new List&lt;Point3D&gt;(); for (; i &lt; InterpolatedData.Count; i++) { @rescan: neighbours = _kd.NearestNeighbours(new KdTreeNode&lt;Point3D&gt;(InterpolatedData[i]), _threasholds[_threasindex % _threasholds.Length]); if (neighbours.Count &lt; 4 &amp;&amp; _threasindex &lt; _threasholds.Length) { _threasindex++; _iteration_count++; goto rescan; } else { if (neighbours.Count &gt;= 4) { double[] xvalues = neighbours.Select(_ =&gt; _.X).ToArray(); double[] yvalues = neighbours.Select(_ =&gt; _.Y).ToArray(); double[] zvalues = neighbours.Select(_ =&gt; _.Z).ToArray(); Point3D pt = new Point3D(); pt.X = Math.Round(Interpolate(InterpolatedData[i].X, xvalues[0], xvalues[1], xvalues[2], xvalues[3]), 2); pt.Y = Math.Round(Interpolate(InterpolatedData[i].Y, yvalues[0], yvalues[1], yvalues[2], yvalues[3]), 2); pt.Z = Math.Round(Interpolate(InterpolatedData[i].Z, zvalues[0], zvalues[1], zvalues[2], zvalues[3]), 2); Interpolated_Values[i] = pt; _interpolation_count++; } _threasindex = 0; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T01:35:14.210", "Id": "43858", "Score": "0", "body": "since your GOTO statement just points to the top of the for loop, replace it with `continue`..that is what it is for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T03:14:11.430", "Id": "43859", "Score": "1", "body": "@RobertSnyder: `continue` will increment `i`. The `goto` doesn't." } ]
[ { "body": "<p>Since you provide no description of your algorithm whatsoever, nor do you provide any implementation of classes you use, i take it you are sure that there is nothing left to optimize. Because normally if you feel that it works too slow, you should start by optimizing the algorithm itself and implementations of its basic calculations.\nBy optimizing this bit of code you provided, you will probably win some milliseconds in a long run, but this kind of micro optimization is not normally necessary. But oh well.</p>\n\n<ol>\n<li><p>In your <code>Interpolate</code> method you calculate x1 - x0 twice. This value can be assigned to local variable. (This is probably optimized anyway at some point of compilation, but better safe than sorry.)</p></li>\n<li><p><code>List&lt;Point3D&gt; InterpolatedData = _data.ToList();</code> -- What is <code>_data</code>? Is it an <code>IEnumerable&lt;T&gt;</code>? Is it possible to refactor <code>LasReader.GetData</code> so it returns <code>IList&lt;T&gt;</code> straight away, so there is no unnecessary copying from one collection to another?</p></li>\n<li><p>You should probably keep <code>goto</code> since it's quite fast, but again this is the kind of micro optimization one dont normally need. So for the sake of people who might read your code you could refactor it to an inner <code>while</code>loop.</p></li>\n<li><p><code>var neighbours = new List&lt;Point3D&gt;();</code> -- what is the point in this assignment? if you want to create an empty list in case <code>InterpolatedData.Count == 0</code> then wrap it in an <code>if</code> statement, otherwise you are wasting resources to create a List you dont really need.</p></li>\n<li><p>I see no reason to do this:</p>\n\n<pre><code>double[] xvalues = neighbours.Select(_ =&gt; _.X).ToArray();\ndouble[] yvalues = neighbours.Select(_ =&gt; _.Y).ToArray();\ndouble[] zvalues = neighbours.Select(_ =&gt; _.Z).ToArray();\n</code></pre>\n\n<p>Why copy? Why can't you simply access <code>neighbours[i].X</code>?</p></li>\n<li><p>it looks like there is clearly a room for some parallel calculations. <strong>That should be your main concern</strong>; that can give a real boost to speed. But without seeing full code, it's hard to tell the way to best implement multithreading into your calculations. So it is something for you to think about.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T06:44:01.527", "Id": "28114", "ParentId": "28107", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T00:04:09.653", "Id": "28107", "Score": "-4", "Tags": [ "c#", "algorithm" ], "Title": "Managing 3D point data" }
28107
<p>I'm a novice at Java and just beginning with Swing. I’m trying to figure out how to separate event logic from the presentation logic. Look at the following classes:</p> <p><strong>GUITest.java</strong></p> <pre><code>package guitest; import java.util.ArrayList; public class GuiTest { public static void main(String args[]) { new MainFrame2();} } </code></pre> <p><strong>MainFrame2.java</strong></p> <pre><code> package guitest; import javax.swing.*; import java.awt.event.*; public class MainFrame2 extends JFrame implements ActionListener{ JPanel pane = new JPanel(); JButton butt = new JButton("Push Me"); JTextArea ta = new JTextArea("Push Me"); int i = 0; MainFrame2(){ super("My GUITest"); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(1000,100,500,500); //From upper left corner (right, down, width, height) this.add(pane); pane.setLayout(null); butt.setSize(300,20); butt.setLocation(10,10); butt.addActionListener(this); pane.add(butt); ta.setBounds(0,50,300,30); pane.add(ta); } //end constructor public void actionPerformed(ActionEvent event){ i++; switch(i){ case 1: ta.setText("And Then Just Touch Me"); break; case 2: ta.setText("Till I Can Get My"); break; case 3: ta.setText("Satisfaction"); break; case 4: ta.setText("Push Me"); break; } } } //end class </code></pre> <p>This simple example works. When the button is pushed, the text area changes. But what if the text is produced by 100 lines of code? Say, if the results of a complex SQL query were pasted there? I wouldn't want to put that 100 lines of code in the <code>MainFrame2</code> class. I’d want to put it into another class, so I've separated my presentation code from my data manipulation code. </p> <p>Going further, what if I had several methods that weren't tied to a particular object? Say, if clicking a button was supposed to write to a log file or send an e-mail? I’d see a need to put that code somewhere outside of the <code>MainFrame2</code> class, but I wouldn't see a need to make a <code>LogFile</code> class or an Email class. I just need a group of methods that I can call without having to make a huge number of new classes.</p> <p>I found a workaround. I made a class called Misc, for all the miscellaneous methods I need to call. Then I instantiate a new Misc object in the <code>MainFrame2</code> class. Then I call the miscellaneous methods from that object. Here are the Misc class and the adjusted <code>MainFrame2</code> class.</p> <p><strong>Misc.java</strong></p> <pre><code>package guitest; public class Misc { Misc(){} public static String lyrics(int i){ if(i == 1){return("And Then Just Touch Me");} if(i == 2){return("Till I Can Get My");} if(i == 3){return("Satisfaction");} if(i == 4){return("Push Me");} return("Something's wrong. I should always be 1-4."); } public static void logging(String s){ //Write s to some file } public static void notification(String sender, String receipient, String subject, String body){ //Send an e-mail to someone. } } </code></pre> <p><strong>MainFrame2.java</strong></p> <pre><code> package guitest; import javax.swing.*; import java.awt.event.*; public class MainFrame2 extends JFrame implements ActionListener{ JPanel pane = new JPanel(); JButton butt = new JButton("Push Me"); JTextArea ta = new JTextArea("Push Me"); int i = 0; MainFrame2(){ super("My GUITest"); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(1000,100,500,500); //From upper left corner (right, down, width, height) this.add(pane); pane.setLayout(null); butt.setSize(300,20); butt.setLocation(10,10); butt.addActionListener(this); pane.add(butt); ta.setBounds(0,50,300,30); pane.add(ta); } //end constructor public void actionPerformed(ActionEvent event){ i++; ta.setText(ot.lyrics(i)); if(i == 4){i = 0;} } } //end class </code></pre> <p>This meets my needs: The code for all those complex methods is</p> <ol> <li>separated from the presentation class</li> <li>accessible by the presentation’s event handlers</li> </ol> <p>But it seems horribly inelegant. It tosses all the random, one-off methods into a class of leftovers. Is there a better way to do this?</p>
[]
[ { "body": "<p>You're on the right way. In principle this is the way used in Java. There are only some differences in real code.</p>\n\n<p>Your class <code>Misc</code> is normally named a <code>Service</code>. A <code>Service</code> class does the business logic of your application. Also normally you don't use <code>static</code> methods but instance methods to do you business logic.</p>\n\n<p>The <code>Service</code> class is normally created outside the GUI code (e.g. in your <code>main()</code> method). You then set the <code>Service</code> class into your GUI class either via the constructor or via a setter.</p>\n\n<p>In more advanced setups you use frameworks like spring to wire up your application.</p>\n\n<p>Also you would have three different services in your case, one for the lyrics (with several methods e.g. to get a single line or the complete lyrics at once), one for the notification and a third for logging (if you don't use a framework for this).</p>\n\n<p>Also the business logic is often parted into two layers, one for the pure business logic and another for the data access (e.g. database access).</p>\n\n<p>Also some other notes:</p>\n\n<ol>\n<li>It is usual to create the GUI first and call <code>setVisible()</code> in the last.</li>\n<li>The GUI initialization code is normally in its own private method that is called from the constructor.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T06:29:01.390", "Id": "28113", "ParentId": "28109", "Score": "4" } }, { "body": "<p>I'm really sorry if I may sound harsh, but there is much things that are wrong in your example.</p>\n\n<p>There is no notion of access modifier being use. Almost everything is by default, which is the package modifier. So all your code is only working because everything is in the same package. If you change the package of any of the three class (<code>Misc</code>, <code>MainFrame2</code> and <code>GuiTest</code>) nothing will work anymore. This is one of the first step you need to take, decide what can be accessed and what not.</p>\n\n<h2>Misc</h2>\n\n<p>You should not return <code>\"Something's wrong. I should always be 1-4.\"</code> bad data as mechanism to show that the method failed. You should fix your method to avoid encountering the wrong case, or throw an exception if you're not in a valid state.</p>\n\n<p>The method <code>lyrics</code> should know by itself which lyrics should be return to the asker, since you want the lyrics in order. One of the big flaws of this class is that it's static. A class that resemble a controller should not be static. You should make an instance and inject your instance where you need the controller. This would help in assuring that no one else is calling the static method from another part of the project and change your order that you should receive your lyrics.</p>\n\n<p>That <code>i</code> was declared in <code>MainFrame2</code> and use in <code>Misc</code> was very unusual and should be avoided at all cost. If you need a variable to be accessible by other classes make get/set and use those to control the state of the variable.</p>\n\n<pre><code>package guitest;\n\npublic class Misc {\n private int count = 0;\n\n public String lyrics() {\n if(count == 4) {\n count = 0;\n }\n count++;\n if (count == 1) {\n return \"And Then Just Touch Me\";\n } else if (count == 2) {\n return \"Till I Can Get My\";\n }else if (count == 3) {\n return (\"Satisfaction\");\n } else {\n return \"Push Me\";\n }\n }\n\n public void logging(String s) {\n // Write s to some file\n }\n\n public void notification(String sender, String recipient,\n String subject, String body) {\n // Send an e-mail to someone.\n }\n}\n</code></pre>\n\n<h2>MainFrame2</h2>\n\n<p>You need to make your class <code>public</code>, you don't need to hide it. You want to use it where you want when you want. Extending <code>JFrame</code> is a bad idea, you don't inheritance favor composition. Your <code>actionPerfomed</code> is a bit too \"intelligent\", it keep track of which lyrics you need to show. This method should not know what she need but should ask someone what should be the next lyrics. You should not use <code>pane.setLayout(null);</code>, try to use a real layout and please don't use absolute positioning. This is hell for maintenance ( I didn't implement this change though). So here is your class, clean up : </p>\n\n<pre><code>package guitest;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\n\npublic class MainFrame2 implements ActionListener {\n private JFrame principalWindow = new JFrame(\"My GUITest\");\n private JPanel panel = new JPanel();\n private JButton pushButton = new JButton(\"Push Me\");\n private JTextArea output = new JTextArea(\"Push Me\");\n\n private Misc miscController;\n\n public MainFrame2(Misc controller) {\n miscController = controller;\n principalWindow.setVisible(true);\n principalWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n principalWindow.setBounds(1000, 100, 500, 500); // From upper left\n // corner (right, down,\n // width, height)\n panel.setLayout(null);\n pushButton.setSize(300, 20);\n pushButton.setLocation(10, 10);\n pushButton.addActionListener(this);\n panel.add(pushButton);\n output.setBounds(0, 50, 300, 30);\n panel.add(output);\n principalWindow.add(panel);\n }\n\n public void actionPerformed(ActionEvent event) {\n output.setText(miscController.lyrics());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-27T01:13:56.660", "Id": "55399", "ParentId": "28109", "Score": "2" } } ]
{ "AcceptedAnswerId": "28113", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T01:26:02.593", "Id": "28109", "Score": "2", "Tags": [ "java", "beginner", "swing" ], "Title": "Separating presentation from the GUI" }
28109
<p>I am trying to pick 3 providers with the highest calculated <code>score</code> based on my algorithm, to recommend them to a user.</p> <p>The recommendation algorithm takes into account a few things. Most are static values, but the one that is <strong>dynamic</strong> is the physical distance from the user (based on lat/lng). Since each user's location is different, I can't cache the distance in the DB.</p> <p>I also need to limit the results to a) providers in a certain category (the <code>WHERE ... IN</code> clause), and b) providers that the user has not already added (the <code>WHERE ... NOT IN</code> clause)</p> <p>Finally I order by <code>score</code> descending limit 3. Here is the query I am running. <code>{$algorithm}</code> is just a complex equation, <code>{$categories}</code> is a comma-separated list</p> <pre><code>SELECT `id`, {$algorithhm} AS `score` FROM `provider` WHERE `id` IN ( SELECT `provider_id` FROM `provider_categories` WHERE `category_id` IN ( {$categories} ) ) AND `id` NOT IN ( SELECT `provider_id` FROM `users_provider` WHERE `user_id` = {$current_user-&gt;id} ) ORDER BY `score` DESC LIMIT 3 </code></pre> <p>I have indexes on every column name you see here. There are only about 13,000 <code>provider</code> records in the database, yet the query takes about .04 seconds on average, which seems pretty slow to me. Back when there were 1,500 providers, it only took .003 seconds. Since I'm hoping to one day have hundreds of thousands, obviously this is a growing concern.</p> <p>What can I do to speed this query up?</p> <p><code>EXPLAIN</code> tells me this:</p> <pre><code> type table type key ref rows Extra 1 PRIMARY provider ALL NULL NULL 12880 Using where; using filesort 3 DEPENDENT SUBQ users_provider eq_ref PRI const, func 1 Using where; using index 2 DEPENDENT SUBQ provider_categories index_subquery PRI func 1 Using index; using where </code></pre> <p><strong>Edit</strong></p> <p>One thought I had was to limit it to providers within an X mile radius. But since the dynamic part of the algorithm is the distance calculation, I would still need to calculate the distance for every provider up front, so that doesn't really help. Maybe instead of a circular radius, I could check within a square lat/lng boundary, since those columns are indexed and the distance wouldn't need to be calculated... just thinking out loud. The main problem with this is that the geocoordinate to mile conversion is very different near the equator vs. near the poles.</p>
[]
[ { "body": "<p>Think one problem is that you have no key that it is using on the provider table, hence it is checking every row.</p>\n\n<p>Not tested the following but this might be faster. Uses the provider_categories table as the first one (on which you are limiting the number of rows with a keyed check) and from that joining to the provider table.</p>\n\n<pre><code>SELECT b.id,\n {$algorithhm} AS score\nFROM provider_categories a\nINNER JOIN provider b ON a.provider_id = b.id\nLEFT OUTER JOIN users_provider c ON a.provider_id = c.provider_id AND user_id = {$current_user-&gt;id}\nWHERE c.provider_id IS NULL AND a.category_id IN ( {$categories} )\nORDER BY score DESC\nLIMIT 3\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T14:45:51.243", "Id": "43894", "Score": "0", "body": "Thanks, but it doesn't seem to be any faster or limit the results any more. EXPLAIN still gives 13000 rows for the first step (and it says table **b**, so it's still grabbing from `provider` first for some reason?). I also tried moving the `a.category_ID IN` clause to the first `INNER JOIN` but that didn't help either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T15:23:47.473", "Id": "43896", "Score": "0", "body": "Try swapping the INNER JOIN for a STRAIGHT_JOIN" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T15:56:57.040", "Id": "43897", "Score": "0", "body": "That helped immensely! Now averaging .008 seconds! Never even heard of `STRAIGHT_JOIN` before, looks like I have some research to do" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T15:58:39.760", "Id": "43898", "Score": "0", "body": "STRAIGHT_JOIN like that just forces the order that MySQL joins the tables in. Most of the time it gets it right but occasionally if doesn't, and then it is useful." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T12:17:41.550", "Id": "28126", "ParentId": "28110", "Score": "2" } } ]
{ "AcceptedAnswerId": "28126", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T01:26:06.733", "Id": "28110", "Score": "0", "Tags": [ "optimization", "algorithm", "mysql", "sql" ], "Title": "Optimized MySQL query with complex calculation" }
28110
<p>This code is supposed to grab live camera feed, display feed in a window, mark in rectangles all detected faces, get the biggest detected face (by total area), display it in separate window, convert it to grayscale and finally save as PNG to hard disk, in project directory.</p> <p>Any ideas for optimizing this code? It has to be OpenCV 2.4.5 compliant.</p> <p>I kindly ask only people familiar with OpenCV2 to give their advice. They know what I mean as for lot of us there is sometimes problem adapting from OpenCV1 to OpenCV2.</p> <pre><code>#include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include &lt;iostream&gt; #include &lt;stdio.h&gt; using namespace std; using namespace cv; // Function Headers void detectAndDisplay(Mat frame); // Global variables // Copy this file from opencv/data/haarscascades to target folder string face_cascade_name = "c:/haarcascade_frontalface_alt.xml"; CascadeClassifier face_cascade; string window_name = "Capture - Face detection"; int filenumber; // Number of file to be saved string filename; // Function main int main(void) { VideoCapture capture(0); if (!capture.isOpened()) // check if we succeeded return -1; // Load the cascade if (!face_cascade.load(face_cascade_name)) { printf("--(!)Error loading\n"); return (-1); }; // Read the video stream Mat frame; for (;;) { capture &gt;&gt; frame; // Apply the classifier to the frame if (!frame.empty()) { detectAndDisplay(frame); } else { printf(" --(!) No captured frame -- Break!"); break; } int c = waitKey(10); if (27 == char(c)) { break; } } return 0; } // Function detectAndDisplay void detectAndDisplay(Mat frame) { std::vector&lt;Rect&gt; faces; Mat frame_gray; Mat crop; Mat res; Mat gray; string text; stringstream sstm; cvtColor(frame, frame_gray, COLOR_BGR2GRAY); equalizeHist(frame_gray, frame_gray); // Detect faces face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30)); // Set Region of Interest cv::Rect roi_b; cv::Rect roi_c; size_t ic = 0; // ic is index of current element int ac = 0; // ac is area of current element size_t ib = 0; // ib is index of biggest element int ab = 0; // ab is area of biggest element for (ic = 0; ic &lt; faces.size(); ic++) // Iterate through all current elements (detected faces) { roi_c.x = faces[ic].x; roi_c.y = faces[ic].y; roi_c.width = (faces[ic].width); roi_c.height = (faces[ic].height); ac = roi_c.width * roi_c.height; // Get the area of current element (detected face) roi_b.x = faces[ib].x; roi_b.y = faces[ib].y; roi_b.width = (faces[ib].width); roi_b.height = (faces[ib].height); ab = roi_b.width * roi_b.height; // Get the area of biggest element, at beginning it is same as "current" element if (ac &gt; ab) { ib = ic; roi_b.x = faces[ib].x; roi_b.y = faces[ib].y; roi_b.width = (faces[ib].width); roi_b.height = (faces[ib].height); } crop = frame(roi_b); resize(crop, res, Size(128, 128), 0, 0, INTER_LINEAR); // This will be needed later while saving images cvtColor(crop, gray, CV_BGR2GRAY); // Convert cropped image to Grayscale // Form a filename filename = ""; stringstream ssfn; ssfn &lt;&lt; filenumber &lt;&lt; ".png"; filename = ssfn.str(); filenumber++; imwrite(filename, gray); Point pt1(faces[ic].x, faces[ic].y); // Display detected faces on main window - live stream from camera Point pt2((faces[ic].x + faces[ic].height), (faces[ic].y + faces[ic].width)); rectangle(frame, pt1, pt2, Scalar(0, 255, 0), 2, 8, 0); } // Show image sstm &lt;&lt; "Crop area size: " &lt;&lt; roi_b.width &lt;&lt; "x" &lt;&lt; roi_b.height &lt;&lt; " Filename: " &lt;&lt; filename; text = sstm.str(); putText(frame, text, cvPoint(30, 30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(0, 0, 255), 1, CV_AA); imshow("original", frame); if (!crop.empty()) { imshow("detected", crop); } else destroyWindow("detected"); } </code></pre>
[]
[ { "body": "<p>Your header asks for <strong>optimization</strong>, but your question asks for <strong>any ideas for improving the code</strong>. I'll answer the latter. If you need to optimize in terms of execution speed or memory use, I recommend using a profiler to measure what the critical path is.</p>\n\n<h3>Overall design</h3>\n\n<p>Your program uses a very C-like structure. Using an object-oriented approach can usually offer many benefits. For example, it will limit the scope of your global variables, since they can be member variables instead.</p>\n\n<p>Your program uses both C++ and C-style IO. I strongly advice you to pick one of them. My recommendation is C++ iostreams, as they are type-safe.</p>\n\n<h3>Inconsistent style</h3>\n\n<p>Your programming style is inconsitent; you do different things in different parts of the program. That looks very untidy. For example, at one point you do:</p>\n\n<pre><code>if (!capture.isOpened()) // check if we succeeded\n return -1;\n</code></pre>\n\n<p>whereas later in the same function, another one-line if gets braces:</p>\n\n<pre><code>if (27 == char(c))\n{\n break;\n}\n</code></pre>\n\n<p>Personally, I prefer to write <code>if</code> statements like this:</p>\n\n<pre><code>if (!capture.isOpened()) return -1;\n</code></pre>\n\n<p>or over multiple lines and with braces. This avoids the risk of code like this:</p>\n\n<pre><code>if (!foo.bar())\n printf(\" --(!) No captured frame -- Break!\");\n foo.cleanup()\n</code></pre>\n\n<p>(In the previous snippet, <code>foo.cleanup()</code> is likely supposed to be run only if the <code>if</code> triggers, but will be run regardless.)</p>\n\n<p>Another example is that at one point you do <code>return -1;</code>, but later you do <code>return (-1);</code>. Prefer the former; <code>return</code> is not a function.</p>\n\n<h3>Readability</h3>\n\n<p>Some of your variables have very poor names. Instead of this:</p>\n\n<pre><code>size_t ic = 0; // ic is index of current element\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>std::size_t index_current = 0;\n</code></pre>\n\n<p>Another thing that greatly boosts readability is avoiding literals in function calls. For example:</p>\n\n<pre><code>face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2,\n 0 | CASCADE_SCALE_IMAGE, Size(30, 30));\n</code></pre>\n\n<p>What's <code>1.1</code>? <code>2</code>? Why is the size 30x30? What do they mean? Are they correct? What possible values can they have? I think it's much better to define symbolic constants instead:</p>\n\n<pre><code>const float size_factor = 1.1;\nconst std::size_t num_buffers = 2;\nconst Size face_size(30, 30);\n\nface_cascade.detectMultiScale(frame_gray, faces, size_factor, num_buffers, 0 | CASCADE_SCALE_IMAGE, face_size);\n</code></pre>\n\n<p>(The names I have given them are likely not what they actually mean. This is just an example.) An addition benefit with this is that code like this:</p>\n\n<pre><code>const float percentage = 20000f;\ndo_something(some_file, percentage);\n</code></pre>\n\n<p>Is more likely to be picked up as a possible error than this:</p>\n\n<pre><code>do_something(some_file, 20000f);\n</code></pre>\n\n<p>On the same note, <code>0 | CASCADE_SCALE_IMAGE</code> is always exactly the same as <code>CASCADE_SCALE_IMAGE</code>, so you can skip the superfluous <code>0 |</code>.</p>\n\n<h3>Comments</h3>\n\n<p>I think comments above the relevant line is more readable than comments beside the relevant line. In other words, prefer</p>\n\n<pre><code>// Get the area of biggest element, at beginning it is same as \"current\" element\nab = roi_b.width * roi_b.height;\n</code></pre>\n\n<p>Over </p>\n\n<pre><code>ab = roi_b.width * roi_b.height; // Get the area of biggest element, at beginning it is same as \"current\" element\n</code></pre>\n\n<p>Also, some of your comments are unnecessary. Comments should explain <em>why</em>, rather than what or how. Comments should not repeat what the code is already saying. <code>// Function main</code> is a great example of a comment that does not add information. Another example is <code>// check if we succeeded</code>.</p>\n\n<p>Personally, I think brief statements of what is going on are good, as long as it doesn't get too much. For example the <code>// Detect faces</code> comment -- I think that's OK.</p>\n\n<h3>Small smells and other details</h3>\n\n<ul>\n<li>Avoid polluting the global namespace with <code>using</code> directives.</li>\n<li>In C++, <code>int main(void)</code> and <code>int main()</code> is exactly the same. Drop <code>void</code> -- this is not C.</li>\n<li>I personally don't like <a href=\"http://en.wikipedia.org/wiki/Yoda_Conditions\">Yoda Conditions</a>, but that's just a matter of preference.</li>\n<li>Limit the scope of variables as much as possible. For example, <code>ic</code> should be restricted to the <code>for</code> loop, as should <code>filename</code>.</li>\n<li>Your program has very little error handling.</li>\n<li>If C++11 is an option, consider using a range-based (<em>foreach</em>-style) <code>for</code> loop</li>\n</ul>\n\n<p>Like this:</p>\n\n<pre><code>for (auto const&amp; face : faces)\n{\n roi_c.x = face.x;\n roi_c.y = face.y;\n\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:04:42.087", "Id": "43915", "Score": "0", "body": "It is a rework of OpenCV2 example. I know about OO approach as I come from Java/C# world. OpenCV framework itself is all mixed up. Even on their official tutorials C and C++ are heavily mixed. Latest trend is to do what you suggest - to exclude C and adopt only C++. Considering that it is framework who currently supports both approaches even long time users of framework are somewhat confused and mix both approaches. You can notice that through many questions on Stackoverflow. BTW I am using Eclipse CDT with autoformat (Allman/BSD style). Anyway, nice review and detailed, I gave you +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T10:37:18.317", "Id": "28123", "ParentId": "28115", "Score": "9" } }, { "body": "<p>This is rather messy code, lots of inconsistencies and I doubt it really works.\nIt looks like something you have written and not bothered to review yourself.\nWriting code is normally an iterative process (for me anyway), whereby you\nwrite something and then consider whether it is any good. Then you refine the\nsolution and consider again. Your idea of what is \"any good\" will develop\nover time, but inconsistency and repetition are clearly not good. </p>\n\n<p>A few observations:</p>\n\n<p><strong>Embedded paths</strong>: It is best not to embed paths in your code. For example\nthe include file paths should be defined during the build (with <code>-I</code>) and the\n<code>face_cascade_name</code> variable should get its value some other way, eg through\narguments to main.\n<hr>\nIn this code, <code>faces</code> is a vector of <code>Rect</code> and <code>roi_c</code> is also a Rect.</p>\n\n<pre><code>roi_c.x = faces[ic].x;\nroi_c.y = faces[ic].y;\nroi_c.width = (faces[ic].width);\nroi_c.height = (faces[ic].height);\n\nac = roi_c.width * roi_c.height; // area of current element\n\nroi_b.x = faces[ib].x;\nroi_b.y = faces[ib].y;\nroi_b.width = (faces[ib].width);\nroi_b.height = (faces[ib].height);\n\nab = roi_b.width * roi_b.height; // area of biggest element\n\nif (ac &gt; ab)\n{\n ib = ic;\n roi_b.x = faces[ib].x;\n roi_b.y = faces[ib].y;\n roi_b.width = (faces[ib].width);\n roi_b.height = (faces[ib].height);\n}\ncrop = frame(roi_b);\n</code></pre>\n\n<p>But <code>roi_c</code> is never used again and <code>roi_b</code> is assigned the same\nvalue twice! My guess is the second assignment should be of <code>roi_c</code> to <code>roi_b</code>,\nbut the whole would be better as:</p>\n\n<pre><code>int area_c = faces[ic].width * faces[ic].height;\nint area_b = faces[ib].width * faces[ib].height;\n\nif (area_c &gt; area_b) {\n roi = faces[ic];\n} else {\n roi = faces[ib];\n}\ncrop = frame(roi);\n</code></pre>\n\n<p>Your coud also pass by reference to <code>frame</code> instead of passing by value. And you might add an <code>area</code> method to the <code>Rect</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:54:59.037", "Id": "43913", "Score": "0", "body": "\"...and I doubt it really works\". Yes, it works. I agree, instead of {\n ib = ic;\n roi_b.x = faces[ib].x;\n roi_b.y = faces[ib].y;\n roi_b.width = (faces[ib].width);\n roi_b.height = (faces[ib].height);\n} I could use just {\n roi_b.x = faces[ic].x;\n roi_b.y = faces[ic].y;\n roi_b.width = (faces[ic].width);\n roi_b.height = (faces[ic].height);\n } . It works both ways. It took a LOT of time to code that tiny piece of code. When I was too tired to even look at monitor I posted it here, hoping to get some good advice not comment such as \"..and not bothered to review yourself. \"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:04:12.647", "Id": "43914", "Score": "0", "body": "You assigned `roi_b.x/y/width/height` with **exactly** the same values twice, once before the `if (ac > ab)` and once inside that condition. Do you not think that is wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:11:00.453", "Id": "43917", "Score": "0", "body": "No, because of: ib = ic; it is NOT exactly the same value. If condition ac > ab is met then ib = ic so the duplicate of this code (when it occurs second time) roi_b.x = faces[ib].x;\n roi_b.y = faces[ib].y;\n roi_b.width = (faces[ib].width);\n roi_b.height = (faces[ib].height); actually becomes (actually) this: roi_b.x = faces[ic].x;\n roi_b.y = faces[ic].y;\n roi_b.width = (faces[ic].width);\n roi_b.height = (faces[ic].height);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:41:25.887", "Id": "43918", "Score": "1", "body": "Oops! I missed that. The refactoring in my answer is still much better code, in my opinion. But you are free to ignore that of course. My answer was unnecessarily blunt, for which I apologise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:51:44.453", "Id": "43920", "Score": "0", "body": "\"refactoring in my answer is still much better code\" +1 for that. I will carefully look at it when I get good sleep. As for \"Embedded paths\" unfortunately, from reasons unknown, at least in this configuration (eclipse CDT, windows 7, MinGW) eclipse CAN'T find relative path, even if additional files are placed next to .exe in /debug. However, if exe is executed from command prompt, then it finds it. Anyway just because of debugging purposes I hardcoded path - but your observation about this is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:52:15.797", "Id": "43921", "Score": "0", "body": "As for \"#include \"opencv2/objdetect/objdetect.hpp\" I can't help it - anyone in OpenCV community is using it that way. Actually it's impossible to make this other way. If you want you can check it here: http://docs.opencv.org/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html#cascade-classifier" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T13:53:02.353", "Id": "28130", "ParentId": "28115", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:00:50.587", "Id": "28115", "Score": "2", "Tags": [ "c++", "optimization", "opencv" ], "Title": "OpenCV 2.4.5 face detection" }
28115
<p>I have a pretty big method where I read data from files and then put them into a combined file in a specific format based on an ID, first and end timestamp.</p> <p>I already refactored some of my code to reduce the code complexity of my method, but it's still over 11 right now. So I was wondering if I should leave the method as is or try to find other ways to make it less complex.</p> <p>This code will run on hardware which is designed by the company I work for so it's important to be as efficient with memory usage as possible.</p> <p>Can you have a look at the code and help me out with reducing the code complexity by extracting pieces of code and putting them into separate methods?</p> <pre><code>protected File getSensorData(String sensorId, long first, long end) throws IOException, NumberFormatException { /* * This method gets data collected from files named after timestamps in seconds */ String[] idArray = new String[0]; String[] valArray = new String[0]; long timestamp = 0; File formatFile = File.createTempFile("temp", "bufferedsensordata"); PrintWriter formatPWriter = getFilePrintWriter(formatFile); // This sorts numerical instead of alphabetical File[] fileArray = sortFiles(file.listFiles()); for(File f : fileArray) { long longTimestamp = getFileTimestamp(f); // Converts filename into timestamp if(longTimestamp &gt;= first &amp;&amp; longTimestamp &lt;= end) { BufferedReader br = new BufferedReader(new FileReader(f)); String line; while(null != (line = br.readLine())) { StringTokenizer tokens = new StringTokenizer(line, ";"); String timestampString = tokens.nextToken(); String id = tokens.nextToken(); String val = tokens.nextToken(); boolean foundId = false; int index = 0; if(id.startsWith(sensorId) &amp;&amp; (Long.parseLong(timestampString) &gt;= first &amp;&amp; Long.parseLong(timestampString) &lt;= end)) { // id should be used and timestamp falls between the requested range if(!Arrays.asList(idArray).contains(id)) { idArray = growArray(idArray); // Increases the array size by 1 to make room for missing id valArray = growArray(valArray); } else { foundId = true; index = getIdIndex(idArray, id); // Returns location of the id in the array } if(foundId) { valArray[index] = val; // Puts value in valArray at same spot as id in idArray } else { idArray[idArray.length -1] = id; // Adds new id &amp; val to end of both arrays valArray[valArray.length -1] = val; } // Timestamps are based on seconds so data should only be written if more than a second has passed // But data is recorded per millisecond so there can be multiple pieces of data per second if(timestamp != Long.parseLong(timestampString)) { if(timestamp != 0) { String dataLine = String.valueOf(timestamp); for(int i = 0; i &lt; valArray.length; i++) { dataLine = dataLine + ";" + valArray[i]; valArray[i] = ""; } formatPWriter.println(dataLine); } // Timestamp is update to the next second timestamp = Long.parseLong(timestampString); } } } } } File finalFile = newFinalFile(); PrintWriter finalPWriter = getFilePrintWriter(finalFile); // Write idArray as first line (header) writeHeader(idArray, finalPWriter); // Write valArray as the rest of the file (body) writeContent(formatFile, finalPWriter); formatFile.delete(); return finalFile; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:29:03.223", "Id": "43872", "Score": "0", "body": "Is there a reason why you use arrays instead of lists?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:31:37.767", "Id": "43873", "Score": "0", "body": "Are this you usual comments or did you add them for the question only?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:34:37.990", "Id": "43874", "Score": "0", "body": "@mnhg I added them for the question only and I'm using arrays because they told me to use arrays, I think because they wanted to keep the memory usage to a minimum, not quite sure to be honest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:38:34.280", "Id": "43875", "Score": "1", "body": "Who is \"they\" and are there really memory constrains (embedded environment?) Usually I recommend to optimize readability/maintainability over abstract memory/performance goals." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:40:52.533", "Id": "43876", "Score": "0", "body": "\"They\" are my superiors (who are also software developers with roughly 10 - 20 years experience). And this is code that will run on hardware that was designed by my company itself. It's not for something like a smartphone or desktop pc or anything. So I think it's more important to have proper memory efficiency than code readability. But that doesn't mean I want as much of both as possible :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:43:30.727", "Id": "43878", "Score": "1", "body": "You are right, but this is an important detail we need to know while reviewing the code. That's why I ask." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:44:16.893", "Id": "43879", "Score": "0", "body": "I'll add it to the question itself, thanks for pointing that out" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T07:24:02.897", "Id": "43950", "Score": "0", "body": "This is _grossly_ inefficient: `idArray = growArray(idArray); // Increases the array size by 1 to make room for missing id`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T07:25:26.450", "Id": "43951", "Score": "0", "body": "@abuzittin gillifirca, Why is that?" } ]
[ { "body": "<p>I have to scroll to read it all, so without looking at the code: <strong>Yes, split it</strong>.</p>\n\n<p>And now with looking at the code:\nI would try to extract the content of your for loop and give the method a nice name.</p>\n\n<p>Afterward you can check how to split this method.</p>\n\n<p>Maybe you want to have a look at <a href=\"https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop\">one-thing-extract-till-you-drop</a> (also check the comments)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:41:40.210", "Id": "43877", "Score": "0", "body": "Thanks for that link, I'll check it out. Definitely looks interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:39:51.983", "Id": "43912", "Score": "0", "body": "+1 for the link. The \"A-Ha\" here is that software principles are fractal; certainly *single responsibility principle (SRP)* applies at the method level. And note that applying any principle inherently brings other guidelines into play. In this case encapsulate complexity, appropriate abstraction, modular construction, readability, understandability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:26:00.663", "Id": "28118", "ParentId": "28116", "Score": "5" } }, { "body": "<p>Reducing the size of your method and making not only it specialized as you should plan your classes is a great way to make your code more readable, so the next guy that has to make some change on it has a easier life.</p>\n\n<p>Read <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean code</a> if you wan't to get better at it, it´s a great book</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T05:16:02.433", "Id": "43944", "Score": "0", "body": "+ Clean Coder + Pragmatic Programmer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T12:36:22.307", "Id": "28128", "ParentId": "28116", "Score": "0" } }, { "body": "<p>Using <code>ArrayList</code> should not be more inefficient than the code above. As your code above contains a <strong>Time and Space inefficient</strong> implementation of it.</p>\n\n<pre><code> String[] idArray = new String[0];\n // ...\n // Increases the array size by 1 to make room for missing id\n idArray = growArray(idArray); \n // ...\n idArray[idArray.length -1] = id;\n</code></pre>\n\n<p>Java arrays are of fixed size. Only way to \"grow\" and array is to allocate a <strong>new</strong> array of larger size, copy its contents to the new array, and update all references to the old array with the references to the new one. You need <strong>more than twice</strong> the size of an array to grow it by only one. Adding an element is <code>O(n)</code>. Filling an array with <code>n</code> elements takes <code>O(n^2)</code> time and ignoring GC <code>O(n^2)</code> space. If you really operate in the large n border cases, where hand coded data structures come into the picture at all, you will hit GC more and more often until you hit it for every insertion. </p>\n\n<p>Whereas <code>ArrayList</code> which grows by a constant factor instead of a constant amount, operates more efficiently and degrades more gracefully, as it hits GC less frequenty until it reaches <code>OutOfMemmoryError</code>.</p>\n\n<p>For efficiency (both time and space), you should allocate enough space right in the beginning, whether you use an array or <code>ArrayList</code>, anyway. If you know you have all the space you need, using an array could save you a few instructions per access.</p>\n\n<p>Also the following two conditionals test for the same thing and rearranging it will make it more readable:</p>\n\n<pre><code>boolean foundId = false; // Declared out of the scoped it is used...\n// ....\nif (!Arrays.asList(idArray).contains(id)) {\n idArray = growArray(idArray);\n valArray = growArray(valArray);\n} else {\n foundId = true;\n index = getIdIndex(idArray, id);\n}\n\nif (foundId) {\n valArray[index] = val;\n} else {\n idArray[idArray.length - 1] = id;\n valArray[valArray.length - 1] = val;\n}\n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>if (Arrays.asList(idArray).contains(id)) {\n // scanning the array for the same string for a second time below:\n index = getIdIndex(idArray, id); \n valArray[index] = val;\n} else {\n idArray = growArray(idArray);\n idArray[idArray.length - 1] = id;\n\n valArray = growArray(valArray);\n valArray[valArray.length - 1] = val;\n}\n</code></pre>\n\n<p>which in turn can be rewritten as:</p>\n\n<pre><code>int index = Arrays.asList(idArray).indexOf(id);\n\nif (index &gt;= 0) {\n valArray[index] = val;\n} else {\n // ... same as above\n}\n</code></pre>\n\n<p>Of course you could just use a <code>LinkedHashMap</code> and optimize only if necessary. (How do you decide if you need to optimize?)</p>\n\n<pre><code>LinkedHashMap&lt;String, String&gt; dict = new LinkedHashMap&lt;String, String&gt;(largeEnough);\n// ... \ndict.put(id, val);\n</code></pre>\n\n<p>Also this code does not do any proper resource management.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T08:30:39.733", "Id": "28157", "ParentId": "28116", "Score": "3" } }, { "body": "<p>If you split a method into smaller ones you have one great benefit: you can give a name to the section that you extracted. And if you can give it a name you can give it a meaning.</p>\n\n<p>If a method is very large it means that you are mixing a lot different aspects that the code is about. You can find these aspects easily while you implement a method. Every time you come to the point when you think \"Hmm, I need to do this/that now\" you have found one aspect (it is the \"this/that\").</p>\n\n<p>Now you have 4 ways of handling it:</p>\n\n<ol>\n<li>Ignore it.</li>\n<li>Introduce a local variable.</li>\n<li>Introduce a method.</li>\n<li>Introduce a class.</li>\n</ol>\n\n<p>To make it concrete an example will show it. The example contains the thoughts of the developer as comments. \nNote that this is only to demonstrate how the methodology I explained above works. The names you give the variables, methods and classes should make these comments needless. If so... you have written clean code.</p>\n\n<pre><code>protected File getSensorData(String sensorId, long fromTime, long toTime)\n throws IOException, NumberFormatException {\n // Hmm, I need to get all files that contain sensor data\n File[] sensorDataFiles = sensorDataDir.listFiles();\n\n // Hmm, I need to filter the sensor data by their timestamp\n File[] inTimeRangeSensorDataFiles = \n filterSensorDataFiles(sensorDataFiles, fromTime, toTime);\n\n // and so on\n}\n\n\nprivate File[] filterSensorDataFiles(File[] sensorDataFiles, long fromTime, long toTime){\n List&lt;File&gt; filteredSensorData = new ArrayList&lt;File&gt;();\n for (File sensorData : sensorDataFiles) {\n\n // Hmm, I need to know if the sensorData is in the time range\n long longTimestamp = getFileTimestamp(sensorData);\n boolean inTimeRange = longTimestamp &gt;= fromTime &amp;&amp; longTimestamp &lt;= toTime;\n\n if (inTimeRange) {\n filteredSensorData.add(sensorData);\n }\n }\n\n // Hmm, I need to return it as an File array\n File[] filteredSensorDataArray = (File[]) filteredSensorData.toArray(new File[filteredSensorData.size()]);\n return filteredSensorDataArray;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:29:33.550", "Id": "28225", "ParentId": "28116", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:03:22.323", "Id": "28116", "Score": "5", "Tags": [ "java", "file" ], "Title": "Putting read data into a combined file based on certain attributes" }
28116
<p>Is there more efficient way remove duplicate records?</p> <pre><code>strsql := 'delete from ' || TableName || ' a where rowid &lt; ( select max(rowid) from ' || TableName || ' b where a.val=b.val )'; </code></pre>
[]
[ { "body": "<p>I would use the ROW_NUMBER windowing function to identify the duplicates and delete those.</p>\n\n<p>Given something like the following:</p>\n\n<pre><code>CREATE TABLE tbl\n(\n v1 VARCHAR2(10)\n ,v2 VARCHAR2(10)\n);\n\nINSERT ALL\n INTO tbl (v1, v2) VALUES ('A','A')\n INTO tbl (v1, v2) VALUES ('A','A')\n INTO tbl (v1, v2) VALUES ('A','Z')\n INTO tbl (v1, v2) VALUES ('B','B')\n INTO tbl (v1, v2) VALUES ('B','B')\n INTO tbl (v1, v2) VALUES ('B','B')\n INTO tbl (v1, v2) VALUES ('C','B')\n INTO tbl (v1, v2) VALUES ('C','B')\n INTO tbl (v1, v2) VALUES ('keep', 'keep')\nSELECT * FROM dual\n;\n</code></pre>\n\n<p>I would do something like the following:</p>\n\n<pre><code>DELETE\n FROM tbl\n WHERE ROWID IN (\n SELECT id\n FROM (\n SELECT\n ROWID AS id\n ,ROW_NUMBER() OVER (PARTITION BY v1, v2 ORDER BY ROWID) AS rnum\n FROM tbl\n )\n WHERE rnum &lt;&gt; 1\n )\n;\n</code></pre>\n\n<p>I wrote a <a href=\"http://comp-phil.blogspot.com/2013/02/how-to-remove-duplicate-records-using.html\" rel=\"nofollow\">blog</a> post about this using SQL Server but the idea is the same on Oracle.</p>\n\n<p>This <a href=\"http://viralpatel.net/blogs/deleting-duplicate-rows-in-oracle/\" rel=\"nofollow\">blog</a> post claims that using ROW_NUMBER for deleting duplicates is very fast in Oracle (my experience in SQL Server would lead me to believe the claim).</p>\n\n<p>Never under estimate the power of windowing functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-18T18:13:58.597", "Id": "47467", "Score": "0", "body": "Sample on SQL Fiddle: http://sqlfiddle.com/#!4/90064/1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-18T18:13:15.173", "Id": "29931", "ParentId": "28117", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T07:03:34.293", "Id": "28117", "Score": "1", "Tags": [ "sql", "oracle" ], "Title": "Efficient way to remove duplicate records" }
28117
<p>This is a very small MVC framework. I have tested this framework and it's working fine. I can do CRUD without any troubles. I am using Smarty to handle the view section. I still feel I can improve this framework and also I want to find out whether I'm doing something wrong here.</p> <p>Could you please spend a moment to check this? Please tell me how I can improve this mini framework. Are there any errors or wrong implementations? Does anything violate OOP structure?</p> <p><strong>index.php</strong></p> <p>This is the 1<sup>st</sup> file to run. It just do all the includes and initiate the bootstrap class.</p> <pre><code>&lt;?php session_start(); /*For debugging*/ error_reporting(E_ALL); require_once('libs/core/Bootstrap.php'); require_once('libs/core/Model.php'); require_once('libs/core/View.php'); require_once('libs/core/Controller.php'); require_once('libs/core/Database.php'); require_once('libs/smarty/Smarty.class.php'); require_once('application/config/config.php'); /* Initiate Bootstrap */ **$bootstrap = new Bootstrap();** ?&gt; </code></pre> <p><strong>Bootstrap.php</strong> explodes the <code>url('/')</code> and gets the controller name and the method name. It loads the controller, loads the method, and passes the parameters (<code>callControllerMethod()</code>). Currently I can pass up to 3 parameters. If the controller/method is invalid, the index controller will run.</p> <pre><code>&lt;?php class Bootstrap { private $url = array(); private $controller = null; private $controllerPath = 'application/controllers/'; // Always include trailing slash private $defaultFile = 'index.php'; function __construct() { $this-&gt;url = $this-&gt;getUrl(); if (empty($this-&gt;url[0])) { $this-&gt;loadDefaultController(); return false; } $this-&gt;loadExistingController(); $this-&gt;callControllerMethod(); } private function getUrl() { $url = isset($_GET['url']) ? $_GET['url'] : NULL; $url = rtrim($url, '/'); $url = filter_var($url, FILTER_SANITIZE_URL); $this-&gt;url = explode('/', $url); return $this-&gt;url; } private function loadDefaultController() { require_once($this-&gt;controllerPath . $this-&gt;defaultFile); $this-&gt;controller = new Index(); $this-&gt;controller-&gt;index(); } private function loadExistingController() { $file = $this-&gt;controllerPath . $this-&gt;url[0] . '.php'; if (file_exists($file)) { require_once($file); $this-&gt;controller = new $this-&gt;url[0](); } else { die('404 Controller is missing!'); } } private function callControllerMethod() { //Get array length $length = count($this-&gt;url); if($length &gt; 1){ if (!method_exists($this-&gt;controller, $this-&gt;url[1])) { die('404 Method is missing!'); } } switch ($length) { case 5: //Controller-&gt;Method(Param1, Param2, Param3) $this-&gt;controller-&gt;{$this-&gt;url[1]}($this-&gt;url[2], $this-&gt;url[3], $this-&gt;url[4]); break; case 4: //Controller-&gt;Method(Param1, Param2) $this-&gt;controller-&gt;{$this-&gt;url[1]}($this-&gt;url[2], $this-&gt;url[3]); break; case 3: //Controller-&gt;Method(Param1) $this-&gt;controller-&gt;{$this-&gt;url[1]}($this-&gt;url[2]); break; case 2: //Controller-&gt;Method() $this-&gt;controller-&gt;{$this-&gt;url[1]}(); break; default: $this-&gt;controller-&gt;index(); break; } } } ?&gt; </code></pre> <p><strong>Base View.php</strong> Initiate Smarty.</p> <p>This sets the Smart dir paths, sets values to the template, and loads the content inside the base template. In the default_theme.tpl I'm calling <code>{include file=$content}</code> to load the custom content.</p> <pre><code>&lt;?php class View { protected $data; protected $smarty; function __construct() { $this-&gt;data = array(); //View $this-&gt;smarty = new Smarty(); $this-&gt;smarty-&gt;setTemplateDir('application/views/templates/'); $this-&gt;smarty-&gt;setCompileDir('application/views/templates_c/'); $this-&gt;smarty-&gt;setConfigDir('application/views/configs/'); $this-&gt;smarty-&gt;setCacheDir('application/views/cache/'); //$this-&gt;smarty-&gt;debugging = true; } public function set($key, $val) { $this-&gt;smarty-&gt;assign($key, $val); } public function render($view) { $this-&gt;smarty-&gt;assign('content', $view.'.tpl'); $this-&gt;smarty-&gt;display('base/default_theme.tpl'); } } ?&gt; </code></pre> <p><strong>Base Controller.php</strong></p> <pre><code>&lt;?php class Controller { protected $view; protected $model; function __construct() { $this-&gt;view = new View(); $this-&gt;model= new Model(); } } ?&gt; </code></pre> <p><strong>Base Model.php</strong></p> <p>I have my own Database.php (PDO class). I have included the model load function here (load). From the controller I can do <code>$this-&gt;helpModel = $this-&gt;model-&gt;load('help_model');</code>.</p> <pre><code>&lt;?php class Model{ protected $db; function __construct() { $this-&gt;db = new Database(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS); } function load($name) { $path = 'application/models/'. $name .'.php'; if (file_exists($path)) { require_once($path); return new $name(); } else { die('Error: Model is not existing.'); } } } ?&gt; </code></pre> <p><strong>This is one of my sample controllers:</strong></p> <pre><code>&lt;?php class help extends Controller{ private $helpModel; function __construct() { parent::__construct(); $this-&gt;helpModel = $this-&gt;model-&gt;load('help_model'); } function index(){ //get data $data = $this-&gt;helpModel-&gt;selectAll(); //set data $this-&gt;view-&gt;set('data',$data); $this-&gt;view-&gt;render('customer/cust'); } public function addUser(){ if($_POST){ extract($_POST); //testing insert $data2["name"] = 'asdasdsd'; $data2["email"] = 'asdasdsd'; $data2["pass"] = 'asdasdsd'; $data2["added"] = date("Y-m-d"); $this-&gt;helpModel-&gt;create($data2); } $this-&gt;index(); } function other($val = false) { echo "inside other function&lt;br/&gt;"; echo "value $val &lt;br/&gt;"; //$this-&gt;index(); } function another($val1,$val2) { echo "inside other function&lt;br/&gt;"; echo "value $val1 and $val2 &lt;br/&gt;"; //$this-&gt;index(); } } ?&gt; </code></pre> <p><strong>My sample <code>Model</code>:</strong></p> <pre><code>&lt;?php class help_model extends Model { function __construct() { parent::__construct(); } public function selectAll() { $results = $this-&gt;db-&gt;selectAll("users"); return $results; } public function create($data) { $values = array( "admin_name"=&gt;$data["name"], "admin_email" =&gt;$data["email"], "admin_pass" =&gt;$data["pass"], "admin_added" =&gt;$data["added"] ); $results = $this-&gt;db-&gt;insert("admins",$values); return $results; } } ?&gt; </code></pre> <p><strong>Sample View</strong></p> <pre><code>&lt;h3&gt;Add Record&lt;/h3&gt; &lt;form action="{$smarty.const.BASE}help/addUser" method="post"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="name"&gt;Name:&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="name" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="email"&gt;Email:&lt;/label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="email" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;input class="btn btn-success" type="submit" value="Submit" name="submit"/&gt; &lt;button class="btn"&gt;Cancel&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;br/&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Stauts&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;Token&lt;/th&gt; &lt;th&gt;Option&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {foreach from=$data item=foo} &lt;tr&gt; &lt;td&gt;{$foo['user_status']}&lt;/td&gt; &lt;td&gt;{$foo['user_name']}&lt;/td&gt; &lt;td&gt;{$foo['user_email']}&lt;/td&gt; &lt;td&gt;{$foo['user_token']|truncate:40}&lt;/td&gt; &lt;td&gt;&lt;a href=""&gt;Edit&lt;/a&gt; /&lt;a href=""&gt;Delete&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; {/foreach} &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>Database.php</strong></p> <pre><code>&lt;?php class Database extends PDO { public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS) { $options = array( PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION ); try { parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS, $options); } catch (PDOException $e) { die($e-&gt;getMessage()); } } public function selectAll($table, $fetchMode = PDO::FETCH_ASSOC) { $sql = "SELECT * FROM $table;"; $sth = $this-&gt;prepare($sql); $sth-&gt;execute(); return $sth-&gt;fetchAll($fetchMode); } public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC) { $sth = $this-&gt;prepare($sql); foreach ($array as $key =&gt; $value) { $sth-&gt;bindValue("$key", $value); } $sth-&gt;execute(); return $sth-&gt;fetchAll($fetchMode); } public function insert($table, $data) { ksort($data); $fieldNames = implode('`, `', array_keys($data)); $fieldValues = ':' . implode(', :', array_keys($data)); $sth = $this-&gt;prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)"); print_r($fieldValues); foreach($data as $key =&gt; $value) { $sth-&gt;bindValue(":$key", $value); } $sth-&gt;execute(); } public function update($table, $data, $where) { ksort($data); $fieldDetails = NULL; foreach ($data as $key =&gt; $value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); $sth = $this-&gt;prepare("UPDATE $table SET $fieldDetails WHERE $where"); foreach ($data as $key =&gt; $value) { $sth-&gt;bindValue(":$key", $value); } $sth-&gt;execute(); } public function delete($table, $where, $limit = 1) { return $this-&gt;exec("DELETE FROM $table WHERE $where LIMIT $limit"); } } </code></pre> <p>Can I just check <code>isUserLoggedIn()</code> in the Bootstrap.php class inside the <code>__construct</code> function? If logged in, run the custom controller. If not, run the default controller.</p>
[]
[ { "body": "<p>Well, I haven't read through all of the code yet, but I couldn't help noticing that you're using a lot of hard-coded paths, and your index.php is just requires the entire FW.<br/>\nIf I were to use your code, in combination with some components, taken from Symfony, or some other FW, I might encounter some problems. </p>\n\n<p>The easy way to solve this is to register an autoloader, set a constant, containing a base path, and using namespaces for your FW's classes. <br/>\nConsider storing your classes in <code>libs/MyFW/</code>, and adding all classes in the _Core_directory (ucfirst your dirs, too) this first line:</p>\n\n<pre><code>namespace MyFW\\Core;\n</code></pre>\n\n<p>The files in <code>Smarty</code>, of course, start with:</p>\n\n<pre><code>namespace MyFW\\Smarty;\n</code></pre>\n\n<p>Then use (or write your own) autoloader, I suggest using Symfony2's UniversalClassLoader, it's quite good.</p>\n\n<p>Then change the index.php to:</p>\n\n<pre><code>&lt;?php\nuse Symfony\\Component\\ClassLoader\\UniversalClassLoader;\nuse MyFW\\Core\\Bootstrap;\n\ndefined('MY_FW_BASE') ||\n define('MY_FW_BASE', realpath(dirname(__FILE__).'../'));\n//the MY_FW_BASE should be your document root\ndefined('LIBS_PATH') || \n define('LIBS_PATH', realpath(MY_FW_BASE.'/libs/'));\n\n //this is the only require you'll ever need\nrequire_once(LIBS_PATH.'/Symfony/Component/ClassLoader/UniversalClassLoader.php');\nset_include_path(\n LIBS_PATH.PATH_SEPARATOR.\n get_include_path()\n);\n$loader = new UniversalClassLoader();\n$loader-&gt;useIncludePath(true);\n$loader-&gt;registerNamespaces(\n array(\n 'Symfony' =&gt; LIBS_PATH,\n 'MyFW' =&gt; LIBS_PATH\n )\n);\n//suppose you want to use ZendFW 1.x, store it in libs/Zend, and add this line:\n$loader-&gt;registerPrefix('Zend_', LIBS_PATH);\n$loader-&gt;register();//register the autoloader, job done\n\n$bootstrap = new Bootstrap;\n</code></pre>\n\n<p>Note that using namespaces, if you want to access the core objects in some namespace, or access globaly defined constants, you'll have to use a <code>\\</code> to indicate the object or constant was defined in the global namespace:</p>\n\n<pre><code>namespace MyFW\\Core;\n$pdo = new \\PDO(\\GLOBAL_PDO_STRING);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>namespace MyFW\\Core;\nuse \\PDO,\n \\PDOException;\n$pdo = new PDO(\\GLOBAL_PDO_STRING);\n</code></pre>\n\n<p>You can avoid name-conflicts this way, easily:</p>\n\n<pre><code>namespace MyFW\\Core\nuse OtherNS\\Database as OtherDB;\nclass Database extends OtherDB\n{\n}\n</code></pre>\n\n<p>We now have 2 Database classes, one extending the other, but in the namespace of the <code>MyFQ\\Core\\Database</code>, the other Database is called <code>OtherDB</code>, so there's no conflict.<br/>\nRead up on Namespaces in PHP, when writing a framework, they're quite handy indeed.</p>\n\n<p>You're also extending from <code>PDO</code>, which in itself is fine, but I tend to say that extending an object you don't control isn't really <em>good practice</em>, just create a wrapper object if needs must.</p>\n\n<p>I'll update this answer along the way, if I think of something else whilst reviewing your code</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T12:06:19.610", "Id": "28125", "ParentId": "28119", "Score": "1" } }, { "body": "<p>There are several areas that could be improved:</p>\n\n<ol>\n<li>Stop calling it \"MVC framework\". There is no model, because model is a layer, not an abstraction for DB table. There is no controller, because controller is not responsible for passing data, rendering template and initializing DB abstractions.</li>\n<li>Learn about autoloading in PHP. Look up <a href=\"http://uk3.php.net/manual/en/function.spl-autoload-register.php\"><code>spl_autoload_register()</code></a> and how it is used.</li>\n<li>Never perform any computation in the constructors. Those should be used only for assigning values, otherwise the code is difficult to test.</li>\n<li>Learn to write <a href=\"https://www.youtube.com/watch?v=wEhu57pih5w\">unit tests</a>.</li>\n<li>Learn how to (and when) to use <a href=\"https://www.youtube.com/watch?v=nLinqtCfhKY\">prepares statements</a>. Also, please actually learn how to use <a href=\"http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers\">PDO</a>. The code does is using emulated prepared statements, which removes any protection against injections.</li>\n<li>Apply <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\">S.O.L.I.D</a> principles to the codebase, as there are numerous violations throughout.</li>\n<li>Avoid <a href=\"https://www.youtube.com/watch?v=-FRm3VPhseI\">global state</a> in form of static structures or constants.</li>\n<li>Most of the code is tightly coupled to to specific class names. Instead learn about <a href=\"http://www.martinfowler.com/articles/injection.html\">dependency injection</a>.</li>\n<li><strong>Controllers in MVC are not autoloaders for Model layer structures.</strong></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T14:48:31.760", "Id": "28131", "ParentId": "28119", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T08:26:33.187", "Id": "28119", "Score": "2", "Tags": [ "php", "object-oriented", "mvc", "authentication", "smarty" ], "Title": "Very small MVC login framework" }
28119
<p><strong>Information about my code:</strong></p> <p>I am following this <a href="http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/" rel="nofollow">MIT OCW algorithms course</a>. The first lecture described insertion sort and merge sort. I implemented insertion sort in C. </p> <p>The algorithm is structured as a function called from the <code>main</code> function. The array to be sorted is allocated dynamically in the <code>main</code> function but can also be statically allocated.</p> <p><strong>What I am looking for:</strong></p> <p>I am looking whether the code can be optimized without changing the algorithm (insertion sort), whether it follows the best-practices of programming in C and does it have proper readability factor?</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; void insertion_sort(int arr[], int length) { /* Sorts into non-decreasing order To change the sorting to non-increasing order just change the comparison in while loop */ register int j, k; int temp; for(j = 1; j &lt; length; j++) { temp = arr[j]; k = j - 1; while (k &gt;= 0 &amp;&amp; arr[k] &gt; temp) { arr[k + 1] = arr[k]; k--; } arr[k + 1] = temp; } } int main() { int length; register int i; int *arr; //Finds the length of array and dynamically creates array of that length scanf("%d", &amp;length); if ( (arr = (int *)malloc(sizeof(int) * length)) == NULL) { printf("Not enough memory"); return 1; } //Reads the array for(i = 0; i &lt; length; i++) scanf("%d", &amp;arr[i]); //Calls the sorting algorithm insertion_sort(arr, length); //Prints the sorted array for(i = 0; i &lt; length; i++) printf("%d ", arr[i]); //Frees the memory allocated and returns free(arr); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T10:19:43.153", "Id": "43953", "Score": "1", "body": "http://en.wikipedia.org/wiki/Insertion_sort#Variants" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:08:43.573", "Id": "43985", "Score": "1", "body": "@MarcDefiant Thanks for the link but instead of changing the algorithm I just wanted reviews about the currently implemented algorithm. Although they are variants of this algorithm they **are** different algorithms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T11:29:09.130", "Id": "44016", "Score": "0", "body": "It'd be better if your sort was done on a linked list, as inserting elements to an array is very slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T11:30:29.613", "Id": "44017", "Score": "0", "body": "@VedranŠego I didn't understand what you said. Are you talking about the `main` function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T13:16:56.620", "Id": "44023", "Score": "0", "body": "Sorry, I've mixed something up. Linked lists would make search slower, so the overall complexity would be O(n^2), just like in your case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T13:20:35.853", "Id": "44024", "Score": "0", "body": "I get it now. You mixed up inserting elements into an array with insertion into linked list. That would be slower." } ]
[ { "body": "<p>I cannot offer any optimization, only a few comments on best practice (as I\nsee it). There's very little to say; the code is nice.</p>\n\n<ul>\n<li><p>Use of <code>register</code> is unnecessary (and hence rare). The compiler may well\nignore it and it probably has a better idea of what to put in registers than\nyou or I.</p></li>\n<li><p>It is best to define variables nearer to where they are first used. This\nreduces their scope and makes for easier reading. For example in\n<code>insertion_sort</code> I would do:</p>\n\n<pre><code>for(int j = 1; j &lt; length; j++)\n{\n int temp = arr[j];\n int k = j - 1;\n while (k &gt;= 0 &amp;&amp; arr[k] &gt; temp)\n ...\n</code></pre>\n\n<p>So I defined the loop variable <code>j</code> in the loop and <code>temp</code> and <code>k</code> at the \npoint of first use. (This makes even more sense in C++ where an early definition incurs the overhead of a default construtor call.)</p></li>\n<li><p>Your while-loop could arguably be a for-loop. A for-loop makes the loop\nconditions more immediately obvious, but in such a short loop it makes no\ndifference. </p></li>\n<li><p>In <code>main</code> you cast the return from <code>malloc</code>. This is necessary in C++ but\nnot in C. And on an error in system and library calls that set the global\n<code>errno</code>, such as <code>malloc</code>, I would use <code>perror(\"malloc\")</code> which will print a\nrelevant error message to stderr, instead of rolling your own with <code>printf</code> (which prints to stdout).</p></li>\n<li><p>Again your for-loops in <code>main</code> would be better defining loop variable <code>i</code>\nin the loop. Also these loops should have braces:</p>\n\n<pre><code>for (int i = 0; i &lt; length; i++) {\n scanf(\"%d\", &amp;arr[i]);\n}\n</code></pre>\n\n<p>Strictly speaking braces are not necessary but they are considered good\npractice, as they prevent a class of error such as someone adding a printf:</p>\n\n<pre><code>for (int i = 0; i &lt; length; i++) \n scanf(\"%d\", &amp;arr[i]);\n print(\"%d\", &amp;arr[i]);\n</code></pre></li>\n<li><p>For safety, you should always check user input before using it, such as\n<code>length</code> here.</p></li>\n<li><p>Your comments in <code>main</code> are really just stating the obvious and as such\ncould be considered 'noise'. The comment in <code>insertion_sort</code> on the other\nhand is more useful, although 'non-decreasing' and 'non-increasing' are odd\nways to say 'increasing' and 'decreasing' respectively.</p></li>\n<li><p>Really nit-picking, I prefer a space after <code>for</code> and <code>while</code> and no space\nbetween brackets in the expression <code>if ((arr = malloc(sizeof...</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T16:43:47.380", "Id": "43984", "Score": "0", "body": "About defining temp and k inside the for loop. I don't know about C++ but in C wouldn't that have significant more overhead in case of outer loop iterating over large ranges? Also wouldn't declaring loop variables at the beginning of a function better if they are reused instead of declaring them again and again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:48:20.703", "Id": "43990", "Score": "1", "body": "No, in C there is no extra overhead associated with exactly where you define a variable. The compiler will handle such things optimally without your needing to care. And defining a loop variable in each loop instead of once at the beginning of the function incurs absolutely no overhead. On the plus side though it reduces the scope of the variable, which is always good - the reader knows for sure that it is not used outside the loop in which it is defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T11:19:42.777", "Id": "44015", "Score": "0", "body": "Can you add something about `errno`. I haven't used it ot `perror()` before. In my code the output of overflow is shown on the console itself. Is that the correct behaviour? Also I have updated the code. Please give your comments about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T12:26:16.210", "Id": "44018", "Score": "0", "body": "Every process on Unix etc has a global error number variable named `errno` set by failing system/library calls. Take a look at the Wikipedia page on `errno` or look at the manual pages on your system (type `man perror`)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T02:06:09.657", "Id": "28153", "ParentId": "28132", "Score": "3" } } ]
{ "AcceptedAnswerId": "28153", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T14:52:32.353", "Id": "28132", "Score": "2", "Tags": [ "optimization", "c", "sorting", "insertion-sort" ], "Title": "Implementation of insertion sort" }
28132
<p>I have this code:</p> <pre><code>public bool IsWorkAddedWIthConcreteImplementation() { SomeAgentClass agentClass = new SomeAgentClass(); bool param1 = true; string param2 = "Hello"; DataTable dt1 = agentClass.ProvideData(param1, param2); SimpleDAl da = new SimpleDAl(); DataTable dt = da.ProvideData(dt1); bool isDataSentSuccessfully = agentClass.SendDataToClient(dt); IUnImplementedInterface dalInterface = new SimpleDAl(); if (dalInterface.ReturnMeTrue(dt1)) { return true; } else { return false; } } </code></pre> <p>And the implementation</p> <pre><code> IUnImplementedInterface dalInterface = new SimpleDAl(); </code></pre> <p>Should I have passed the interface as a parameter to method or in the class constructor? What will happen to the method signature or class constructor signature if more interfaces are introduced ?</p> <p><strong>Update:</strong></p> <p>In the actual implementation new SimpleDal() class is replaced by DaFactory.GetUnImplementedInterface(), which is returning me the concrete instance of IUnImplementedInterface.</p> <p>Now the DaFactory is using Activator.CreateInstance() in order to give me correct instantiation.</p> <p><strong>Update2</strong></p> <p>One thing I forgot to tell was, that I am passing the DaFactory instance in the constructor of this class, and later using this factory instance to create concrete IUnImplementedInterface instance.</p> <p><strong>Update3 and Solution</strong></p> <p>Finally my code structure will now be having a IUnImplementedInterface instance in the class rather than the Factory instance.So now the caller of this class will have to pass the correct concrete implementation of this interface in its constructor.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T16:01:48.480", "Id": "43899", "Score": "1", "body": "What is this code trying to accomplish? The only suggestion I could make without more context is to use `return dalInterface.ReturnMeTrue(dt1)` instead of `if..else`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:24:58.977", "Id": "43909", "Score": "0", "body": "This method is not a real implementation. It is just created to understand the common mistakes I make, I found out that during unit testing I wasn't able to test this method, so I asked You people whether the code is correct or has some problems in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:10:39.890", "Id": "43916", "Score": "1", "body": "It's impossible to determine if this code is 'correct' without knowing the intent. There's nothing inherently wrong with it it, although the way you use the classes seems strange. If you give us some broader context we may be able to give you an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:38:45.940", "Id": "43988", "Score": "0", "body": "updated my question as asked. Hope this sheds more light on the context I am talking about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T15:37:46.517", "Id": "44365", "Score": "0", "body": "Thanks a lot for everyone, I don't know which one to choose for answer but, all these answers have been helpful. I have now updated my actual code to adhere to [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter)" } ]
[ { "body": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa973811.aspx\" rel=\"nofollow\">This</a> article is a great overview of Inversion of Control (IoC), and why it makes code easier to work with. But here's an example in the context of the code you posted. Imagine you are working on the <code>SimpleDal</code> class and decide that you have some configuration setting that you need to pass in. So now your constructor looks like this.</p>\n\n<pre><code>public class SimpleDal:IUnImplementedInterface\n{\n public SimpleDal(string configSetting)\n {\n ...do something with it\n }\n\n ...\n\n public bool ReturnMeTrue(DataTable dt1){...}\n}\n</code></pre>\n\n<p>This is not an issue in itself, except for now your line </p>\n\n<pre><code>IUnImplementedInterface dalInterface = new SimpleDAl();\n</code></pre>\n\n<p>needs to have that string in the constructor call (or you could add another constructor that called it with a default value). The point here is that in the end all your calling code really cares about is the <code>IUnImplementedInterface.ReturnMeTrue()</code> method. You \"should\" be able to replace SimpleDal with any other class that implements that interface (<a href=\"http://www.cs.utexas.edu/~mitra/csSummer2013/cs312/lectures/interfaces.html\" rel=\"nofollow\">polymorphism</a>). So, by deferring the creation of the IUnImplementedInterface instance to a level above the calling code or by using a factory method, you separate the concern of creating a dependency and using that dependency. The two most popular methods of achieving that are <a href=\"http://www.martinfowler.com/articles/injection.html\" rel=\"nofollow\">Dependency Injection</a>, or <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow\">Factory methods</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:43:10.773", "Id": "43989", "Score": "0", "body": "@matt I didn't mentioned that I was using factory methods to create concrete instances. Please see my updated question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T15:52:04.867", "Id": "44367", "Score": "0", "body": "Thanks a lot Matt, my next step would certainly be using Ioc and making them configuring my classes, if that is possible :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:59:56.497", "Id": "28149", "ParentId": "28134", "Score": "3" } }, { "body": "<p>I think Factories are a pretty common way of dealing with these situations whether it's right or not. Dependency Injection is a fantastic way to manage changing interfaces but can easily slip down a path where the class starts to violate Single Responsibility Principle or the number of variables injected become ridiculous. Passing via constructor or method really depends on the needed life span of the object in the class but also remember <a href=\"https://stackoverflow.com/questions/2244860/when-a-method-has-too-many-parameters\">Uncle Bob Martin says the best number of parameters is 0, the next best is 1, etc.</a>.</p>\n\n<p>Take a look a Test Driven Development. This guide <a href=\"http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf\" rel=\"nofollow noreferrer\">\"Writing Testable Code\" by Jonathan Wolter, Russ Ruffer, Misko Hevery</a> has served me well and should help you pull those instantiations from your method. When you write methods to be testable many of these questions solve themselves.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T15:50:51.723", "Id": "44366", "Score": "0", "body": "I consider this as an answer because it gives me a Link to Writing testable code again further in this link it discusses regarding Law of Demeter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T21:24:18.677", "Id": "28180", "ParentId": "28134", "Score": "1" } } ]
{ "AcceptedAnswerId": "28180", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T15:32:22.137", "Id": "28134", "Score": "0", "Tags": [ "c#", "object-oriented" ], "Title": "creating a concreate implemetation inside a method" }
28134
<p>I am trying to allow users to upload profile pics on my site. Basically I am following this code: <a href="https://stackoverflow.com/questions/4360568/allow-users-to-upload-a-pic-for-their-profile">Allow users to upload a pic for their profile</a>.</p> <p>I don't know if the code is secure enough. I am worried that users may upload malicious files.</p> <p>Also, I am concerned that if there is many users, I will have many pictures in a single folder and it may slow down the retrieving process. I wonder what is the best practice in storing the profile pics. How many photos maximum should there be in a folder for better efficiency? </p> <pre><code>if(is_uploaded_file($_FILES['image']['tmp_name'])) { uploadImage($_FILES['image']['tmp_name'], 100, 100, "image/users/test2.jpeg"); } </code></pre> <p>and</p> <pre><code>function uploadImage($source, $max_width, $max_height, $destination) { list($width, $height) = getimagesize($source); if ($width &gt; 150 || $height &gt; 150) { $ratioh = $max_height / $height; $ratiow = $max_width / $width; $ratio = max($ratioh, $ratiow); // New dimensions $newwidth = intval($ratio * $width); $newheight = intval($ratio * $height); $newImage = imagecreatetruecolor($newwidth, $newheight); $ext = trim(strtolower($_FILES['image']['type'])); $sourceImage = null; // Generate source image depending on file type switch ($ext) { case "image/jpg": case "image/jpeg": $sourceImage = imagecreatefromjpeg($source); break; case "image/gif": $sourceImage = imagecreatefromgif($source); break; case "image/png": $sourceImage = imagecreatefrompng($source); break; } imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Output file depending on type switch ($ext) { case "image/jpg": case "image/jpeg": imagejpeg($newImage, $destination); break; case "image/gif": imagegif($newImage, $destination); break; case "image/png": imagepng($newImage, $destination); break; } // Destroy resources imagedestroy($newImage); imagedestroy($sourceImage); } } </code></pre>
[]
[ { "body": "<p>what happens if I upload a .exe file? or even a .txt file? Your application will give errors. Always have a fallback for if some hack0r uploads a non-picture to your application. Use the default: statement in your switch cases for that and hand back an error when they try to upload a non-image or a image you don't support (e.g. svg).</p>\n\n<p>You talk about security and number of files in one directory, why is there a correlation between these two? The only restriction you have on the number of files per directory depends on the Filestructure format.</p>\n\n<p>I would however create a directory per user instead of storing all the images in the same directory.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:53:15.377", "Id": "28143", "ParentId": "28136", "Score": "1" } }, { "body": "<p>This won't help with security, but if you want to shorten your code a little, you can replace this </p>\n\n<pre><code>// Generate source image depending on file type\nswitch ($ext) { \ncase \"image/jpg\":\ncase \"image/jpeg\":\n $sourceImage = imagecreatefromjpeg($source);\n break;\ncase \"image/gif\":\n $sourceImage = imagecreatefromgif($source);\n break;\ncase \"image/png\":\n $sourceImage = imagecreatefrompng($source);\n break;\n}\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>$sourceImage = imagecreatefromstring(file_get_contents($source)); \n</code></pre>\n\n<p>Also why don't you just store the whole lot as jpg, why is it necessary to save them as different types</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T21:21:48.863", "Id": "73116", "Score": "0", "body": "Always make sure there is a default. Especially in a case like this where the program has a chance of breaking if the conditions aren't met." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T21:39:35.423", "Id": "30703", "ParentId": "28136", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T16:32:53.347", "Id": "28136", "Score": "1", "Tags": [ "php", "security" ], "Title": "Security and efficiency for profile picture upload" }
28136
<p>I am sure there are better ways to do things but this is part of my first JavaScript project and I'm slowly getting accustomed with how things work in JavaScript. This is also why I ask for a code review, to find what I could not see.</p> <p>Suggestions on idiomatic JavaScript would be welcome.</p> <pre><code>/* Circular buffer used to add values in blocks of constant size */ function IndexOutOfBounds(maxIndex, requestedIndex, method) { this.maxIndex = maxIndex; this.requestedIndex = requestedIndex; this.method = method; this.toString = function () { return "Invalid index in method ['" + this.method + "']\n" + "Requested index : " + this.requestedIndex + "\n" + "Valid _buffer index : " + "[0.." + this.maxIndex + "]"; }; } function ImproperBlockLength(ringBlockLength, givenBlockLength) { this.ringBlockLength = ringBlockLength; this.givenBlockLength = givenBlockLength; this.toString = function () { return "Block length mismatch.\n" + "Requeste block length : " + this.givenBlockLength + "\n" + "Valid block length : " + this.ringBlockLength; }; } function Ring(length, blockLength) { this.length = length; this._maxIndex = this.length - 1; this._start = 0; this._buffer = new Float32Array(this.length); /* blockLength should always be a factor of size. * An exception is thrown if it's not; */ this._blockLength = 0; if (blockLength) { if (length % blockLength != 0) { throw "Block length must be a factor of length."; } else { this._blockLength = blockLength; } } } Ring.prototype.checkBounds = function (requested, callerName) { if (requested &lt; 0 || requested &gt; this._maxIndex) throw new IndexOutOfBounds(this._maxIndex, requested, callerName); }; Ring.prototype.relativeIndex = function(index) { return (this._start + index) % this.length; }; /* Should not be used when there is a set _blockLength */ Ring.prototype.push = function (element) { this._buffer[this._start] = element; var newStart = this._start + 1; this._start = newStart &gt; this._maxIndex ? 0 : newStart; }; Ring.prototype.get = function (index) { this.checkBounds(index, 'get'); return this._buffer[this.relativeIndex(index)]; }; Ring.prototype.set = function (index, value) { this.checkBounds(index, 'set'); this._buffer[this.relativeIndex(index)] = value; }; Ring.prototype.concat = function(arr) { var alen = arr.length; var blen = this._blockLength; if (alen != blen) { throw new ImproperBlockLength(blen, alen); } this._buffer.set(arr, this._start); this._start = (this._start + alen) % this.length; }; Ring.prototype.map = function (callback) { var relativeIndex; var value; for(var i = 0 ; i &lt; this.length ; i++) { relativeIndex = this.relativeIndex(i); value = this._buffer[relativeIndex]; this._buffer[relativeIndex] = callback(value, i, this.length); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T10:38:36.447", "Id": "43956", "Score": "0", "body": "You could move your `this.toString` methods out from their respective functions and make them `xxx.prototype.toString` and thereby they are not created on every `new` instance but reused from the `prototype`. I am not a fan of the `x ? y : z` conditionals, personally I prefer the long `if .. then .. else` for readability (but this is just personal preference). I also prefer `i += 1;` to `i++`. You could run your code through [jslint](http://www.jslint.com/) for further styling tips and it may find some errors/warnings that you haven't considered." } ]
[ { "body": "<p>I haven't examined the actual functionality, but this is based on my comment about moving <code>this.toString</code> to a <code>prototype method</code> (which is, I feel, the main improvement) and then I've done a few micro optimisations (but nothing that is going to make any real noticeable difference). Other than that I performed a bit of personal styling, there was nothing particularly wrong with what you had.</p>\n\n<p>Javascript</p>\n\n<pre><code>/*jslint maxerr: 50, indent: 4, browser: true, nomen: true */\n/*global Float32Array */\n\n(function () {\n \"use strict\";\n\n /* Circular buffer used to add values in blocks of constant size */\n\n function IndexOutOfBounds(maxIndex, requestedIndex, method) {\n this.maxIndex = maxIndex;\n this.requestedIndex = requestedIndex;\n this.method = method;\n }\n\n IndexOutOfBounds.prototype.toString = function () {\n return \"Invalid index in method ['\" + this.method + \"']\\nRequested index : \" + this.requestedIndex + \"\\nValid _buffer index : [0..\" + this.maxIndex + \"]\";\n };\n\n function ImproperBlockLength(ringBlockLength, givenBlockLength) {\n this.ringBlockLength = ringBlockLength;\n this.givenBlockLength = givenBlockLength;\n }\n\n ImproperBlockLength.prototype.toString = function () {\n return \"Block length mismatch.\\nRequeste block length : \" + this.givenBlockLength + \"\\nValid block length : \" + this.ringBlockLength;\n };\n\n function Ring(length, blockLength) {\n this.length = length;\n this._maxIndex = length - 1;\n this._start = 0;\n this._buffer = new Float32Array(length);\n\n /* blockLength should always be a factor of size.\n * An exception is thrown if it's not;\n */\n this._blockLength = 0;\n if (blockLength) {\n if (length % blockLength !== 0) {\n throw \"Block length must be a factor of length.\";\n }\n\n this._blockLength = blockLength;\n }\n }\n\n Ring.prototype.checkBounds = function (requested, callerName) {\n var maxIndex = this._maxIndex;\n\n if (requested &lt; 0 || requested &gt; maxIndex) {\n throw new IndexOutOfBounds(maxIndex, requested, callerName);\n }\n };\n\n Ring.prototype.relativeIndex = function (index) {\n return (this._start + index) % this.length;\n };\n\n /* Should not be used when there is a set _blockLength */\n Ring.prototype.push = function (element) {\n var start = this._start,\n newStart = start + 1;\n\n this._buffer[start] = element;\n this._start = 0;\n if (newStart &lt;= this._maxIndex) {\n this._start = newStart;\n }\n };\n\n Ring.prototype.get = function (index) {\n this.checkBounds(index, 'get');\n\n return this._buffer[this.relativeIndex(index)];\n };\n\n Ring.prototype.set = function (index, value) {\n this.checkBounds(index, 'set');\n this._buffer[this.relativeIndex(index)] = value;\n\n };\n\n Ring.prototype.concat = function (arr) {\n var alen = arr.length,\n blen = this._blockLength,\n start;\n\n if (alen !== blen) {\n throw new ImproperBlockLength(blen, alen);\n }\n\n start = this._start;\n this._buffer.set(arr, start);\n this._start = (start + alen) % this.length;\n\n };\n\n Ring.prototype.map = function (callback) {\n var relativeIndex,\n length = this.length,\n i = 0;\n\n while (i &lt; length) {\n relativeIndex = this.relativeIndex(i);\n this._buffer[relativeIndex] = callback(this._buffer[relativeIndex], i, length);\n i += 1;\n }\n };\n}());\n</code></pre>\n\n<p>One other thing to consider is, because you will only be using newer browsers that support <code>Float32Array</code> then you could also define properties using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow\"><code>Object.defineProperty</code></a></p>\n\n<p><em><strong>Update:</strong> Here is a <a href=\"/questions/tagged/refactoring\" class=\"post-tag\" title=\"show questions tagged 'refactoring'\" rel=\"tag\">refactoring</a> using <code>Object.defineProperty</code>, I did it kind of quick so there are no guarantees that I did it correctly, it is more to give you a starter, hope it helps.</em></p>\n\n<p>Javascript</p>\n\n<pre><code>/*jslint maxerr: 50, indent: 4, browser: true, nomen: true, bitwise: true */\n/*global console, Float32Array */\n\n(function () {\n \"use strict\";\n\n var Ring = (function () {\n /* Circular buffer used to add values in blocks of constant size */\n\n var minIndex = 0,\n maxIndex = 4294967294;\n\n function clamp(number, min, max) {\n return Math.min(Math.max(number, min), max);\n }\n\n function IndexOutOfBounds(maxIndex, requestedIndex, method) {\n Object.defineProperties(this, {\n \"maxIndex\": {\n value: maxIndex\n },\n\n \"requestedIndex\": {\n value: requestedIndex\n },\n\n \"method\": {\n value: method\n }\n });\n }\n\n Object.defineProperty(IndexOutOfBounds.prototype, \"toString\", {\n get: function () {\n return \"Invalid index in method ['\" + this.method + \"']\\nRequested index : \" + this.requestedIndex + \"\\nValid _buffer index : [0..\" + this.maxIndex + \"]\";\n }\n });\n\n function ImproperBlockLength(ringBlockLength, givenBlockLength) {\n Object.defineProperties(this, {\n \"ringBlockLength\": {\n value: ringBlockLength\n },\n\n \"givenBlockLength\": {\n value: givenBlockLength\n }\n });\n }\n\n Object.defineProperty(ImproperBlockLength.prototype, \"toString\", {\n get: function () {\n return \"Block length mismatch.\\nRequeste block length : \" + this.givenBlockLength + \"\\nValid block length : \" + this.ringBlockLength;\n }\n });\n\n function Ring(length, blockLength) {\n length = clamp(length, minIndex, maxIndex + 1) &gt;&gt;&gt; 0;\n\n /* blockLength should always be a factor of size.\n * An exception is thrown if it's not;\n */\n blockLength = clamp(blockLength, minIndex, maxIndex + 1) &gt;&gt;&gt; 0;\n if (length % blockLength !== 0) {\n throw \"Block length must be a factor of length.\";\n }\n\n var privateStart = 0,\n privateBuffer = new Float32Array(length);\n\n Object.defineProperties(this, {\n \"length\": {\n get: function () {\n return length;\n },\n\n set: function (newLength) {\n length = clamp(newLength, minIndex, maxIndex + 1) &gt;&gt;&gt; 0;\n }\n },\n\n \"_start\": {\n get: function () {\n return privateStart;\n },\n\n set: function (start) {\n privateStart = clamp(start, minIndex, maxIndex) &gt;&gt;&gt; 0;\n }\n },\n\n \"_buffer\": {\n get: function () {\n return privateBuffer;\n },\n\n set: function (buffer) {\n privateBuffer = buffer;\n }\n },\n\n \"_blockLength\": {\n value: blockLength\n }\n });\n }\n\n Object.defineProperties(Ring.prototype, {\n \"_maxIndex\": {\n value: function () {\n return clamp(this.length - 1, minIndex, maxIndex) &gt;&gt;&gt; 0;\n }\n },\n\n \"checkBounds\": {\n value: function (requested, callerName) {\n var maxIndex = this._maxIndex;\n\n if (requested &lt; 0 || requested &gt; maxIndex) {\n throw new IndexOutOfBounds(maxIndex, requested, callerName);\n }\n\n return maxIndex;\n }\n },\n\n \"relativeIndex\": {\n value: function (index) {\n return (this._start + index) % this.length;\n }\n },\n\n /* Should not be used when there is a set _blockLength */\n \"push\": {\n value: function (element) {\n var start = this._start,\n newStart = start + 1;\n\n this.buffer = element;\n if (newStart &gt; this._maxIndex) {\n this._start = 0;\n } else {\n this._start = newStart;\n }\n }\n },\n\n \"get\": {\n value: function (index) {\n this.checkBounds(index, 'get');\n\n return this._buffer[this.relativeIndex(index)];\n }\n },\n\n \"set\": {\n value: function (index, value) {\n this.checkBounds(index, 'set');\n this._buffer[this.relativeIndex(index)] = value;\n }\n },\n\n \"concat\": {\n value: function (arr) {\n var alen = arr.length,\n blen = this._blockLength,\n start;\n\n if (alen !== blen) {\n throw new ImproperBlockLength(blen, alen);\n }\n\n start = this._start;\n this._buffer.set(arr, start);\n this._start = (start + alen) % this.length;\n }\n },\n\n \"map\": {\n value: function (callback) {\n var relativeIndex,\n length = this.length,\n i = 0;\n\n while (i &lt; length) {\n relativeIndex = this.relativeIndex(i);\n this._buffer[relativeIndex] = callback(this._buffer[relativeIndex], i, length);\n i += 1;\n }\n }\n }\n });\n\n return Ring;\n }());\n\n var ring = new Ring(10, 1);\n\n console.log({\n 0: ring,\n 1: ring.length\n });\n}());\n</code></pre>\n\n<p>On <a href=\"http://jsfiddle.net/Xotic750/UeMCC/\" rel=\"nofollow\">jsfiddle</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:45:45.607", "Id": "43964", "Score": "0", "body": "Thank you for your tips, i just found out about Object.defineProperty a few days ago and i was considering using it since it gives me the oportunity to set the writable descriptor on object properties. I'm not very keen of the ternary operator :? either but in that one case i think it improves readability while also saving a bit of typing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T21:47:33.633", "Id": "44002", "Score": "0", "body": "No problem, I have added a quick conversion that will hopefully give you a starter. Good luck." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T11:04:53.357", "Id": "28160", "ParentId": "28138", "Score": "1" } } ]
{ "AcceptedAnswerId": "28160", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:28:07.373", "Id": "28138", "Score": "3", "Tags": [ "javascript", "performance", "circular-list" ], "Title": "Circular Buffer on a typed Float32Array" }
28138
<p>I have three different types of XML files (structure) which I would like to import into a database.</p> <p>Every hour a cronjob calls my import.php with a specific XML file type as a parameter.</p> <p>The import script includes a bootstrap.php (AutoLoader, Setup Doctrine DB Connection) and puts all files matching the name convention of this type in an array and calls a static method for this class.</p> <p>Simplified code (import.php):</p> <pre><code>&lt;?php require_once("bootstrap.php"); function getFiles($pattern) { $fileList = NULL; foreach( glob('xml/*'.$pattern.'.xml') as $filename ) { $fileList[] = $filename; } return $fileList; } switch($xmlType) { case "TypeA": TypeA::importFeed(getFiles($xmlType)); break; case "TypeB": TypeB::importFeed(getFiles($xmlType)); break; case "TypeC": TypeC::importFeed(getFiles($xmlType)); break; } </code></pre> <p>Currently, the classes (<code>TypeA</code>, <code>TypeB</code>, <code>TypeC</code>) contain no other method except <code>importFeed</code>.</p> <p>Inside <code>importFeed</code>, only 2 things are equal in each class:</p> <ol> <li>Getting the <code>entityManager</code> (Doctrine) by calling <code>$em = app::getEm();</code></li> <li>Convert XML into <code>SimpleXMLElement</code> using my parser class <code>$feedObj = Parser::xmlToObject($xmlFile);</code></li> </ol> <p>Everything else in <code>importFeed</code> differs from class to class because of the different XML types. Only a few tasks repeating e.g. check if an entity already exists in the database.</p> <p>My first thought was creating a Helper class for this and some other repeating tasks I also need outside the import-script in this application.</p> <p>But I'm not sure if this helper class should be a normal, "static" or "singleton" class.</p> <p>The helper-methods doesn't need a specific object instance so static-methods would a good choice. But in some methods I need access to the DB and I do not wont to call <code>app::getEm();</code> in every method because I don't think this is a good/clean solution.</p> <p>At this point I challenged my current application design and read a lot of articles about this. The point is the application is not large and it should not be so using a Framework like Symfony is completely exaggerated - nonetheless I want a good solution.</p> <p>All three classes (TypeA/B/C) have the same function that looks like this:</p> <pre><code>public static function importFeed($xmlFiles) { $em = \App::getEm(); foreach($xmlFiles as $xmlFile) { try { $feedObj = Parser::xmlToObject($xmlFile); ...import xml data to database - differns ... } catch(\Exception $e) { .... } } } </code></pre> <p>Only the "..." area differs a lot because of the different XML structure but this part isn't really important for the question. In short: A Doctrine entity is created and many <code>setAttributeX</code> methods are called and in the end <code>$em-&gt;flush()</code>.</p> <p>My feeling tells me that it is not right to have three classes with only static methods to import XML files, but I can't find a better solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:45:55.047", "Id": "43919", "Score": "1", "body": "create an abstract class that is then extended by TypA, TypeB,..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:44:53.023", "Id": "43963", "Score": "0", "body": "There are no methods that I need in all classes (TypeA, TypeB, TypeC) therefore I could better use a Interface to ensure all needed function of a \"Import\"-Class are implemented. But I think the major problem is the \"3 Classes with only static methods\"-Solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:23:37.953", "Id": "43969", "Score": "1", "body": "I agree with @Pinoniq (called him out since you didn't) If you make a abstract marker class that is extended by typeA, B,C you can make a few methods that all 3 share in the marker class. And you can make a GetXMLType (name??) that returns the correct instance of the Parser you need. That would clean up your code a bunch. Any common methods can be made in the Abstract class so you don't repeat your self." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:54:58.807", "Id": "43975", "Score": "0", "body": "@Robert Snyder Thanks for your feedback. The \"problem\" is that no methods are shared between the three classes. It's too individually. The only repeating tasks I would like to have in a Helper-Class because I also need them outside the import functionality. I thought my approach using three classes with only static methods was completly wrong but If i understand you correctly it's nothing wrong with it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T14:00:45.507", "Id": "43976", "Score": "0", "body": "@Manuel Personally I try to avoid static methods since they make me right bad code. But that's because I tend to get very lazy sometimes. I also alway use dependency injection because that makes unit tests a lot easier. Just my 5 cents" } ]
[ { "body": "<p>I would go somewhere in the lines of the following code:\n\n\n<pre><code>abstract class ObjectImporter {\n\n protected $em;\n\n public function __construct($em) {\n $this-&gt;em = $em;\n }\n\n abstract public function import($object);\n}\n\nclass TypeAImporter extends ObjectParser {\n\n public function __construct($em) {\n parent::__construct($em);\n }\n\n public function import($object) {\n #do your import magic\n }\n}\n\nclass XmlImporter {\n\n private $importer;\n\n public function __construct($importer) {\n $this-&gt;importer = $importer;\n }\n\n public function import($files) {\n foreach ( $files as $file ) {\n $obj = Parser::xmlToObject($file);\n $this-&gt;importer-&gt;import($obj);\n }\n }\n}\n\nswitch ( $xmlType ) {\n\n case 'TypeA':\n $importer = new XmlImporter(new TypeAImporter(\\App::getEm()));\n break;\n}\n\n$importer-&gt;import($files);\n</code></pre>\n\n<p>Some notes: the code is not ideal (names aren't that good imo) and I don't like the Parser::xmlToObject method. The Parser should be injected into the XmlImporter class aswel. This way its easier tested and you can also very easily change the xml Parser.</p>\n\n<p>I hope the code is of any use.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T14:33:32.563", "Id": "43977", "Score": "0", "body": "Thank you for this example. Looks much tidier as mine. Although I actually do not need a individually class instance for this task because the processing is object independently but it seems more a question of what harms a instance instead of whats the benefit. Or I'm wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T15:29:57.717", "Id": "43982", "Score": "0", "body": "It's more a question of how easy do you want to be able to run Tests on your code. At my work everything gets unit tested. even if I remove some white-spaces. That is why I use dependency injection instead of using static classes or using the 'new' operator inside a class. More info here: http://stackoverflow.com/questions/1580641/when-to-use-dependency-injection for instance. So the benefit is the ability to write better an smaller tests ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:58:28.793", "Id": "28164", "ParentId": "28140", "Score": "1" } } ]
{ "AcceptedAnswerId": "28164", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T17:34:01.367", "Id": "28140", "Score": "2", "Tags": [ "php", "design-patterns", "xml" ], "Title": "Finding the right structure for my application" }
28140
<p>I'm new to Java right now. Here is my following code snippet:</p> <pre><code>for(int i = (SelectedAssets.size()-1); -1 &lt; i; i--){ Double supportTime = 0; //Date class must be used. Cannot replace with another class Date oDate=SelectedAssets[i].Entitlement_End_Date__c; Date dateDifference = oDate.daysBetween(date.today()); /**************************************************************************** If the number of days between Entitlement End Date and Todays date is a positive number, then that means the support given to client is expired since entitlement end date happened before todays date. *****************************************************************************/ if(dateDifference&gt;0){ supportTime=((dateDifference/365.00)); //If the number of days is greater than one year, I want //to find out exactly the amount of days it's gone over in decimals. if(supportTime&gt;1){ supportTime=1; supportTime+=(date.today().daysBetween(TheEndDate)/365.00); } } else{ //if it hasn't gone over a year, find out how much time has elapsed in years. supportTime=oDate.daysBetween(TheEndDate)/365.00; } } </code></pre> <p>Is there any redundancies anywhere that I'm overlooking? Is there an easier way of doing this with fewer lines?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T19:39:05.300", "Id": "43924", "Score": "2", "body": "Please reformat and indent your code. Good code formatting is very important for readability and it's an important habit to take care of it. Also wrap lines to some reasonable column count (such as 72). Scrolling to the right to read comments and back makes reading difficult and makes one lose track. See [Is inconsistent formatting a sign of a sloppy programmer?](http://programmers.stackexchange.com/q/149401/61231) (I'm not implying any sloppiness at your side. The answers provide valuable information on the subject.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:38:13.217", "Id": "43927", "Score": "0", "body": "As I was commenting and rewriting the code, I realised that my understanding of the current code was wrong because of the wrong formatting. Please fix this before anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T21:13:37.243", "Id": "43930", "Score": "0", "body": "Hi, I think I fixed the formatting issues. Hope it helps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T04:17:13.477", "Id": "43939", "Score": "0", "body": "asking for fewer lines of code might be a little difficult without a little more context. Maybe we could see the entire method instead of just this one function. Anyway I feel that this for loop needs to get cleaned up a bit, but more context would help to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:33:50.453", "Id": "43972", "Score": "2", "body": "I am wrong in saying that this piece of code doesn't do anything at the moment ? (Just updating variables with a scope limited to the for-loop)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:51:14.513", "Id": "43973", "Score": "0", "body": "Imo, your code is ok like this. Shorter != better, case in point (your entire if statement on a single line): supportTime = dateDifference <= 0 ? oDate.daysBetween(TheEndDate)/365.00 : (dateDifference/365.00) <= 1 ? (dateDifference/365.00) : 1 + (date.today().daysBetween(TheEndDate)/365.00);" } ]
[ { "body": "<p>This can also be written as below (avoid magic numbers, use private helper methods to make your code more clearer to understand):</p>\n\n<pre><code>private static final double NO_OF_DAYS_IN_AN_YEAR = 365.00;\n..........\nfor(SelectedAsset asset : selectedAssets){\n double supportTime = 0.0;\n if(isSupportExpiredForAsset(asset)&gt;0){\n supportTime = convertDaysToYear(getDaysBetweenTodayAndAssetEntitlementEndDate(asset));\n if(supportTime&gt;1){\n supportTime=1+convertDaysToYear(date.today().daysBetween(TheEndDate));\n }\n }else{\n supportTime=convertDaysToYear(asset.Entitlement_End_Date__c.daysBetween(TheEndDate));\n }\n}\n\nprivate int getDaysBetweenTodayAndAssetEntitlementEndDate(SelectedAsset asset){\n return asset.Entitlement_End_Date__c.daysBetween(date.today());\n}\n\nprivate double convertDaysToYear(int days){\n return days/NO_OF_DAYS_IN_AN_YEAR\n}\n\nprivate boolean isSupportExpiredForAsset(SelectedAsset asset){\n return getDaysBetweenTodayAndAssetEntitlementEndDate(asset)&gt;0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T14:05:32.600", "Id": "44037", "Score": "0", "body": "Just my 2 cent, but I think it would be better to use some comments instead of super-specific and verbose private method that are used only once and make the whole code harder to follow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T13:10:52.623", "Id": "44158", "Score": "0", "body": "I agree with specific naming. If the name has to be a mile long for clarity i'd prefer that. My eyes get to read his code like a book. I don't have to go to the private helper methods and read them because I already know what they do. They *MIGHT* be able to be reworded, but from what I'm reading it is all good." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T18:21:35.320", "Id": "28174", "ParentId": "28142", "Score": "1" } }, { "body": "<p>First thing would be to scan your code with <a href=\"http://www.sonarsource.com/\" rel=\"nofollow noreferrer\">Sonar</a>. This will hit all the formatting complaints, magic numbers, etc.. Likewise, set up your IDE to auto format on save action to save lots of time fixing those Sonar findings.</p>\n\n<p>The next thing to simplify would be to use <a href=\"https://stackoverflow.com/questions/1404210/java-date-vs-calendar\">Calendar instead of Date</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T20:54:39.040", "Id": "28178", "ParentId": "28142", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T18:14:30.563", "Id": "28142", "Score": "1", "Tags": [ "java", "beginner", "datetime" ], "Title": "Support entitlement date check for customer assets" }
28142
<p>My old script: <a href="https://codereview.stackexchange.com/questions/27510/does-my-login-script-contain-any-exploitable-holes">Exploitable holes in login script</a></p> <p>Have I improved?</p> <p>I've wrote this script today, by listening to many many suggestions from my last login script thread above.</p> <p>How secure is my script? What would you suggest me to change in my script to make it more secure? Any problems? (not 100% tester, but I haven't seen any bugs so far).</p> <p><strong>Member.class.php:</strong></p> <pre><code> /** * Member.class * * Handling everything related to members * * @Author Jony &lt;artemkller@gmail.com&gt; &lt;www.driptone.com&gt; **/ Class Member { /** * Properties **/ private $pdo = null; private $db; private $hasher; /** * Connect to the database **/ function __construct() { $this-&gt;db = new Database(); $this-&gt;hasher = new Hash(); $this-&gt;pdo = $this-&gt;db-&gt;connect(); } /** * Method login * * Logs the user in securly * * @param username The entered username * @param password The entered password * @param ip Client's ip * * @return boolean (Login successed or not). **/ public function login($username, $password, $ip) { // Query to fetch from login attempts $query = $this-&gt;pdo-&gt;prepare("SELECT * FROM login_attempts WHERE ip_address = :ip"); $query-&gt;execute(array(":ip" =&gt; $ip)); // Fetching from login attempts. $fetch = $query-&gt;fetch(PDO::FETCH_ASSOC); // If the username exists in the database.. if ($this-&gt;db-&gt;countRows("users", array("username" =&gt; $username)) == 1) { // Hashed password using our hashing class. $password = $this-&gt;hasher-&gt;secureHash($password); // Checking if user is blocked. if ($fetch['blocked'] != 1) { // Checking if user has used less than 6 attempts. if ($fetch['attempts'] &lt; 6) // Checking if the entered username and hashed password are matching the ones in the table. if ($this-&gt;db-&gt;countRows("users", array("username" =&gt; $username, "password" =&gt; $password)) == 1) { // Match found, clear login history. $this-&gt;clearHistory($ip); // Everything works fine, return true. return true; } else { // Updating attempts count (+1), if not exists, it will insert it. $this-&gt;updateAttempts($ip); // Throwing an error. throw new exception ("Details are incorrect."); // Not working, return false. return false; } } else { // Updating attempts count (+1), if not exists, it will insert it. $this-&gt;updateAttempts($ip); // Throwing error.. throw new exception ("You are blocked!"); } } else { // Updating attempts count (+1), if not exists, it will insert it. $this-&gt;updateAttempts($ip); // Throwing error again.. throw new exception ("You are blocked."); } } else { // Checking if attempts count is less than 6 if ($fetch['attempts'] &gt; 6) { // Updating attempts count (+1), if not exists, it will insert it. $this-&gt;updateAttempts($ip); // Throw an error.. throw new exception ("You're blocked."); } else { // Updating attempts count (+1), if not exists, it will insert it.. $this-&gt;updateAttempts($ip); //Throwing an error again. throw new exception ("Details are incorrect."); } // Updating attempts count (+1), if not exists, it will insert it. $this-&gt;updateAttempts($ip); // Not working, return false.. return false; } } /** * Method loginCookie * * Validating the remember me cookie * * @param hash The value of the cookie (Hashed name). * @return boolean (If hash matching, works). **/ public function loginCookie($hash) { // Checking if there is a row with the same hash as the remember me cookie. if ($this-&gt;db-&gt;countRows("users", array("hashed_name" =&gt; $hash)) == 1) { // Worked, return true. return true; } else { // Didn't work, throw an error and return false.. throw new exception ("An error has occured."); return false; } } /** * Method getNameAfterHash * * Gets the name of the hashed name (for cookie). * * @param hash The hashed name. * @return String the name. **/ public function getNameAfterHash($hash) { // Checks if the hash is available.. if ($this-&gt;db-&gt;countRows("users", array("hashed_name" =&gt; $hash)) == 1) { /** * Fetching from the table, basically fetching the column `username` **/ $query = $this-&gt;pdo-&gt;prepare("SELECT * FROM users WHERE hashed_name = :hash"); $query-&gt;execute(array(":hash" =&gt; $hash)); $fetch = $query-&gt;fetch(PDO::FETCH_ASSOC); // Returnign the fetches column value. return $fetch['username']; } else { // Not working to be honest, throw error. throw new exception ("ERROR!"); } } /** * Method logout * * Pretty useless, but it checks if the name is in the database. * * @param name Session name. * @return boolean **/ public function logout($name) { // Checking if there is a row with that username. if ($this-&gt;db-&gt;countRows("users", array("username" =&gt; $name)) == 1) { // Working return true; } else { // Not working. return false; } } /** * Method register * * Just for testing **/ public function register($name, $password) { $query = $this-&gt;pdo-&gt;prepare("SELECT * FROM users WHERE username = :user"); $query-&gt;execute(array(":user" =&gt; $name)); if (!$query-&gt;rowCount()) { $hashedName = $this-&gt;hasher-&gt;secureHash($name); $password = $this-&gt;hasher-&gt;secureHash($password); $this-&gt;db-&gt;insert("users", array("username" =&gt; $name, "password" =&gt; $password, "hashed_name" =&gt; $hashedName)); } else { throw new exception("User exists"); } } /** * Method clearLimits * * Clear user login fails attempts count * * @param ip The IP address of the client. **/ public function clearLimits($ip) { // Query to fetch from login_attempts table. $query = $this-&gt;pdo-&gt;prepare("SELECT * FROM login_attempts WHERE ip_address = :ip"); $query-&gt;execute(array(":ip" =&gt; $ip)); // Fetching from login_attempts $fetch = $query-&gt;fetch(PDO::FETCH_ASSOC); /* If fails count is less than 6, block for 10 minutes. */ if ($fetch['attempts'] &lt; 6) { $time = "10 MINUTE"; } /* If fails count is less than 11, block for 1 hour. */ else if ($fetch['attempts'] &lt; 11) { $time = "1 HOUR"; } /* If fails count is less than 21, block for 1 day. */ else if ($fetch['attempts'] &lt; 21) { $time = "1 DAY"; } /* If fails count is greater than 21, block for 1 week. */ else if ($fetch['attempts'] &gt; 21) { $time = "7 DAY"; } // Updating the results now, setting INTERVAL as @var Time. $update = $this-&gt;pdo-&gt;prepare("UPDATE login_attempts SET blocked = 0, date = NOW() WHERE ip_address = :ip AND date &lt; DATE_SUB(NOW(), INTERVAL $time)"); $update-&gt;execute(array(":ip" =&gt; $ip)); // This is the default delete query, it will occur only for ips that their date didnt update for 1 day atleast. $delete = $this-&gt;pdo-&gt;prepare("DELETE FROM login_attempts WHERE date &lt; DATE_SUB(NOW(), INTERVAL 1 DAY) AND ip_address = :ip"); } /** * Method clearHistory * * Clears ALL login history off an ip, deletes his row. * * @param ip The clients ip **/ private function clearHistory($ip) { // Deleting process... $delete = $this-&gt;pdo-&gt;prepare("DELETE FROM login_attempts WHERE ip_address = :ip"); $delete-&gt;execute(array(":ip" =&gt; $ip)); } /** * Method updateAttempts * * Checks if theres a row of attempts, if not, insert it. Else add +1 to attempts. * * @param ip The clients ip **/ private function updateAttempts($ip) { // Checking if row exists. if ($this-&gt;db-&gt;countRows("login_attempts", array("ip_address" =&gt; $ip)) == 1) { // Add +1 to attempts and update time to NOW(). $update = $this-&gt;pdo-&gt;prepare("UPDATE login_attempts SET attempts = attempts + 1, date = NOW() WHERE ip_address = :ip"); $update-&gt;execute(array(":ip" =&gt; $ip)); } else { // Not found, insert new row. $this-&gt;db-&gt;insert("login_attempts", array("ip_address" =&gt; $ip, "attempts" =&gt; 1)); } } } </code></pre> <p><strong>Hash.class.php:</strong></p> <pre><code>/** * Hash.class * * Hashing passwords/names * * @Author Jony &lt;artemkller@gmail.com&gt; &lt;www.driptone.com&gt; **/ Class Hash { private $globalSalt = "F926E3GGmv6Iy3kYj411Sq6J4A8L885co168UK4I5q1128chk685dTny21518s2"; public function secureHash($toHash) { $salt = hash("SHA512", $toHash."".$this-&gt;globalSalt); return self::hashName($salt); } private static function hashName($salt) { $salt = hash("SHA512", $salt); $final = hash("SHA512", $salt); return hash("SHA512", $final); } } </code></pre> <p><strong>login.php:</strong></p> <pre><code>&lt;?php /** * - LOGIN * - The login page. **/ include ("includes/config.inc.php"); /** * Creating objects. **/ $member = new Member(); $hasher = new Hash(); $member-&gt;clearLimits($_SERVER['REMOTE_ADDR']); if (!isset($_SESSION['user'])) { if(!isset($_COOKIE['remember_me'])) { if (isset($_POST['submit'])) { try { if ($member-&gt;login($_POST['username'], $_POST['password'], $_SERVER['REMOTE_ADDR'])) { if (isset($_POST['remember'])) { setcookie("remember_me", $hasher-&gt;secureHash($_POST['username']), time()+604800); } $_SESSION['user'] = $username; session_regenerate_id(); header("Location: index.php"); } } catch (exception $t) { echo $t-&gt;getMessage(); } } } else { try { if ($member-&gt;loginCookie($_COOKIE['remember_me'])) { $_SESSION['user'] = $member-&gt;getNameAfterHash($_COOKIE['remember_me']); header("Location: index.php"); } } catch (exception $e) { echo $e-&gt;getMessage(); } } } else { header("Location: index.php"); } ?&gt; &lt;html&gt; &lt;form action="login.php" method="POST"&gt; &lt;input type="text" name="username"&gt; &lt;input type="password" name="password"&gt; &lt;input type="checkbox" name="remember"&gt; &lt;input type="submit" name="submit"&gt; &lt;/form&gt; &lt;/html&gt; </code></pre> <p><strong>index.php including the logout method:</strong></p> <pre><code>include ("includes/config.inc.php"); $member = new Member(); if (isset($_SESSION['user'])) { if(isset($_GET['logout'])) { try { if ($member-&gt;logout($_SESSION['user'])) { setcookie("remember_me", "", time()-1000000); unset($_SESSION['user']); session_regenerate_id(); header("Location: login.php"); } } catch (exception $r) { echo $r-&gt;getMessage(); } } echo "hello, ". $_SESSION['user'], ' &lt;a href="?logout"&gt;Do you wish to log out&lt;/a&gt;? '; } else { header("Location: login.php"); } </code></pre>
[]
[ { "body": "<p>Try to <a href=\"https://security.stackexchange.com/questions/25585/is-my-developers-home-brew-password-security-right-or-wrong-and-why\">avoid creating your own hashing</a> function. Instead (if your PHP version allows), use the built in <a href=\"http://us2.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\"><code>password_hash()</code></a> and <code>password_verify()</code> functions.</p>\n\n<p>Your method of gaining the IP address is a start, but I think <a href=\"http://www.virendrachandak.com/techtalk/getting-real-client-ip-address-in-php-2/\" rel=\"nofollow noreferrer\">it could be more complete</a>.</p>\n\n<p>If you can, avoid using <code>echo $r-&gt;getMessage();</code> as it may produce information a malicious user could exploit. Control the output given to the user.</p>\n\n<p>In <strong>Member.class.php</strong> I see a lot of nested <code>if</code>s. <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Try to flatten your code</a> for greater readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T21:09:33.993", "Id": "42466", "ParentId": "28145", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T19:50:07.000", "Id": "28145", "Score": "1", "Tags": [ "php", "object-oriented", "security" ], "Title": "Are there any possible exploit holes in this login script?" }
28145
<p>I'm developing an Android app to view C-programs. I wanted to give a simple color scheme to the text which is stored in database, retrieved as a string and then passed on to the textview.</p> <p>The code I have written assigns the green color to header file declarations and brackets, the blue color is assigned to <code>numbers</code>, <code>printf</code>, <code>scanf</code>, and the red color is assigned to datatypes such as <code>int</code>, <code>char</code>, <code>float</code>.</p> <p>It is, however, very inefficient. Before applying this color scheme, my app was displaying the textview activity instantly. Now, depending on the length of the C-programs, it takes up to 4 to 5 seconds, which is really poor performance.</p> <p>It takes one keyword at a time, then iterates the complete text of textview looking for that particular keyword only and changes its color, sets the text again. Thus, it traverses text of the entire textview 29 times as I have defined 29 keywords in String arrays (namely <code>keywordsgreen</code>, <code>keywordsblue</code>, <code>keywordsred</code>).</p> <p>The activity's <code>onCreate()</code> function:</p> <pre><code>textView = (TextView) findViewById(R.id.textView1); textView.setText(programtext); textView.setBackgroundColor(0xFFE6E6E6); //The problem starts here String [] keywordsgreen={"#define","#include","stdio.h","conio.h","stdlib.h","math.h","graphics.h","string.h","malloc.h","time.h","{","}","(",")","&lt;","&gt;","&amp;","while ","for "}; for(String y:keywordsgreen) { fontcolor(y,0xff21610B); } String [] keywordsred={"%d","%f","%c","%s","int ","char ","float","typedef","struct ","void "}; for(String y:keywordsred) { fontcolor(y,0xFFB40404); } String [] keywordsblue={"printf","scanf","\n","getch","0","1","2","3","4","5","6","7","8","9"}; for(String y:keywordsblue) { fontcolor(y,0xFF00056f); } </code></pre> <p>The <code>fontcolor()</code> function:</p> <pre><code>private void fontcolor(String text,int color) { Spannable raw=new SpannableString(textView.getText()); int index=TextUtils.indexOf(raw, text); while (index &gt;= 0) { raw.setSpan(new ForegroundColorSpan(color), index, index + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); index=TextUtils.indexOf(raw, text, index + text.length()); } textView.setText(raw); } </code></pre>
[]
[ { "body": "<p>I think the right way to do would be to have a map associating keywords to their color and them to go through your text, split it in tokens and for each token, apply the color if relevant.</p>\n\n<p>This wouldn't be as good as a real syntax hilighter but it would probably work as good as your current code with better performances.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:29:34.547", "Id": "43926", "Score": "0", "body": "I'm a beginner in java.Could you please help me out with some sample code which shows how to do what you've written above ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:19:07.470", "Id": "28147", "ParentId": "28146", "Score": "1" } }, { "body": "<p>First of all, some side notes:</p>\n\n<ol>\n<li><p>In your <code>keywordsgreen</code> array, you're checking for very specific library names. But you also check for <code>#include</code> and <code>#define</code>. So what if I include <code>&lt;stdlib.h&gt;</code>? Your current code would search the text, find <code>#include</code>, turn it green, then search again, find <code>&lt;stdlib&gt;</code> and turn that green. But the whole line might as well be green. Instead, just look for the <code>#</code> symbol at the absolute start of the line (it would take a little more logic, of course). That way, you eliminate most of the <code>keywordsgreen</code> array.</p></li>\n<li><p>Also, you're setting the text every single time you edit a single word. You don't need to do that. Just keep one <code>SpannableString</code> and pass that around, setting the <code>textView</code> to that <em>all the way at the end of the function</em>.</p></li>\n<li><p>I don't think this should be that slow. It's not a very good solution, but even for a 300-line source file, I can't imagine it would take 5 seconds. Put all that in a new thread and see what happens.</p>\n\n<p>Example:</p>\n\n<pre><code>Thread colorTextThread = new Thread(new Runnable(){\npublic void run(){ \n //Put all that searching code in here\n}//end of run\n});\ncolorTextThread.start();\n</code></pre></li>\n</ol>\n\n<p>You put it on a new thread because the UI thread is super slow. Remember, though, if you want to change the textView on a separate thread, you have to use the <code>runOnUiThread()</code> function.</p>\n\n<p>I'll add more later if no one tells you how to make the code faster. I've got to go at the moment, sorry.</p>\n\n<p>EDIT:</p>\n\n<p>After looking at your code again, I can't see a way to make it <em>faster</em>. The most important things you can do is to do the search on the \"programText\" variable you're passing to <code>textView</code>. That variable holds all the information you need, so you should manipulate <em>that</em>, and <em>then</em> pass it to <code>textView.setText()</code>. That way, you never have to call <code>getText()</code>, which means you can do all of your text processing on a separate thread. If it runs slow even on a separate thread, then yes, your code is very slow. Otherwise, problem solved for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:40:59.740", "Id": "28148", "ParentId": "28146", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T20:02:52.920", "Id": "28146", "Score": "4", "Tags": [ "java", "optimization", "performance", "android" ], "Title": "Setting color of specific keywords in a textview" }
28146
<p>To implement an insertion sort that sorts an array with optional block to determine sorting order, how can I improve this code? (Seeking best practices and code correctness)</p> <pre><code>def custom_insertion_sort(arr) for i in (1..arr.length-1) curr = arr[i] compare = i-1 if block_given? sorted = yield arr, compare, curr else sorted = arr[compare] &lt; curr end while compare &gt;= 0 &amp;&amp; sorted arr[compare+1] = arr[compare] compare -= 1 if block_given? sorted = yield arr, compare, curr else sorted = arr[compare] &lt; curr end end arr[compare+1] = curr end arr end </code></pre>
[]
[ { "body": "<ol>\n<li><p>Your block usage <code>yield arr, compare, curr</code> is rather weird:</p>\n\n<pre><code>custom_insertion_sort(array){ |_, i, j| _[i].abs &gt; j.abs }\n</code></pre>\n\n<p>I would do <code>yield arr[compare], curr</code>:</p>\n\n<pre><code>naki_insert_sort(array){ |i, j| i.abs &gt; j.abs }\n</code></pre></li>\n<li><p>You may use <code>...n</code> syntax instead of <code>..n-1</code></p></li>\n<li><p>You are sorting inplace, operating with an array like with a memory pointer, so you don't have to return <code>arr</code> from the function.</p></li>\n<li><p>Instead of writing comparision code twice you can either define <code>lambda</code> or put it just inside <code>while</code> condition.</p></li>\n</ol>\n\n<p>And after a bit more golf I've got this:</p>\n\n<pre><code>def naki_insert_sort arr\n for i in (1...arr.length)\n curr = arr[compare = i]\n while 0 &lt;= (compare -= 1) &amp;&amp; ( block_given? ?\n yield(arr[compare], curr) :\n arr[compare] &lt; curr\n )\n arr[compare + 1] = arr[compare]\n end\n arr[compare + 1] = curr\n end\nend\n</code></pre>\n\n<p>But looks like Insertion sort and Ruby don't actually suit each other, because using indexes isn't functional.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T14:39:09.927", "Id": "43979", "Score": "0", "body": "\"You are sorting inplace, operating with an array like with a memory pointer, so you don't have to return arr.\". Indeed, but core Ruby methods tend to do this (on the other hand Python does not, to emphasise that they are in-place operations)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T12:26:07.717", "Id": "28162", "ParentId": "28152", "Score": "1" } } ]
{ "AcceptedAnswerId": "28162", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T01:11:10.500", "Id": "28152", "Score": "1", "Tags": [ "ruby", "sorting", "insertion-sort" ], "Title": "Implementation of insertion sort in Ruby, code correctness" }
28152
<pre><code>boolean isBalance(Node root) { if (root == null ) return true; return Math.abs(getHeight(root.left)-getHeight(root.right)) &lt;=1; } int getHeight(Node N) { int L = 0; int R = 0; if (N.L!=null) L = getHeight(N.L); if (N.R!=null) R = getHeight(N.R); return 1 + Max(L,R); } </code></pre> <p>I believe that the run time of my algorithm is O(N); But one of my friend told this runs for O(N^2);</p> <p>My question is whether I am wrong or right since I believe I visit each node once. SO for that its O(N)... </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T11:23:59.863", "Id": "43957", "Score": "2", "body": "Note that `isBalanced` will return `true` if the height of the two branches is (near) equal even if the branches themselves are not balanced. Is this intentional?" } ]
[ { "body": "<p>Your <code>getHeight</code> method could be simpler (and more correct) if it was handling the <code>null</code> case.</p>\n\n<pre><code>int getHeight(Node N) {\n if (N==null) return 0\n return 1 + Max(getHeight(N.L),getHeight(N.R));\n}\n</code></pre>\n\n<p>Also, I think you should have a read at <a href=\"https://stackoverflow.com/questions/742844/how-to-determine-if-binary-tree-is-balanced\">this quite similar question</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T13:02:30.490", "Id": "28163", "ParentId": "28159", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T10:47:15.667", "Id": "28159", "Score": "1", "Tags": [ "java", "algorithm", "tree" ], "Title": "Complexity Of Determining Tree is balanced?" }
28159
<p>How would I write a foreach statement that includes both of these statement together</p> <pre><code>//clear textboxes foreach (Control c in panel1.Controls.OfType&lt;TextBox&gt;()) { if (!string.IsNullOrEmpty(c.Text)) { c.Text = ""; } } //clear price label text foreach (Control c in panel1.Controls.OfType&lt;Label&gt;()) { if ((string)c.Tag == "Clearable") { c.Text = ""; } } </code></pre>
[]
[ { "body": "<p>You could write it in 1 loop but you'll still need separation of logic for each type of Control:</p>\n\n<pre><code>foreach(Control c in panel1.Controls)\n{\n if(c is TextBox)\n {\n var tb = c as TextBox;\n if(!String.IsNullOrEmpty(tb.Text))\n tb.Text = \"\";\n }\n\n if(c is Label)\n {\n var l = c as Label;\n if(l.Tag != null &amp;&amp; l.Tag.ToString() == \"Clearable\")\n l.Text = \"\";\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T05:33:02.217", "Id": "44138", "Score": "0", "body": "I think using `is` and then `as` is bad code style. You essentially cast object twice. It is better to cast with `as` and then check for `null`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T15:10:58.887", "Id": "28166", "ParentId": "28165", "Score": "3" } }, { "body": "<p>Working off of Abbas answer, to remove the if statement, you could have an overridden method to deal with each one.</p>\n\n<pre><code>private void ClearControl(Control control)\n{\n ProcessControl((dynamic)control);\n}\n\nprivate void ProcessControl(TextBox textbox)\n{\n if(!String.IsNullOrEmpty(tb.Text))\n tb.Text = \"\";\n}\n\nprivate void ProcessControl(Label label)\n{\n if(l.Tag != null &amp;&amp; l.Tag.ToString() == \"Clearable\")\n l.Text = \"\";\n}\n\nprivate void ProcessControl(Control control)\n{\n // Nothing to do\n}\n\n// Calling code\n// if Controls is a list, than the ToList() does not need to be called.\npanel1.Controls.ToList().ForEach(ClearControl);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T19:09:08.897", "Id": "43995", "Score": "0", "body": "I would probably use `dynamic` as little as possible, that is `private void ClearControl(Contol control)` and `ProcessControl((dynamic)control);`. That way, you don't have to check the type manually." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T21:41:53.630", "Id": "44001", "Score": "0", "body": "@svick I tried it that way. The problem is by making it a control only the ProcessControl(Control control) method is called. By making it a dynamic, a little bit of reflection is used to call the correct method. I will take that little hit in performance in a windows app to save the if/ifelse/else statements that will pop-up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:31:58.220", "Id": "44010", "Score": "0", "body": "I'm saying you should use `dynamic`, but use it later than you currently do. Notice the cast to `dynamic` in my prposed call to `ProcessControl()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T14:55:49.300", "Id": "44039", "Score": "0", "body": "Got it now. I got the two methods mixed up. I like your way, it gets rid of an extra if statement :) I made the change" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:42:53.850", "Id": "44049", "Score": "2", "body": "This answer is the bad practise i think. Creating a dummy method and using dynamic cast?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T21:55:27.887", "Id": "44132", "Score": "0", "body": "I my opinion, it is better than a method full of if/elses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T05:50:48.810", "Id": "44139", "Score": "0", "body": "I agree with Peter, this looks ugly to me. `if` on the other hand is a basic operator, there is nothing wrong with using it. Method full of if-elses (would not call a method with two `if`-s that, but oh well) is no good either, but it can be easily split into sub-methods by simple refactoring." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T16:29:09.373", "Id": "44180", "Score": "0", "body": "You guys are completely breaking one of the [SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) principles. To add a new control, you have to modify the original class, this pattern will allow you to add logic for other controls without having to modify the original class (closed for modification, open for extension). You can also now move this logic into their own classes, and make them into some kind of service. And for me, this coding style makes way more sense, and is much easier to read than a whole bunch of if/elses or switches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T05:39:44.970", "Id": "44342", "Score": "0", "body": "@Jeff Vanzella, again, if-else can be refacotred to support inheritance. The thing is however - there is a clear deep design issue with the application itself, if code such as this is needed, imho. Personally, i would not use your solution, nor will i use if-else's or w/e. Instead I would change the design of my UI, so that there is no `foreach` loops such as one in the original post to begin with :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T16:14:21.113", "Id": "28168", "ParentId": "28165", "Score": "2" } }, { "body": "<p>You can make a dictionary of the types that you want to handle and the functions to determine if they should be cleared:</p>\n\n<pre><code>var clear = new Dictionary&lt;Type, Func&lt;Control, bool&gt;&gt;();\nclear.Add(typeof TextBox, c =&gt; !String.IsNullOrEmpty(c.Text));\nclear.Add(typeof Label, c =&gt; (string)c.Tag == \"Clearable\");\n\n// clear controls\nforeach (Control c in panel1.Controls) {\n Func&lt;Control, bool&gt; f;\n if (clear.TryGetValue(c.GetType(), out f) &amp;&amp; f(c)) {\n c.Text = String.Empty;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:43:42.620", "Id": "44050", "Score": "0", "body": "Not bad but it can be slow as hell becouse of the reflection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T21:08:05.713", "Id": "44059", "Score": "0", "body": "@PeterKiss: What reflection?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T06:25:35.053", "Id": "44082", "Score": "0", "body": "c.GetType() is getting the type at runtime but ofcourse this overhead can be tagged with micro optimalization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T09:23:11.020", "Id": "44088", "Score": "1", "body": "@PeterKiss: That's not reflection. Getting the type of an object is a rather simple operation. Calling `Int32.ToString` for example takes a lot longer, and that is not generally considered \"slow as hell\"..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:43:49.933", "Id": "28188", "ParentId": "28165", "Score": "0" } }, { "body": "<p>The Control class it self has the Tag and Text properties no need additional separation.</p>\n\n<pre><code>foreach (Control c in panel1.Controls.Where(c =&gt; c is TextBox || (c.Tag is string &amp;&amp; (c.Tag as string) == \"Clearable\")))\n{\n c.Text = \"\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T21:12:59.360", "Id": "44060", "Score": "0", "body": "You would need to check if it's a label also, to have it do the same as the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T06:26:00.103", "Id": "44083", "Score": "0", "body": "True if it's really necessary." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T15:12:50.800", "Id": "28198", "ParentId": "28165", "Score": "1" } } ]
{ "AcceptedAnswerId": "28166", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T14:47:38.263", "Id": "28165", "Score": "1", "Tags": [ "c#", "winforms" ], "Title": "Foreach statement for two OfType<>" }
28165
<p>I was doing a standard problem of DP (dynamic programming) on SPOJ <a href="http://www.spoj.com/problems/EDIST/" rel="nofollow">Edit Distance</a> using Python. </p> <pre><code>t = raw_input() for i in range(int(t)): a,b = raw_input(),raw_input() r = len(a) c = len(b) x = [[0]*(c+1) for j in range(r+1)] for j in range(c+1): x[0][j] = j for j in range(r+1): x[j][0] = j for j in range(1,r+1): for k in range(1,c+1): if(b[k-1]!=a[j-1]): x[j][k] = min(x[j-1][k-1]+1,x[j-1][k]+1,x[j][k-1]+1) else: x[j][k] = min(x[j-1][k-1],x[j-1][k]+1,x[j][k-1]+1) print x[r][c] </code></pre> <p>The solution I have proposed is giving T.L.E (Time Limit Exceeded) even though I am using D.P. Is there any way to optimize it further in terms of time complexity or with respect to any feature of Python 2.7 such as input and output?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:09:26.710", "Id": "43986", "Score": "1", "body": "you can group these things into descriptive functions, moving some of the arguments into variables would help because they would give a hint to the intent of them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T22:46:46.090", "Id": "44004", "Score": "0", "body": "this works pretty quickly for me; are you testing it on very long strings?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T06:39:51.390", "Id": "44007", "Score": "0", "body": "@Stuart the max size of strings are 2000 characters....... I don't think we can improve the solution algorithmically but can we improve it with respect to some feature of python like fast input/output,etc.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:07:49.540", "Id": "44012", "Score": "0", "body": "ah. because they run it on the slow cluster and presumably use long strings. You could look in to improving the algorithm with something like `collections.deque` - I doubt the input/output methods will make much difference. But I see no one has solved this problem with python yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:14:55.397", "Id": "44013", "Score": "0", "body": "@stuart you can go to the best solutions for this problem and see that there are two python solutions..... how can we use **collections.deque** ????" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:53:08.647", "Id": "44014", "Score": "0", "body": "Sorry, yes, you're right. I noted with your solution that in each iteration you are only accessing a certain part of `x`, and that this could be done by manipulating a deque instead of a list of lists, and might be faster. I doubt it would bring the speed improvement you need though. The fastest solution is 2.65s which must be using a much better algorithm, probably with more use of special data types and libraries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T12:43:47.547", "Id": "44098", "Score": "0", "body": "Checking the forums, [psyco](http://psyco.sourceforge.net/) was available on spoj in the past but has now been disabled. This may make it hard to achieve times using Python that were possible up until last year." } ]
[ { "body": "<p>I don't think there is much to improve in terms of performance. However, you could make the code a whole lot more self-descriptive, e.g. using better variable names, and moving the actual calculation into a function that can be called with different inputs. Here's my try:</p>\n\n<pre><code>def min_edit_distance(word1, word2, subst=1):\n len1, len2 = len(word1), len(word2)\n med = [[0] * (len2 + 1) for j in range(len1 + 1)]\n for j in xrange(len1 + 1):\n for k in xrange(len2 + 1):\n if min(j, k) == 0:\n med[j][k] = max(j, k) # initialization\n else:\n diag = 0 if word1[j-1] == word2[k-1] else subst\n med[j][k] = min(med[j-1][k-1] + diag, # substite or keep\n med[j-1][k ] + 1, # insert\n med[j ][k-1] + 1) # delete\n return med[len1][len2]\n</code></pre>\n\n<p>Main points:</p>\n\n<ul>\n<li>move the actual calculation into a function, for reusability</li>\n<li>use more descriptive names instead of one-letter variables</li>\n<li>different calculations of minimum edit distance use different costs for substitutions -- sometimes <code>1</code>, sometimes <code>2</code> -- so this could be a parameter</li>\n<li>unless I'm mistaken the <code>min</code> in your <code>else</code> is not necessary; <code>x[j-1][k-1]</code> will always be the best</li>\n<li>the two initialization loops can be incorporated into the main double-loop. (Clearly this is a question of taste. Initialization loops are more typical for DP, while this variant is closer to the <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance#Definition\" rel=\"nofollow\">definition</a>.)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:08:21.643", "Id": "28223", "ParentId": "28167", "Score": "1" } }, { "body": "<p>I've solved that problem in java and c++ (<a href=\"http://www.spoj.com/ranks/EDIST/\" rel=\"nofollow\">2nd and 3th places</a> in best solutions category :) so I can compare the local and the remote execution time in order to see - how much faster should be your solution in order to pass.</p>\n\n<p>So, the local execution time of my java solution is 78 ms for the <a href=\"http://pastebin.com/5Q9h5dRK\" rel=\"nofollow\">such testcase</a> (10 pairs x 2000 chars), the robot's time is 500 ms, so my PC is ~6.5 times faster. Then the following python DP solution takes 3.6 seconds on my PC so, it would take ~23.5 seconds on the remote PC. So if the remote time limit 15 seconds, the following solution <strong>must be minimum ~ 1.56 times faster</strong> in order to pass. Ufff.... </p>\n\n<pre><code>import time\n\ntry:\n # just to see the Python 2.5 + psyco speed - 17 times faster than Python 2.7 !!!\n import psyco\n psyco.full()\nexcept:\n pass\n\ndef editDistance(s1, s2):\n if s1 == s2: return 0 \n if not len(s1):\n return len(s2)\n if not len(s2):\n return len(s1)\n if len(s1) &gt; len(s2):\n s1, s2 = s2, s1\n r1 = range(len(s2) + 1)\n r2 = [0] * len(r1)\n i = 0\n for c1 in s1:\n r2[0] = i + 1\n j = 0\n for c2 in s2:\n if c1 == c2:\n r2[j+1] = r1[j]\n else:\n a1 = r2[j]\n a2 = r1[j]\n a3 = r1[j+1]\n if a1 &gt; a2:\n if a2 &gt; a3:\n r2[j+1] = 1 + a3\n else:\n r2[j+1] = 1 + a2\n else:\n if a1 &gt; a3:\n r2[j+1] = 1 + a3\n else:\n r2[j+1] = 1 + a1\n j += 1\n aux = r1; r1 = r2; r2 = aux\n i += 1\n return r1[-1] \n\nif __name__ == \"__main__\": \n st = time.time()\n t = raw_input() \n for i in range(int(t)): \n a, b = raw_input(), raw_input()\n print editDistance(a, b)\n #print \"Time (s): \", time.time()-st\n</code></pre>\n\n<p>What I can say - It's very very hard or may be impossible to pass that puzzle using Python and DP approach (using java or c++ - peace of cake). Wait, wait - ask you - what about that two guys <a href=\"http://www.spoj.com/ranks/EDIST/lang=PYTH%202.7\" rel=\"nofollow\">that passed using python</a>? Ok, the answer is easy - they use something different. What's exactly? Something that <a href=\"http://google-web-toolkit.googlecode.com/svn-history/r8941/trunk/dev/core/src/com/google/gwt/dev/util/editdistance/MyersBitParallelEditDistance.java\" rel=\"nofollow\">I've used for java solution</a> I think. That stuff just blows away the competitors....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:36:27.337", "Id": "44175", "Score": "0", "body": "Thanks @cat_baxter i am not much familiar with java but i will try and look into the algo part of that java solution and try to implement it in python if possible ...." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:05:30.273", "Id": "28253", "ParentId": "28167", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T15:29:13.203", "Id": "28167", "Score": "2", "Tags": [ "python", "algorithm", "python-2.x", "time-limit-exceeded", "edit-distance" ], "Title": "Optimizing SPOJ edit distance solution" }
28167
<p>I was wondering if anyone would mind looking over my </p> <p><strong><a href="http://jsfiddle.net/L5w52/chec" rel="nofollow">JSFiddle</a></strong> ( contains html / css / js )</p> <p>and letting me know if this is best practice for the operation.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//&lt;!-- Services checkbox operations // i dont think this is the best way to do it but it works--&gt; $(function () { $(".service-slider").on("click", function () { // Disable all bottom level slides $(".slide").attr("disabled", false); // Uncheck all previous checked checkboxes $(".slide").prop('checked', false); // Disable top level checkboxs $(".service-slider").prop('checked', false); // Enable the selected checkbox to true $(this).prop('checked', true); //Disable bottom level slides $(".slide").attr("disabled", true); // Get selected id to enable all bottom level slides based on this var tron = "." + $(this).attr("id"); // Get the var and enable only those checkboxes $(tron).attr("disabled", false); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.service-desc,.service-price{ font-size:14px; } .dialog-main-label { font-weight:bold; } .ui-dialog .ui-dialog-buttonpane{ padding:0; } .service-type{ display:inline-block; width:25%; float:left; height:auto; } .service-type button{ width:100%; } .service-type input{ width:10px; } .service-type label{ font-size:16px; } #total{ position:absolute; bottom:20px; z-index:1000; width:670px; font-size:25px; } /* SLIDE TWO */ .slide { width: 80px; height: 20px; position: relative; margin:0; background:#ccc; -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); } .slide:after { content: ''; position: absolute; top: 10px; left: 14px; height: 2px; width: 52px; background: #111; -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); } .slide label { display: block; width: 22px; height: 13px; -webkit-transition: all .4s ease; -moz-transition: all .4s ease; -o-transition: all .4s ease; -ms-transition: all .4s ease; transition: all .4s ease; cursor: pointer; position: absolute; top: 4px; z-index: 1; left: 4px; -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); background: #fcfff4; background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 ); } .slide label:after { content: ''; position: absolute; width: 11px; height: 8px; background: #333; left: 2px; top: 2px; -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9); -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9); box-shadow: inset 0px 1px 1px rgba(0,0,0,1), 0px 1px 0px rgba(255,255,255,0.9); } .slide input[type=checkbox]:checked + label { left: 54px; } .slide input[type=checkbox]:checked + label:after { background: #00bf00; left:9px; } .slide input[type="checkbox"]{ display:none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Choose Your Service--&gt; &lt;div id="service-types"&gt; &lt;!-- Economay --&gt; &lt;div id="economy-service" class="service-type"&gt; &lt;label class="dialog-main-label"&gt;Economy&lt;/label&gt; &lt;div class="service-desc"&gt;24 - 96 hours&lt;/div&gt; &lt;div class="service-price"&gt;R78.09&lt;/div&gt; &lt;div class="slide"&gt; &lt;input type="checkbox" value="Economy" class="service-slider" id="economy-main" name="economy-main" /&gt; &lt;label for="economy-main"&gt;&lt;/label&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div id="Div3"&gt; &lt;label id="Label3"&gt;&lt;/label&gt; &lt;label&gt; Embassies&lt;br /&gt; R300.00 &lt;/label&gt; &lt;div class="slide"&gt; &lt;!-- Append top level checkbox id to the bottom level checkbox class so that there is a relationship in jquery ( _quickQuote.js) --&gt; &lt;input type="checkbox" value="Embassies" class="slide economy-main" id="eco-ckbx-embassies" name="eco-ckbx-embassies" /&gt; &lt;label for="eco-ckbx-embassies"&gt;&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Same Day --&gt; &lt;div id="same-day-service" class="service-type"&gt; &lt;label class="dialog-main-label"&gt;Same Day&lt;/label&gt; &lt;div class="service-desc"&gt;Get it today&lt;/div&gt; &lt;div class="service-price"&gt;397.40&lt;/div&gt; &lt;div class="slide"&gt; &lt;input type="checkbox" value="Same Day" class="service-slider" id="same-main" name="same-main" /&gt; &lt;label for="same-main"&gt;&lt;/label&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div id="Div2"&gt; &lt;label id="Label2"&gt;&lt;/label&gt; &lt;label&gt; Embassies&lt;br /&gt; R300.00 &lt;/label&gt; &lt;div class="slide"&gt; &lt;input type="checkbox" value="Public holiday" class="slide same-main" id="day-ckbx-embassies" name="day-ckbx-embassies" /&gt; &lt;label for="day-ckbx-embassies"&gt;&lt;/label&gt; &lt;/div&gt; &lt;label&gt; Public Holidays&lt;br /&gt; R200.00 &lt;/label&gt; &lt;div class="slide"&gt; &lt;input type="checkbox" value="Public holiday" class="slide same-main" id="day-ckbx-public" name="day-ckbx-public" /&gt; &lt;label for="day-ckbx-public"&gt;&lt;/label&gt; &lt;/div&gt; &lt;label&gt; After Hours&lt;br /&gt; R300.00 &lt;/label&gt; &lt;div class="slide"&gt; &lt;input type="checkbox" value="Public holiday" class="slide same-main" id="day-ckbx-after" name="day-ckbx-after" /&gt; &lt;label for="day-ckbx-after"&gt;&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I am looking at it and it works but it seems very verbose. The code basically allows a top level set of checkboxes, it you think of it in a table structure it would be the first row and only checkboxes in the column that has the active checkbox can be selected.</p> <p>I am relying very heavily on the naming convention of classes and ids together with the jQuery <code>$(this)</code>.</p> <p>Basically the classes of the bottom level checkboxes have to be the same name as the top level ids. The bottom level checkboxes are also disabled using a class name that all the bottom level checkboxes have.</p> <p>I am kinda new to jQuery and I am not sure this is the best way to do it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:50:09.007", "Id": "70445", "Score": "2", "body": "There is something that is bugging me when people are using jQuery to handle states or application flow. The logic code becomes dependant of the view. Though, I think it's as good as jQuery allows you to do. You could use functions with meaningful names so that the comments would be useless. If you plan on creating something bigger, you should consider using a framework over a dom manipulation library. I suggest AngularJS or Backbone." } ]
[ { "body": "<p>You aren't really doing much here that can really be cleaned up, your indentation is off though, your code should look like this</p>\n\n<pre><code>$(function () {\n $(\".service-slider\").on(\"click\", function (){\n // Disable all bottom level slides\n $(\".slide\").attr(\"disabled\", false);\n\n // Uncheck all previous checked checkboxes\n $(\".slide\").prop('checked', false);\n\n // Disable top level checkboxes\n $(\".service-slider\").prop('checked', false);\n\n // Enable the selected checkbox to true\n $(this).prop('checked', true);\n\n //Disable bottom level slides\n $(\".slide\").attr(\"disabled\", true);\n\n // Get selected id to enable all bottom level slides based on this\n var tron = \".\" + $(this).attr(\"id\");\n\n // Get the var and enable only those checkboxes\n $(tron).attr(\"disabled\", false);\n });\n});\n</code></pre>\n\n<p>Please use proper indentation</p>\n\n<p>You should also provide the html that goes along with this so that we can give a better review.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-11T06:16:01.813", "Id": "114150", "Score": "0", "body": "Hey, thanks for the reply. I did post a link to the jsfiddle that has all the code. It is the first link in the post" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-11T15:37:33.027", "Id": "114269", "Score": "1", "body": "@gerdi, we also have the ability to use Stack Snippets now so that reviewers don't have to leave this page to run your code. There is a new option when you go to edit your question on the toolbar, next to the picture insert button" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-11T20:04:17.410", "Id": "114325", "Score": "1", "body": "rad .. Updated with the snippet." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-10T18:37:56.727", "Id": "62559", "ParentId": "28176", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T20:02:56.853", "Id": "28176", "Score": "5", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "Checkbox processes" }
28176
<p>I'm currently working to implement a simple configuration file parser. I intend to add more functional down the road.</p> <p><strong>ConfigReader.hpp</strong></p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; class ConfigReader { public: struct record { std::string section; std::string name; std::string value; }; ConfigReader(); explicit ConfigReader (const std::string &amp; file); bool readfile (const std::string &amp; file); std::string get_string (const std::string &amp; tsection, const std::string &amp; tname, std::string tdefault = std::string()); private: std::vector&lt;record&gt; records; }; </code></pre> <p><strong>ConfigReader.cpp</strong></p> <pre><code>#include &lt;fstream&gt; #include "ConfigReader.hpp" namespace { /* Erases leading tabs, leading spaces; trailing tabs, trailing spaces. */ std::string &amp; trim (std::string &amp; str) { // leading tabs / spaces int i = 0; while (i &lt; (int) str.length() &amp;&amp; (str[i] == ' ' || str[i] == '\t')) ++i; // erase leading tabs / spaces if (i &gt; 0) str.erase (0, i); int j = i = str.length(); while (i &gt; 0 &amp;&amp; (str[i - 1] == ' ' || str[i - 1] == '\t')) --i; // erase trailing tabs / spaces if (i &lt; j) str.erase (i, j); return str; } /* Erases tabs and spaces between the variable's name and its value. */ std::string &amp; normalize (std::string &amp; str) { // Erases leading tabs, leading spaces; trailing tabs, trailing spaces. trim (str); // i is the start of the section of tabs and spaces. // j is the end of said section. std::size_t i, j; i = j = 0; while (i &lt; str.length()) { if (str[i] == ' ' || str[i] == '\t') { j = i + 1; // find the end of section of tabs and spaces. while (j &lt; str.length() &amp;&amp; (str[j] == ' ' || str[j] == '\t')) ++j; // if the section consists of just one character, // then erase just one character. // otherwise, remove j - i characters. if (j == i) str.erase (i, 1); else str.erase (i, j - i); } else { str[i] = std::tolower (str[i]); ++i; } } return str; } /* Check if a line consists only of spaces and tabs */ bool spaceonly (const std::string &amp; line) { for (int i = 0, j = line.length(); i &lt; j; ++i) { if (line[i] != ' ' &amp;&amp; line[i] != '\t') return false; } return true; } /* Check if a line is valid */ bool isvalid (std::string &amp; line) { normalize (line); std::size_t i = 0; // if the line is a section if (line[i] == '[') { // find where the section's name ends std::size_t j = line.find_last_of (']'); // if the ']' character wasn't found, then the line is invalid. if (j == std::string::npos) return false; // if the distance between '[' and ']' is equal to one, // then there are no characters between section brackets -&gt; invalid line. if (j - i == 1) return false; } /* Check if a line is a comment */ else if (line[i] == ';' || line[i] == '#' || (line[i] == '/' &amp;&amp; line[i + 1] == '/')) return false; /* Check if a line is ill-formed */ else if (line[i] == '=' || line[i] == ']') return false; else { std::size_t j = line.find_last_of ('='); if (j == std::string::npos) return false; if (j + 1 &gt;= line.length()) return false; } return true; } // parse the line and write the content to our vector void parse (std::vector&lt;ConfigReader::record&gt; &amp; records, std::string &amp; section, std::string &amp; line) { std::size_t i = 0; // if the line is a section if (line[i] == '[') { ++i; std::size_t j = line.find_last_of (']') - 1; section = line.substr (i, j); } // if the line is a variable + value else { ConfigReader::record temp; temp.section = section; // construct the name of the variable std::size_t j = line.find ('='); std::string name = line.substr (i, j); temp.name = name; // construct the variable's value std::size_t k = line.find ('=') + 1; std::size_t z = line.find (';'); z = (z == std::string::npos) ? line.length() : z; std::string value = line.substr (k, z); // bug ? if the line is width = 32; then the semicolon is not erased. temp.value = value; records.push_back (temp); } } } bool ConfigReader::readfile (const std::string &amp; file) { records.clear(); std::ifstream config (file); if (!config.is_open()) return false; std::string section; std::string buffer; std::size_t i = 0; while (std::getline (config, buffer, '\n')) { if (!spaceonly (buffer)) { if (isvalid (buffer)) parse (records, section, buffer); else{} // std::cout &lt;&lt; "Failed at line " &lt;&lt; i; } ++i; } return true; } std::string ConfigReader::get_string (const std::string &amp; tsection, const std::string &amp; tname, std::string tdefault) { for (std::size_t i = 0; i &lt; records.size(); ++i) { if (records[i].section == tsection &amp;&amp; records[i].name == tname) { return records[i].value; } } record temp; temp.section = tsection; temp.name = tname; temp.value = tdefault; records.push_back (temp); return tdefault; } ConfigReader::ConfigReader (const std::string &amp; file) : records() { readfile (file); } ConfigReader::ConfigReader() : records() { } </code></pre> <p>The syntax of the config file is simple:</p> <pre><code>[video] width = 1920; etc; </code></pre> <p>What should I change? Improve? Are there any errors? (Well, there is one in parse.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T00:44:19.883", "Id": "44005", "Score": "0", "body": "Consider using a standard format: like Json. It makes it easier to maintain." } ]
[ { "body": "<p>Use standard algorithms where applicable. For instance, <code>trim</code> could be rewritten:</p>\n\n<pre><code>std::string&amp; trim(std::string&amp; s) {\n auto is_whitespace = [] (char c) -&gt; bool { return c == ' ' || c == '\\t'; };\n auto first_non_whitespace = std::find_if_not(begin(s), end(s), is_whitespace);\n s.erase(begin(s), first_non_whitespace);\n auto last_non_whitespace = std::find_if_not(s.rbegin(), s.rend(), is_whitespace)\n .base();\n s.erase(std::next(last_non_whitespace), end(s));\n return s;\n}\n</code></pre>\n\n<p>Likewise, <code>normalize</code> could be written like this:</p>\n\n<pre><code>std::string&amp; normalize(std::string&amp; s) {\n s.erase(std::remove_if(begin(s), end(s),\n [] (char c) { return c == ' ' || c == '\\t'; }),\n end(s));\n std::transform(begin(s), end(s), begin(s),\n [] (char c) { return std::tolower(c); });\n return s;\n}\n</code></pre>\n\n<p>Note that the intent of this code is quite clear -- I didn't need to add comments to let you know what each section of the code was meant to be doing (although it is necessary to know standard C++ algorithms and idioms like erase-remove). It took me a few minutes of careful reading to realize that you were removing all whitespace in your <code>normalize</code> function; my version makes this very clear. Are you sure you want to remove all whitespace? Couldn't some future configuration use string types?</p>\n\n<p>PS I chose to use C++11 features like <code>auto</code> and lambda, but this code can be written in C++03 with not very much more boilerplate code.</p>\n\n<hr>\n\n<p>In <code>isvalid</code>, you declare <code>std::size_t i = 0</code>. This is confusing for a couple of reasons. When I see a variable declared non-<code>const</code>, I expect that it will change. Even if it were <code>const</code>, <code>i</code> is not meaningful here. Use <code>0</code> instead of <code>i</code> throughout that function to make it more readable. Likewise, your use of <code>j</code> is not self-documenting. I expect <code>i</code> and <code>j</code> to be loop variables. For <code>j</code> it's a bit more forgivable because it has such a narrow scope, but <code>last_bracket</code> is a name that tells me what the variable is actually for.</p>\n\n<p>Also, throughout <code>isvalid</code>, you dereference <code>line[0]</code> and <code>line[1]</code>, but line might be empty after normalization. Even if you think that's not the case because of <code>spaceonly</code> guarding it, you should add an assertion that documents the precondition. As it stands, your code will access out-of-bounds memory when the line contains only whitespace and a single <code>'/'</code>.</p>\n\n<hr>\n\n<p><code>get_string</code> has funny semantics. For one thing, if my config file is</p>\n\n<pre><code>[Video]\nFoo = Bar\n</code></pre>\n\n<p>I will get an empty string when calling <code>getline(\"Video\", \"Foo\")</code> because you normalize the configuration file but not the queries.</p>\n\n<p>Why do you store a default value if the query fails to find a record? This is not behavior I would expect; in fact, I'd expect <code>get_string</code> to be declared <code>const</code>. If you insist on storing a temp value, you should add a constructor for <code>record</code> and rewrite the storage as <code>records.push_back(record(tsection, tname, tdefault));</code>; in modern compilers, this will result in no copy being made while your version requires a copy.</p>\n\n<p>You should also consider a different data structure. There are a few reasonable options.</p>\n\n<ul>\n<li>Keep using a <code>vector</code>, but sort it and use <code>lower_bound</code> to do lookups.</li>\n<li>Use a <code>map</code> keyed on section or section and name.</li>\n<li>Use an <code>unordered_map</code>.</li>\n</ul>\n\n<p>It depends on future class features, the expected size of config files, and the frequency of insertions, but the <code>vector</code> approach is almost certainly best -- see <a href=\"http://yaserzt.com/blog/archives/615\" rel=\"nofollow\">this blog entry</a> for example.</p>\n\n<hr>\n\n<p>This list is not exhaustive, but it should get you started.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T07:43:31.690", "Id": "44008", "Score": "0", "body": "Hey. Thanks. I am well aware of lamdas. I have been programming for about a year and it is a bad habit of mine of not using STL algrorithms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T07:44:34.820", "Id": "44009", "Score": "0", "body": "I have already been thinking of using a map, btw. I will accept your answer.:)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T00:28:58.247", "Id": "28184", "ParentId": "28179", "Score": "3" } } ]
{ "AcceptedAnswerId": "28184", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T21:06:09.513", "Id": "28179", "Score": "4", "Tags": [ "c++", "parsing" ], "Title": "Simple .cfg parser" }
28179
<p>Much in the spirit of <a href="https://codereview.stackexchange.com/questions/11440/correctness-of-a-minimal-parallel-workers-queue-in-ruby">this question</a>, I have implemented a simple class for parallel workers and wanted to get some feedback on it. Can I make the code even more concise or readable? Are there any hidden problems that I should be aware of?</p> <h1>Worker class</h1> <pre><code>class Worker def initialize queue @queue = queue # Set the "idle state" (returned by the idle? method) # and a mutex for accessing it @idle_state = false @idle_mutex = Mutex.new # Set the "exit state" (returned by the done? method) # and a mutex for accessing it @exit_state = false @exit_mutex = Mutex.new poll end # Poll a queue for Proc objects to process def poll @thread = Thread.new do loop do while @queue.empty? set_idle true exit 0 if done? sleep 1 end set_idle false job = @queue.pop job.call end end end def done? @exit_mutex.synchronize { @exit_state } end def shut_down @exit_mutex.synchronize { @exit_state = true } @thread.join end def idle? @idle_mutex.synchronize { @idle_state } end def set_idle state @idle_mutex.synchronize { @idle_state = state } end end </code></pre> <h1>Usage</h1> <pre><code># Set up a job queue queue = Queue.new # Spin up a few workers workers = [] (1..5).each do workers &lt;&lt; Worker.new(queue) end # Add some jobs to the queue (1..50).each do |i| queue &lt;&lt; Proc.new { $stdout.print "Job ##{i}\n" } end # Shut down each of the workers once the queue is empty sleep 0.1 until queue.empty? workers.each { |worker| worker.shut_down } </code></pre> <p>References:</p> <ul> <li><a href="https://codereview.stackexchange.com/questions/11440/correctness-of-a-minimal-parallel-workers-queue-in-ruby">Correctness of a minimal parallel workers queue in Ruby</a></li> </ul>
[]
[ { "body": "<p><strong>Where not to lock</strong><br>\nI'm not sure why you decided to lock on <code>@exit_state</code> and <code>@idle_state</code>, as they don't seem to have any potential to cause any race condition (except for maybe when the manager calls <code>thread.shut_down</code>, and even then - all that would happen is that you will 'lose' a round of one second - hardly catastrophic).</p>\n\n<p><strong>Where to lock</strong><br>\nWhen you want to concurrently work on a queue - you should synchronize your work with the queue (in this case <code>@queue.empty?</code> and <code>@queue.pop</code>), which you don't do...</p>\n\n<p><strong>How to lock</strong><br>\nYou should also note the <code>@queue.pop</code> is implicitly <code>@queue.pop(false)</code> which means that if the queue is empty, it will block until a new message arrives, which is probably not what you want, since you can't be sure that it is not empty (between <code>while @queue.empty?</code> to <code>job = @queue.pop</code> another worker might have 'hijacked' your message).</p>\n\n<p>Since <code>Queue</code> is thread-safe, you could write your worker like this:</p>\n\n<pre><code>class Worker\n\n def initialize(queue)\n @thread = Thread.new { poll(queue) }\n end\n\n def poll(queue)\n until done?\n begin\n queue.pop(true).call\n rescue ThreadError\n # queue was empty\n sleep 1\n end\n end\n exit 0\n end\n\n def done?\n @done\n end\n\n def shut_down\n @done = true\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T14:52:08.073", "Id": "42308", "ParentId": "28182", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T22:45:59.710", "Id": "28182", "Score": "3", "Tags": [ "ruby", "multithreading" ], "Title": "An implementation of parallel workers in Ruby" }
28182
<p>I'm looking to create a model in JavaScript. Here is an example of the code that I have so far: </p> <pre><code>// Person model function Person(firstName, age) { // Check first name if (firstName) { if (typeof firstName === 'string') { this.firstName = firstName; } else throw new Error('The first name is not a string.'); } else throw new Error('First name is a required field.'); // Check age if (age) { if (typeof age === 'number') { if (age &lt; 0) { throw new Error('The age provided is a negative.'); } else { this.age = age; } } else throw new Error('The age provided is not a number.'); } else throw new Error('Age is a required field.'); } // Example usage try { var joel = new Person('Joel', 30); console.log(joel); } catch(err) { console.log(err.message); } </code></pre> <p>Is this an idiomatic approach to the solution? And if so is there a way in which I can improve it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T14:30:07.290", "Id": "44038", "Score": "0", "body": "Seems inflexible, sometimes one needs temporarily invalid objects" } ]
[ { "body": "<p>I prefer to create <code>isValid()</code> method instead of exceptions and <code>getValidationErrors()</code> to get array of all errors instead of one error message with exception.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var joel = new Person('Joel', 30);\nif( ! joel.isValid() ) {\n console.log(joel.getValidationErrors());\n}\n</code></pre>\n\n<p>Also you can create some validation function like</p>\n\n<pre><code>validate({\n name: {\n type: 'string'\n },\n age: {\n type: 'number',\n minValue: 0,\n maxValue: 150\n }\n}, {\n name: firstName,\n age: age\n});\n</code></pre>\n\n<p>Which will return array of errors. If array length is 0 then validation passed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T11:53:38.503", "Id": "28287", "ParentId": "28189", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T12:29:37.817", "Id": "28189", "Score": "1", "Tags": [ "javascript", "validation" ], "Title": "Validating Javascript Model" }
28189
<p>I have a comments page on my site and I was wondering if it is vulnerable to some sort of sql attack or something else. At the moment users can type what they want, they can even write a php script and it will upload to the database. Is this a problem and how can I fix it.</p> <p>This is the script I use:</p> <pre><code>$name= $_POST['name']; $email= $_POST['e_mailaddress']; if(isset($_POST['comments']) AND $_POST['comments']!=''){ $comments= $_POST['comments']; $comments_sent = 'true'; $dbcn = new connection(); $sql= &quot;INSERT INTO contact (name, email, comments) VALUES (:name, :email, :comments);&quot;; $query = $dbcn-&gt;dbconnect()-&gt;prepare($sql); $results = $query-&gt;execute(array( &quot;:name&quot;=&gt; $name, &quot;:email&quot;=&gt; $email, &quot;:comments&quot;=&gt; $comments )); } </code></pre>
[]
[ { "body": "<p>It depends. Prepared statements \"help\" preventing sql injection when entering data into the database. But at some point you will want to use your data. Thus make sure you check the entered data for consistency and plausibility. e.g. make sure the email address is really an email address and the name does not contain code which might trick your mail routine to send a completely different mail ...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:40:25.313", "Id": "44025", "Score": "0", "body": "Its just a comments page that only I can read from. I have been posting php scripts and they save into the database but dont show up in the inbox.\nAny suggestions on a script I could test, nothing malicious just something that will let me know for sure if the scripts in the database can be run." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:47:24.400", "Id": "44026", "Score": "0", "body": "Nevertheless, there are bad persons out there, who might craft an entry which, when displayed on your personal comments page sends your own login data to their own server ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:54:27.467", "Id": "44027", "Score": "0", "body": "Aye ive been trying to write something that will let me know if a script will be run when i open my message page. But so far nothing, it just opens message page and has blank entries for the messages that were scripts. My passwords are hashed so even if someone did manage to pul a password from database it will just be a long asss hash" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:57:54.203", "Id": "44028", "Score": "0", "body": "Well, your question was if the code above prevents any other attack ... and the answer is no, not really ... escape your input variables, check them for consistency and plausibility ... and even then, there could be possible attacks for which your code is prone to ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:20:23.370", "Id": "44029", "Score": "0", "body": "OK so can you tell me what to look into to \"escape input variables\" and to check for consistency and plausibility?\n\nI use to use the function GetSQLValueString back when i was using mysql_query. Is this what you mean? should i be using it with my new script?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T10:13:15.660", "Id": "44030", "Score": "0", "body": "That depends on how thorough you want/need to be. As far as I know GetSQLValueString just removes the sql specific format and will not provide any security. For the email address, check if it is an email address. e.g. it has an @ sign and only contains valid characters, does it include a valid domain etc ... for the comments, check for html tags, or JavaScript code ... you could also want to check for strings known to disrupt sendmail ... it's really an ugly world out there ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T10:35:08.263", "Id": "44031", "Score": "0", "body": "Cheeers martin you have been very helpful. I dont suppose you woul dlike to share an script that would check for html tags and javascript?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T08:35:06.290", "Id": "28191", "ParentId": "28190", "Score": "0" } }, { "body": "<p>With prepared statements, I don't see anything that would immediately make it susceptible to sql injection (this isn't to say there isn't something that is there at a deeper level - I'm not a security auditor nor intimately familiar with php). The \"or something else\" part remains quite large.</p>\n\n<p>Look at <a href=\"https://www.owasp.org/index.php/Main_Page\" rel=\"nofollow\">OWASP</a> (Open Web Application Security Project) which goes through a large set of possible attack vectors through the web.</p>\n\n<p>Such a page <em>is</em> susceptible to various scripting injection where someone inserts a script (or flash, or even something like an image from another site) to be executed on another client machine. From the <a href=\"http://owasptop10.googlecode.com/files/OWASP%20Top%2010%20-%202013.pdf\" rel=\"nofollow\">OWASP top 10 - 2013 pdf</a> the XSS attack can be seen and described on page A3 (page 9).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T11:19:55.800", "Id": "28192", "ParentId": "28190", "Score": "3" } }, { "body": "<p>It is good that you used a paramterized query. I guess you are using pdo and mysqli, if I am not wrong they make a prepared statement and clean it before submitting it to your database.</p>\n\n<p>To protect against sql injection make 2 classes.\nOne that confirms that a name is a name (could check its type that is a string, and length) and an email (check for length and use the made classes on the internet to check that u really an email). - That would be considered as creating a whitelist.</p>\n\n<p>The second class would sanitize bad characters. Sanitize > &lt; \" ' % characters that are used for sql injection. The PDO/MSQLi framework that I think you are using, already does some of the filtering..one of your own could also help- That would be considered as creating a blacklist.</p>\n\n<p>WhiteList is safer, but having both of them is good enough.</p>\n\n<p>Make test on your code, if you dont know sql well and ways to use canocolisation to pass the filters, use a good tool which is called sqlmap.</p>\n\n<p>Last note..SQL injection is possible in prepared statements. May be even a secondary sql injection!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T12:09:23.283", "Id": "44032", "Score": "1", "body": "Your last point might be good to clarify: if a value is injected directly into a SQL string (i.e. that part is not inserted as a parameter) then it could be vulnerable. But if the only user input introduced into the query goes through PDO/mysqli parameters, it is 100% safe as far as SQL injection goes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T20:57:44.083", "Id": "44058", "Score": "2", "body": "-1. Please don’t ever sanitize." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T11:51:47.117", "Id": "28193", "ParentId": "28190", "Score": "-2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-07-06T08:23:54.930", "Id": "28190", "Score": "1", "Tags": [ "php", "sql" ], "Title": "Insert row into database using values from a html form submission" }
28190
<p>Suppose there is a number <strong>N</strong> which can be divided into two positive non zero numbers <strong>X</strong> and <strong>Y</strong> i.e <code>N = X + Y</code>. There will be <strong>N/2</strong> pairs of <strong>(X,Y)</strong>. </p> <p>I want to find the largest <code>LCM(Least common multiple)</code> of <code>X</code> &amp; <code>Y</code></p> <blockquote> <p><strong>Example</strong> <br/> <code>5 = (1 + 4)</code> and <code>5 = (2 + 3)</code><br/> Since <code>LCM(1,4) = 4</code> &lt; <code>LCM(2,3) = 6</code> the largest LCM will be <code>LCM(2,3) = 6</code>.</p> </blockquote> <p><strong>CODE</strong></p> <pre><code>#include &lt;stdio.h&gt; int lcm(int, int); int main(void) { int counter = 0; int lowerBound = 0, upperBound, input, result; // input is the n printf("input = "); scanf("%d",&amp;input); int max = -1; upperBound = input; // at first upperBound will be the input for(counter=0; counter &lt; input/2; counter++) // we will iterate till the input/2 terms { lowerBound++; upperBound--; // in every iteration we will compute the lcm of lowerBound and upperBound // so 1st iteration : compute lcm(1, n-1) // 2nd iteration : compute lcm(2, n-2) // 3rd iteration : compute lcm(3, n-3) // .......after ((n/2)-1)th iteration..... // if n is even : compute lcm(n/2, n/2) // if n is odd : compute lcm((n/2)-1, n/2) result = lcm(lowerBound,upperBound); // store the result if(result &gt;= max) // if result is maximum update the maximum { max = result; } } printf("output = %d",max); return 0; } int lcm(int x, int y) { int n1 = x, n2 = y; while(n1 != n2) { if(n1 &gt; n2) n1 = n1 - n2; else n2 = n2 - n1; } return((x*y) / n1); } </code></pre> <p><strong>OUTPUT 1</strong></p> <pre><code>input = 10 output = 21 </code></pre> <p><strong>OUTPUT 2</strong></p> <pre><code>input = 11 output = 30 </code></pre> <hr> <p><strong>UPDATE 1</strong></p> <p>After <a href="https://codereview.stackexchange.com/users/26426/aseem-bansal">Aseem Bansal</a>'s answer I try to find a more optimize way to solve the problem and i came up with this code</p> <pre><code>#include&lt;stdio.h&gt; int main(void) { int input, result = 0; printf("Enter the input = "); scanf("%d",&amp;input); while(input &lt;= 0) // if input is negative ask again { printf("Enter a positive non zero number :"); scanf("%d",&amp;input); } int middle = (input/2); if(input%2 != 0) // if the input is an odd number { result = (middle * (middle+1)); } else // if input is an even number { result = middle%2 == 0 ? ((middle-1) * (middle+1)) : ((middle-2) * (middle+2)); } printf("result = %d",result); return 0; } </code></pre> <p><strong>OUTPUT 1</strong></p> <pre><code>Enter the input = 13 result = 42 </code></pre> <p><strong>OUTPUT 2</strong></p> <pre><code>Enter the input = 12 result = 35 </code></pre> <p><strong>OUTPUT 3</strong></p> <pre><code>Enter the input = 10 result = 21 </code></pre> <p><strong>EXPLANATION</strong></p> <p>As for any <em>odd</em> number the <code>middle</code> and <code>middle+1</code> are highest <a href="http://en.wikipedia.org/wiki/Coprime_integers" rel="nofollow noreferrer">coprime</a> numbers, so the <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor" rel="nofollow noreferrer">GCD</a> will be 1. Therefore <code>LCM</code> will be product of <code>middle</code> and <code>middle+1</code>.</p> <p>But for any <em>even</em> number the <code>LCM</code> of <code>middle</code> and <code>middle+1</code> is 1. So we need to find the nearest coprime numbers. If <code>middle</code> is even then the nearest coprime numbers are <code>middle-1</code> and <code>middle+1</code> otherwise the nearest coprime numbers are <code>middle-2</code> and <code>middle+2</code>. The product will be the result.</p> <p><strong>NOTE</strong> </p> <p>here <code>middle</code> is <a href="http://www.mathsisfun.com/sets/function-floor-ceiling.html" rel="nofollow noreferrer">floor</a> of (<code>middle</code>).</p> <p>Can it be more optimized? Any review is welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T13:57:39.390", "Id": "44036", "Score": "0", "body": "Please add a definition of LCM (LCM: the least common multiple of two numbers is the smallest number (not zero) that is a multiple of both)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T15:04:31.063", "Id": "44040", "Score": "0", "body": "Related [question on CS](http://cs.stackexchange.com/questions/13101/find-out-the-largest-lcm-of-the-partitions-of-n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T15:12:17.063", "Id": "44041", "Score": "0", "body": "@AseemBansal yes actually if you look closely one of the answer is given by me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T15:13:11.940", "Id": "44042", "Score": "0", "body": "I noticed that. Just wanted others reading this question to know that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T16:05:39.873", "Id": "44043", "Score": "0", "body": "Did you actually run this code? Because of `scanf(\"input = %d\",&input);` it will give incorrect results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T16:15:35.070", "Id": "44044", "Score": "0", "body": "@AseemBansal i just corrected it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:10:31.070", "Id": "44045", "Score": "0", "body": "@AseemBansal as i don't have enough reputation i can't comment on your answer. Thanks to your answer i got a more easy solution http://pastebin.com/bkMdhKT3" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:16:45.833", "Id": "44046", "Score": "0", "body": "I would suggest you to use euclid's algorithm, paste the code here as an edit to your question [like I have done here](http://codereview.stackexchange.com/questions/28132/implementation-of-insertion-sort-optimization), explain the logic behind the else part because I am curious and make a habit of [accepting answers](http://codereview.stackexchange.com/help/accepted-answer) if you like one. All your choices but all recommended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:18:46.090", "Id": "44048", "Score": "0", "body": "If you add the explanation put it in your question as an edit. Otherwise the comments will be very messy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T18:59:19.053", "Id": "44053", "Score": "0", "body": "@AseemBansal Ok i will edit my question and put up the answer. Now for the `else` part, after many test cases i observe that for the even numbers the highest partition LCM always lies between `lcm((input/2)-2, (input/2)+2)` or `lcm((input/2)-1, (input/2)+1)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T16:48:12.663", "Id": "44121", "Score": "0", "body": "Updated the answer for exact answer. Its better than calculating both of these LCM." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:06:52.057", "Id": "44168", "Score": "1", "body": "@tintinmj I rejected your edit because your current code calculates 3 LCMs while my answer explains how it can be done by calculating only one of them. You might need to read my answer's **EDIT3** again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T17:43:16.947", "Id": "44187", "Score": "0", "body": "Updated answer. I think my last update on this question." } ]
[ { "body": "<p>I am not sure about the overall algorithm but there are better ways for finding LCM. You should use a different algorithm. Try <a href=\"https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations\" rel=\"nofollow noreferrer\">Euclid's algorithm</a> to find the GCD.</p>\n<p>Then calculate <code>result</code>(your LCM) in <code>main()</code> as</p>\n<p><code>result = (lowerbound * upperbound)/gcd(lowerbound upperbound);</code></p>\n<p>The problem with your LCM function is that subtraction isn't the best way for finding the GCD which you are currently doing. It will take too long. Just consider the case of <code>x = 1 and y = 100000</code>. It should be easy to see that number of subtractions is much higher in this case and the program would be <strong>very</strong> slow.</p>\n<hr />\n<p>If you don't want to change the algorithm(which you should) then the least optimization that I can think is to not declare <code>n1</code> and <code>n2</code> separately in the function <code>lcm</code>. Just use x and y. Do the final division by the product in the <code>main</code> function. It will at least save you 2 variables.</p>\n<hr />\n<p><strong>EDIT</strong></p>\n<p>I came up with a much better optimization. In your main loop instead of going from the outside pairs i.e (1, n-1) to the inside pairs you would do much better by going from the inside.</p>\n<p><strong>Example</strong></p>\n<blockquote>\n<p><code>5 = (1,4)</code> and <code>5 = (2,3)</code>. The maximum is found at <code>5 = (2,3)</code>.</p>\n<p><code>7 = (1,6)</code> , <code>7 = (2,5)</code> and <code>7 = (3,4)</code>. The maximum is at <code>7 = (3,4)</code>.</p>\n</blockquote>\n<p>The answer is in the middle. You'll get it without a loop.</p>\n<p>But there is a big problem. This reasoning works only for odd numbers. I tried writing down numbers on paper and solved it by hand. I'll need some more time to find out a pattern for even numbers.</p>\n<p>But <strong>for odd numbers</strong> this is probably the best optimization.</p>\n<p><strong>EDIT2</strong></p>\n<p>In the <code>main</code> function instead of\n<code>if(result &gt;= max)</code> you should be using <code>if(result &gt; max)</code>. What is the use of replacing the number with the same number? One less operation.</p>\n<p>You don't need to initialize <code>counter</code> at the beginning. You are doing that in the <code>for</code> loop.</p>\n<p><strong>EDIT3:</strong></p>\n<p><strong>For the case of even numbers</strong> the maximum lcm will be either <code>lcm((input/2)-2, (input/2)+2)</code> or <code>lcm((input/2)-1, (input/2)+1)</code>. It's easy to find which will be maximum without calculating both of them.</p>\n<p>If <code>input/2</code> is even then <code>lcm((input/2)-1, (input/2)+1)</code> should be maximum otheriwse it should be <code>lcm((input/2)-2, (input/2)+2)</code>.</p>\n<hr />\n<p><strong>EDIT After OP's Update 1</strong></p>\n<p>How about this as a better code</p>\n<pre><code>#include&lt;stdio.h&gt;\n\nint main(void)\n{\n int input, result;\n printf(&quot;Enter the input = &quot;);\n scanf(&quot;%d&quot;,&amp;input);\n\n while (input &lt;= 0)\n {\n printf(&quot;Enter a positive non zero number :&quot;);\n scanf(&quot;%d&quot;,&amp;input);\n }\n\n // (x % 2) used as a condition in C means checking x for odd number\n int middle = input/2;\n result = input % 2 ? (middle % 2 ? middle * middle - 4 : middle * middle - 1)\n : middle * (middle + 1);\n\n printf(&quot;Result = %d&quot;,result);\n return 0;\n}\n</code></pre>\n<p>Removed unnecessary braces, spaces, comparisons and comments. Comments are needed but commenting obvious things is just noise. I prefer single space on both sides of operators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T18:05:59.453", "Id": "44190", "Score": "0", "body": "i also thought about nested ternary operators, this minimizes the code but create readability issue. I like the `(middle * middle) - 4` it's for `(a+b) * (a-b)` but seeing this code only once someone will stumble, just a thought." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T18:10:52.453", "Id": "44191", "Score": "0", "body": "Seeing `(a + b) * (a - b)` will also lead people to think why if they don't know the logic behind it. So that should not be an issue. If you can explain that then you can also explain this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T18:12:34.787", "Id": "44192", "Score": "0", "body": "If if-else is nested a lot to just decide the value of a variable that would create more readability issues. This makes things clear IMHO." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T14:59:18.903", "Id": "28196", "ParentId": "28194", "Score": "2" } } ]
{ "AcceptedAnswerId": "28196", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T13:50:10.930", "Id": "28194", "Score": "2", "Tags": [ "c" ], "Title": "Largest LCM of partitions of a number" }
28194
<p>I would like a code review for my first simple slideToggle jQuery plugin. </p> <p><a href="https://rawgithub.com/Shivambh28/ezToggle/master/demo.html" rel="nofollow">Demo</a></p> <pre><code>(function($) { $.fn.ezToggle = function(options) { var defaults = { selector : '.yourSelector', speed : 300, openedClassName : 'opened', closedClassName : 'closed', }, options = $.extend(defaults, options); return this.each(function() { var originalHeight = $(this).outerHeight(true); options.minHeight = options.minHeight || $(this).find(defaults.selector).outerHeight(true); if (!$(this).hasClass(defaults.openedClassName)) { $(this).addClass(defaults.closedClassName).height(options.minHeight); } $(this).find(defaults.selector).on('click', function(e) { e.preventDefault(); var $parent = $(this).parent(); if ( $parent.hasClass(defaults.closedClassName) ) { $('.'+defaults.openedClassName) .removeClass(defaults.openedClassName) .addClass(defaults.closedClassName) .animate( { height : options.minHeight }, defaults.speed ); $parent.removeClass(defaults.closedClassName) .addClass(defaults.openedClassName) .animate({ height : originalHeight }, defaults.speed); } else if ( $parent.hasClass(defaults.openedClassName) ) { $parent.removeClass(defaults.openedClassName) .addClass(defaults.closedClassName) .animate({ height : options.minHeight }, defaults.speed); } }); }); }; }) (jQuery); </code></pre>
[]
[ { "body": "<p>First of all you don't need <code>defaults</code> and second <code>options</code> can be undefined so</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>options = $.extend({\n selector : '.yourSelector',\n speed : 300,\n openedClassName : 'opened',\n closedClassName : 'closed',\n }, options || {});\n</code></pre>\n\n<p>Third don't use every time <code>$(this)</code>, define it once and use everywhere</p>\n\n<pre><code>var $this = $(this);\n\nvar originalHeight = $this.outerHeight(true);\n...\n</code></pre>\n\n<p>Next, instead of <code>e.preventDefault();</code> just <code>return false</code> in the end of <code>.on('click', function(e) {</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T11:34:46.517", "Id": "28283", "ParentId": "28195", "Score": "1" } }, { "body": "<p>If you didn't know already, this type of plugin is referred to as an <a href=\"http://jqueryui.com/accordion/\" rel=\"nofollow\">accordion</a>. I would suggest reading the code for the jQuery plugin (since you are using jQuery) to find out how they do it. With this you can get ideas, see their organization, and if you find something that can be fixed/improved you'll have the power to contribute!</p>\n\n<p>To add to redexp's answer about the <code>preventDefault()</code> method.\nIn your click functions you might want to prevent the default browser action on a link, which is to direct the page to that link. Since you just want to perform something on your page and don't actually want the browser to leave the page you should prevent that action. The difference between the two is that <code>return false;</code> does that and at the same time stops event propagation. Propagation being when you click on an element, it triggers an event on the element, and any events on its parent elements (because technically they were also clicked). Whether or not you need to stop propagation is up to you, so pick accordingly.</p>\n\n<p>So basically:</p>\n\n<pre><code>function() {\n return false;\n}\n\n// Is the same as doing\n\nfunction(e) {\n e.preventDefault();\n e.stopPropagation();\n}\n</code></pre>\n\n<p>It's all probably a lot more complicated than this and articles <a href=\"http://www.quirksmode.org/js/events_order.html\" rel=\"nofollow\">like this</a> probably explain it all a lot better.</p>\n\n<p>As you progress in plugin development you should start to think about implementing design patterns. There are almost endless options of patterns you can use and some you can event make sort of a hybrid pattern. Don't feel overwhelmed with all the options pick out a couple to start with and try them out. I'd suggest the <a href=\"http://www.yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"nofollow\">Module Pattern</a> (<a href=\"http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/\" rel=\"nofollow\">another good article</a>) since you've already sort of implemented it in this plugin. Also look at the Observer Pattern (aka Pub/Sub) it's great for dealing with custom events. <a href=\"https://tutsplus.com/lesson/custom-events-and-the-observer-pattern/\" rel=\"nofollow\">This video</a> by Jeffery Way does a great job of explaining the concept. I'd recommend you'd watch the rest of the episodes from that series as well because he does cover some good ground on plugins.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T14:32:45.907", "Id": "28292", "ParentId": "28195", "Score": "1" } } ]
{ "AcceptedAnswerId": "28292", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T13:54:32.690", "Id": "28195", "Score": "1", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "slideToggle plugin" }
28195
<p><strong><em>Did I improve since <a href="https://codereview.stackexchange.com/questions/28060/is-there-any-way-to-improve-my-java-anything-wrong-with-it">then</a>?</em></strong></p> <p>I have been writing this program today, and tried my best to improve my object-oriented understanding.</p> <p>Mains.java:</p> <pre><code>import games.GameHandler; import java.util.Scanner; import java.io.*; public class Mains { public static void main (String[] args) { //Start the game startGame(); } private static void startGame() { //Declares GameHandler handler = new GameHandler(); Scanner console = new Scanner(System.in); boolean game = true; String input = ""; //Print program welcome text handler.printStart(); //While in game... while (game) { //Getting input ready for new commands from the player input = console.nextLine(); //Checking if input was set. if (input != null) { //Selecting the game you want to play. handler.selectGame(input); //If game was selected.. then.. let's start playing. while (handler.inGame) { //Use will say something. input = console.nextLine(); //If it was "exit", it will go back and select another game. if (input.equals("exit")) { handler.exitGame(); } else { //Play again. handler.continueGame(input); } } } } } } </code></pre> <p>GameHandler.java:</p> <pre><code>package games; import java.io.*; public class GameHandler { private String[] games = {"Spin", "Tof"}; private String[] navigation = {"Back", "Start"}; private Spin spin = new Spin(); private boolean spinGame = false; private boolean tofGame = false; public boolean inGame = false; /** * Method printStart * * Will welcome the player to the program. */ public void printStart() { this.print(0, "Welcome to the program!"); this.print(0, "Please select a game: " + this.availableGames()); } /** * Method available games * * This will print all the games that are located in the games array in one row. **/ private String availableGames() { String names = ""; for (int i = 0; i &lt; games.length; i++) { names = (names + games[i]); if (i &lt; games.length -1) { names = (names + ", "); } } return names; } /** * Method selectGame * * This will select the given game. * @param command The entered command. **/ public void selectGame(String command) { if (this.inArray(command)) { if (command.equalsIgnoreCase("spin")) { this.startGame("spin"); } else if (command.equalsIgnoreCase("tof")) { this.startGame("tof"); } } else { this.print(0, "Could not find game!"); } } /** * Method inArray * * This will check if the entered game name is exisiting in the games array. * If yes, will return a boolean true, else false. * * @param value The entered game name. * @return boolean true/false. **/ private boolean inArray(String value) { int returning = 0; for (String s : games) { if (value.equalsIgnoreCase(s)) { returning = 1; } } if (returning == 1) { return true; } else { return false; } } /** * Method startGame * * Will start the game, and print instructions. * will set the game boolean to true. **/ private void startGame(String game) { switch (game) { case "spin": this.print(0, "Welcome to spin game!"); this.print(0, "Please click on any key to spin!"); spinGame = true; break; case "tof": break; } inGame = true; } /** * Method continueGame * * Will continue the game, either spin again, or print new question or even answer. * @param command The entered command. **/ public void continueGame(String command) { while (inGame) { if (spinGame) { this.spinWheel(); // Break out of the loop. break; } } } /** * Method exitGame * * Exit the game.. **/ public void exitGame() { spinGame = false; tofGame = false; this.printStart(); } /** * Method spinWheel * * This will spin the wheel. **/ private void spinWheel() { this.print(0, spin.spinWheel()); } /** * Method print * * Prints text using System.out * @param type printing type (Println/print). * @param message The message **/ private void print(int type, String message) { switch (type) { case 0: System.out.println(message); break; case 1: System.out.print(message); break; } } } </code></pre> <p>spin.java:</p> <pre><code>package games; import java.util.Random; public class Spin { /** * The base auth we are going to work with.. **/ private int auth = this.rand(1000) / 5; /** * Creating new Random object. **/ private Random r = new Random(); /** * Method spinWheel * * Spins the damn wheel.. * @return spinned value + if you won or not. **/ public String spinWheel() { return this.spinWheel(this.rand(100)); } /** * spinWheel * * Returning results. **/ private String spinWheel(int number) { int result = this.Calculate(this.rand(number)); if (result &lt; 101) { return "You have won the game!" + result; } else { return "You've lost the game!" + result; } } /** * Method calculate * * Calculates the spin. * @return the spinned number. **/ private int Calculate(int Number) { int var = this.rand(101); int holder = (var * Number) / 2; return holder + this.auth; } /** * Shortcut for nextInt of Random **/ public int rand(int x) { return r.nextInt(x); } } </code></pre> <p>What's wrong with it? did I improve since last time? Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T08:11:24.560", "Id": "44216", "Score": "0", "body": "Please use a meaningful title and tell us what your code does and what it is supposed to do (and if you have any doubts about it)." } ]
[ { "body": "<p>i would suggest to change </p>\n\n<pre><code> private boolean inArray(String value) {\n int returning = 0;\n for (String s : games) {\n if (value.equalsIgnoreCase(s)) {\n returning = 1;\n }\n }\n if (returning == 1) {\n return true;\n } else {\n return false;\n }\n }\n</code></pre>\n\n<p>to </p>\n\n<pre><code> private boolean inArray(String value) {\n boolean doesExist = false;\n for (String s : games) {\n if (value.equalsIgnoreCase(s)) {\n doesExist = true;\n break;\n }\n }\n return doesExist;\n }\n</code></pre>\n\n<p>To OP : Pretty impressive improvement since then.</p>\n\n<p>Put this </p>\n\n<pre><code>public class GameHandler {\n\n private String[] games = {\"Spin\", \"Tof\"};\n private String[] navigation = {\"Back\", \"Start\"};\n private Spin spin = new Spin();\n private boolean spinGame = false;\n private boolean tofGame = false;\n public boolean inGame = false;\n</code></pre>\n\n<p>into the <code>GameHandler</code> constructor, it is a convention to define non-static variable in the class <strong>constructor</strong>.</p>\n\n<hr>\n\n<p>You have a massive error in your <code>Spin</code> class. you have declared <code>private int auth = this.rand(1000) / 5;</code>. So do you know how <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html\" rel=\"nofollow\"><code>this</code></a> keyword works? i don't think so, after running your new code and judge it by the previous i think that you only try break your huge code into smaller part without thinking the logic how it will be executed. I will recommend you to at first do some basic Java programming with small classes and methods and you should start with the <a href=\"http://docs.oracle.com/javase/tutorial/java/concepts/index.html\" rel=\"nofollow\">official tutorial</a>. Good Luck. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T03:55:11.127", "Id": "44208", "Score": "3", "body": "Once doesExist is true why not just exist immediately rather than continue the loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T08:19:10.780", "Id": "44218", "Score": "0", "body": "Instead of returning `doesExist`, you can just do `for (String s : games) { if (value.equalsIgnoreCase(s)) { return true; } } return false;` There's no need for the variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T08:22:38.293", "Id": "44219", "Score": "0", "body": "@Corbin i was trying to change the code as close as OP's code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T08:37:38.470", "Id": "44221", "Score": "1", "body": "@tintinmj Sometimes code should be drastically different than the OPs :)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T18:30:33.267", "Id": "28202", "ParentId": "28197", "Score": "4" } }, { "body": "<p>Building on tintinmj’s answer, I would change his suggestion of</p>\n\n<pre><code>private boolean inArray(String value) {\n boolean doesExist = false;\n for (String s : games) {\n if (value.equalsIgnoreCase(s)) {\n doesExist = true;\n break;\n }\n }\n return doesExist;\n}\n</code></pre>\n\n<p>into</p>\n\n<pre><code>private boolean inArray(String value) {\n for (String s : games)\n if (value.equalsIgnoreCase(s))\n return true;\n return false;\n}\n</code></pre>\n\n<p>– Another reduction by half.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-13T22:37:10.107", "Id": "28443", "ParentId": "28197", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T15:12:48.440", "Id": "28197", "Score": "4", "Tags": [ "java", "object-oriented" ], "Title": "Improving my Java object-oriented? Review!" }
28197
<p>I would like some help to clean up this action, especially from <code>@companies</code> and downward. The comments should be enough to explain :)</p> <pre class="lang-rb prettyprint-override"><code>def search @query = params[:query] unless @query.blank? @query.strip! #Get tags with fuzzy match tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name) #Get vouchers with these tags @vouchers = Voucher.tagged_with(tags, :any =&gt; true) #Get companies with these tags, and add their vouchers to the list @companies = Company.tagged_with(tags, :any =&gt; true) @companies.each do |company| #Because can't merge with nil. Can this be re-written? if @vouchers.empty? @vouchers = company.vouchers else @vouchers.merge(company.vouchers) end end #Get every voucher's category. Can this be re-written? @categories = [] @vouchers.each do |voucher| @categories &lt;&lt; voucher.categories end #Because can't call .flatten on nil if @categories.any? #Need to flatten because the array will contain an arrays of categories [[],[],[]] @categories.flatten!.uniq # I don't really want .flatten.uniq in the view, or? end end end </code></pre>
[]
[ { "body": "<p>Unless I've misjudged what you're going for, this should work (it's not pretty though, I'm sure there's an even better way)</p>\n\n<pre><code>def search\n @query = params[:query].try(:strip) # strip here instead\n\n unless @query.blank?\n tags = Tag.where(\"name LIKE ?\", \"%#{@query}%\").pluck(:name)\n @companies = Company.tagged_with(tags, :any =&gt; true).includes(:vouchers) # eager load vouchers\n @vouchers = [\n Voucher.tagged_with(tags, :any =&gt; true),\n companies.map(&amp;:vouchers)\n ].flatten.uniq\n @categories = @vouchers.map(&amp;:categories).uniq\n else\n # you need something here, by the way...\n end\nend\n</code></pre>\n\n<p>If you don't need each of the collections in the search results, but only need the <code>categories</code>, you should probably add this to the <code>Company</code> model</p>\n\n<pre><code>has_many :categories, :through =&gt; :vouchers\n</code></pre>\n\n<p>then you can do</p>\n\n<pre><code>def search\n @query = params[:query].strip # strip here instead\n\n unless @query.blank?\n tags = Tag.where(\"name LIKE ?\", \"%#{@query}%\").pluck(:name)\n vouchers = Voucher.tagged_with(tags, :any =&gt; true).includes(:categories)\n companies = Company.tagged_with(tags, :any =&gt; true).includes(:categories)\n\n @categories = [vouchers, companies].flatten.map(&amp;:categories).flatten.uniq\n end\nend\n</code></pre>\n\n<p>However, I'd think about restructuring the database if possible, to avoid the mix of 1st and 2nd order associations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T18:23:19.997", "Id": "44125", "Score": "0", "body": "I'm using your first example. Exactly the type of refactoring I was looking for. But watch out, you can't call .strip on params that are nil" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T10:36:02.137", "Id": "44146", "Score": "0", "body": "@Frexuz Ah, of course you're right about that. Wasn't thinking. But it's an excellent chance to use ActiveSupport's `try` method. I've updated my code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T11:42:47.023", "Id": "44149", "Score": "0", "body": "Yes, I went with `try` instead. Just love that method :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T18:05:25.703", "Id": "28231", "ParentId": "28200", "Score": "1" } } ]
{ "AcceptedAnswerId": "28231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:19:19.263", "Id": "28200", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "search", "controller" ], "Title": "Controller method to do fuzzy search for companies" }
28200
<p>I got tired of stringing together objectAtIndex: and objectForKey: and hoping nothing fails along the way. I parse a lot of JSON from sources like the Google Directions API and it was cluttering my code and hard to read. In this example I am parsing the JSON returned by this call:</p> <p><a href="http://maps.googleapis.com/maps/api/directions/json?origin=415OliveStMenloPark&amp;destination=425ShermanAvePaloAlto&amp;sensor=false&amp;mode=driving" rel="nofollow">http://maps.googleapis.com/maps/api/directions/json?origin=415OliveStMenloPark&amp;destination=425ShermanAvePaloAlto&amp;sensor=false&amp;mode=driving</a></p> <p>I just learned Objective-C and how to program (beyond Matlab) and want some feedback on the best practices for what I am doing. </p> <h1>Usage</h1> <p>I call the class method below and pass in a dictionary along with a cascading series of keys for a dictionary and indexes for arrays. I defined a couple of macros to reduce typing. </p> <h1>Usage code</h1> <pre><code> NSTimeInterval flightTime = [(NSNumber *)[RDUtilities objectFromNestedJSON:responseDictionary usingCascadedKeys:RDJSONKey(@"routes"),RDJSONIndex(0), RDJSONKey(@"legs"), RDJSONIndex(0), RDJSONKey(@"duration"), RDJSONKey(@"value")] doubleValue]; </code></pre> <h1>Implementation Code</h1> <pre><code>#define RDJSONKey(x) @{@"dKey":x} #define RDJSONIndex(x) @{@"aIndex":@x} @implementation RDUtilities +(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,... { NSMutableArray *keyDexList = [[NSMutableArray alloc] init]; NSArray *subArray = nil; NSDictionary *subDictionary = nil; id subObject = nil; va_list args; va_start(args, firstArg); // Figure out the type of JSONObject. if ([JSONObject isKindOfClass:[NSDictionary class]]) { subDictionary = JSONObject; } else if ([JSONObject isKindOfClass:[NSArray class]]) { subArray = JSONObject; } else { return nil; } // Iterate through the list of arguments. for (NSDictionary *arg = firstArg; arg != nil; arg = va_arg(args, NSDictionary *)) { if ( [[arg allKeys] containsObject:@"dKey"] || [[arg allKeys] containsObject:@"aIndex"]) { [keyDexList addObject:arg]; } else { NSLog(@"Invalid input types"); return nil; } } // Look at the keyDex and pull out the next subObject from the current correct subObject. NSArray *allButLastKeyDex = [keyDexList objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [keyDexList count]-1)]]; for (NSDictionary *keyDex in allButLastKeyDex) { if (subDictionary != nil &amp;&amp; [[keyDex allKeys] containsObject:@"dKey"]) { // Get the sub object that this key references. subObject = [subDictionary objectForKey:[keyDex objectForKey:@"dKey"]]; // Figure out what we got. if ([subObject isKindOfClass:[NSDictionary class]]) { subDictionary = subObject; subArray = nil; // We can be sure we don't try to use this incorrectly now. } else if ([subObject isKindOfClass:[NSArray class]]) { subArray = subObject; subDictionary = nil; // We can be sure we don't try to use this incorrectly now. } // Unneeded due to containsObject constraint. continue; } if (subArray != nil &amp;&amp; [[keyDex allKeys] containsObject:@"aIndex"]) { // Get the sub object that this key references. subObject = [subArray objectAtIndex:[(NSNumber *)[keyDex objectForKey:@"aIndex"] integerValue]]; // Figure out what we got. if ([subObject isKindOfClass:[NSDictionary class]]) { subDictionary = subObject; subArray = nil; // Safer until we verify logic. } else if ([subObject isKindOfClass:[NSArray class]]) { subArray = subObject; subDictionary = nil; // Safer until we verify logic. } // Unneeded due to containsObject constraint. continue; } } // Get the last key or index. NSDictionary *finalKeyDex = [keyDexList lastObject]; // Pull out the final value and return it. if ([[finalKeyDex allKeys] containsObject:@"dKey"]) { return [subDictionary objectForKey:[finalKeyDex objectForKey:@"dKey"]]; } else if ([[finalKeyDex allKeys] containsObject:@"aIndex"]) { return [subArray objectAtIndex:[(NSNumber *)[finalKeyDex valueForKey:@"aIndex"] integerValue]]; } else { return nil; } } @end </code></pre>
[]
[ { "body": "<p>First off, good job recognizing this problem and coming up with an innovative solution! I definitely like, and it's always nice to see a variadic argument list implementation. I also like that the code is written fairly accessibly, and doesn't try to get into any particularly clever solution.</p>\n\n<p>The primary issue I see with this code is that it relies on conditional logic based on the type of objects rather than polymorphism, object-oriented programming, or useful features of Objective-C. This code does considerable work that the Objective-C runtime could be handling.</p>\n\n<p>For instance we see groups of repeated, quite similar logic in the loop that iterates the key / index dictionaries. We could instead add methods to <code>NSArray</code> and <code>NSDictionary</code> using <a href=\"http://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html\" rel=\"nofollow\">categories</a> that will handle the key or index dictionaries as appropriate.</p>\n\n<p>There are a few other issues, too. There is a repetition of logic at the end of the method to allow returns from the body of the if/else statements, but you could have iterated your entire loop and then just return <code>subObject</code>. The code in most cases due to missing/incorrect object types will return <code>nil</code> but in the case of an incorrect array index it throws an exception. I think a consistent behavior there is best. Also, some style issues - abbreviations like <code>keyDex</code> that aren't particularly explicit (something like <code>keyOrIndexDictionary</code> would be an improvement). This class method could easily be a function, actually, as it never refers to <code>self</code> - remember that in Objective-C you don't have to make your utility functions class methods on some <code>Utilities</code> class like you do in Java. Finally, I notice a lot of use of hard-coded strings, those should be moved out into constants.</p>\n\n<p>As part of reviewing this code, I placed it in an empty iOS project with a unit test target, and document its behavior so that I could refactor it and demonstrate an alternative way of doing things. I used the sample response you linked to as input to the tests, and wrote the following test case:</p>\n\n<pre><code>@implementation RDUtilitiesTests\n\n- (void)testOneKey\n{\n id responseObject = [self responseObject];\n id returnValue = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@\"status\"),nil];\n STAssertEqualObjects(returnValue, @\"OK\", nil);\n}\n\n- (void)testKeyThenIndex\n{\n id responseObject = [self responseObject];\n id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(0),nil];\n STAssertTrue([value isKindOfClass:[NSDictionary class]], nil);\n STAssertNotNil([(NSDictionary *)value objectForKey:@\"bounds\"], nil);\n}\n\n- (void)testSelfCheck\n{\n id responseObject = [self responseObject];\n STAssertNotNil(responseObject, nil);\n}\n\n- (void)testIndexFirstReturnsNil\n{\n id responseObject = [self responseObject];\n id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONIndex(0),nil];\n STAssertNil(value, nil);\n value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONIndex(1),nil];\n STAssertNil(value, nil);\n}\n\n- (void)testOutOfBoundsIndexThrowsException\n{\n id responseObject = [self responseObject];\n STAssertThrows(([RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(1),nil]),nil);\n}\n\n- (void)testNonexistentKeyReturnsNil\n{\n id responseObject = [self responseObject];\n id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(0),RDJSONKey(@\"LOLOLOLOLOL\"),nil];\n STAssertNil(value, nil);\n}\n\n- (void)testReturnsNilWhenGivenNonDictionaryNonArrayObject\n{\n NSObject *object = [[NSObject alloc] init];\n id value = [RDUtilities objectFromNestedJSON:object usingCascadedKeys:RDJSONKey(@\"routes\"),nil];\n STAssertNil(value, nil);\n value = [RDUtilities objectFromNestedJSON:object usingCascadedKeys:RDJSONIndex(0),nil];\n STAssertNil(value, nil);\n}\n\n- (void)testReturnsNilWhenIndexLeadsToNonDictionaryNonArrayObject\n{\n id value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(0),RDJSONKey(@\"bounds\"),RDJSONKey(@\"northeast\"),RDJSONKey(@\"lat\"),RDJSONKey(@\"value\"),nil];\n STAssertNil(value, nil);\n value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(0),RDJSONKey(@\"bounds\"),RDJSONKey(@\"northeast\"),RDJSONKey(@\"lat\"),RDJSONIndex(0),nil];\n STAssertNil(value, nil);\n}\n\n- (void)testReturnsPrimitive\n{\n id value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(0),RDJSONKey(@\"bounds\"),RDJSONKey(@\"northeast\"),RDJSONKey(@\"lat\"),nil];\n STAssertTrue([value isKindOfClass:[NSNumber class]], nil);\n NSNumber *expected = @37.45040780;\n STAssertEqualObjects(value, expected, nil);\n}\n\n- (id)responseObject\n{\n NSString *responsePath = [[NSBundle bundleForClass:[self class]] pathForResource:@\"response\" ofType:@\"json\"];\n NSData *responseData = [NSData dataWithContentsOfFile:responsePath];\n id object = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:NULL];\n return object;\n}\n\n@end\n</code></pre>\n\n<p>It seems to provide decent coverage of the behavior to give us the freedom to change things with confidence.</p>\n\n<p>As I said, the primary issue is using conditional logic based on types rather than take advantage of polymorphism. I ended up with the following implementation:</p>\n\n<p>RDUtilities.h:</p>\n\n<pre><code>#import &lt;Foundation/Foundation.h&gt;\n\nextern NSString *const RDJSONKeyKey;\nextern NSString *const RDJSONIndexKey;\n\n#define RDJSONKey(x) @{@\"dKey\":x}\n#define RDJSONIndex(x) @{@\"aIndex\":@x}\n\n@interface RDUtilities : NSObject\n\n+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,...;\n\n@end\n</code></pre>\n\n<p>RDUtilities.m:</p>\n\n<pre><code>#import \"RDUtilities.h\"\n\nNSString *const RDJSONKeyKey = @\"dKey\";\nNSString *const RDJSONIndexKey = @\"aIndex\";\n\n@interface NSObject (RDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary;\n\n@end\n\n@implementation NSObject (RDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary\n{\n return nil;\n}\n\n@end\n\n\n@implementation NSArray (RDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary\n{\n id toReturn = nil;\n NSUInteger index = NSUIntegerMax;\n NSNumber *indexNumber = dictionary[RDJSONIndexKey];\n if ([indexNumber respondsToSelector:@selector(unsignedIntegerValue)]) {\n index = [indexNumber unsignedIntegerValue];\n }\n if (index &lt; [self count]) {\n toReturn = self[index];\n }\n\n return toReturn;\n}\n\n@end\n\n@implementation NSDictionary (RDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary\n{\n id toReturn = nil;\n id key = dictionary[RDJSONKeyKey];\n if (key) {\n toReturn = self[key];\n }\n return toReturn;\n}\n\n@end\n\n@implementation RDUtilities\n\n+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,...\n\n{\n /*** rename for clarity - Objective-C style is usually very explicit about purpose and type ***/\n NSMutableArray *mutableKeysAndIndexes = [[NSMutableArray alloc] init];\n id subObject = nil;\n\n va_list args;\n va_start(args, firstArg);\n\n // Iterate through the list of arguments.\n for (NSDictionary *arg = firstArg; arg != nil; arg = va_arg(args, NSDictionary *))\n {\n if ( [[arg allKeys] containsObject:RDJSONKeyKey] || [[arg allKeys] containsObject:RDJSONIndexKey])\n {\n [mutableKeysAndIndexes addObject:arg];\n }\n else\n {\n NSLog(@\"Invalid input types\");\n return nil;\n }\n }\n\n subObject = JSONObject;\n\n for (NSDictionary *pathDictionary in mutableKeysAndIndexes) {\n subObject = [subObject rdValueForKeyOrIndexDictionary:pathDictionary];\n }\n\n return subObject;\n}\n\n@end\n</code></pre>\n\n<p>As you can see, the complexity of the method has been reduced significantly. We no longer have hard-coded string checks, or separate code paths for arrays and dictionaries, or extra logic for the last key or index.</p>\n\n<p>As I mentioned earlier, passing an out of bounds index as an index key threw an exception; since the other errors seemed to return <code>nil</code> I decided to follow that convention with the code and I adjusted the unit tests appropriately, replacing <code>testOutOfBoundsIndexThrowsException</code> with <code>testOutOfBoundsIndexReturnsNil</code>:</p>\n\n<pre><code>- (void)testOutOfBoundsIndexReturnsNil\n{\n id responseObject = [self responseObject];\n id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@\"routes\"),RDJSONIndex(1),nil];\n STAssertNil(value, nil);\n}\n</code></pre>\n\n<p>Taking a look at this refactor, I then realized that this allows key or index arguments to not be passed within dictionaries, but rather we can simply pass the keys or indexes themselves in the argument list. I rewrote the category methods and the dictionary wrapper macros, as well as modifying the types in the <code>RDUtilities</code> class method, and ended with the following implementation:</p>\n\n<p>RDUtilities.h, second refactor:</p>\n\n<pre><code>#import &lt;Foundation/Foundation.h&gt;\n\n#define RDJSONKey(x) x\n#define RDJSONIndex(x) @x\n\n@interface RDUtilities : NSObject\n\n+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(id)firstArg,...;\n\n@end\n</code></pre>\n\n<p>RDUtilities.m, second refactor:</p>\n\n<pre><code>#import \"RDUtilities.h\"\n\n@interface NSObject (PrivateRDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndex:(id)keyOrIndex;\n\n@end\n\n@implementation NSObject (PrivateRDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndex:(id)keyOrIndex\n{\n return nil;\n}\n\n@end\n\n\n@implementation NSArray (PrivateRDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndex:(id)keyOrIndex\n{\n id toReturn = nil;\n NSUInteger index = NSUIntegerMax;\n if ([keyOrIndex respondsToSelector:@selector(unsignedIntegerValue)]) {\n index = [keyOrIndex unsignedIntegerValue];\n }\n if (index &lt; [self count]) {\n toReturn = self[index];\n }\n\n return toReturn;\n}\n\n@end\n\n@implementation NSDictionary (PrivateRDUtilityAdditions)\n\n- (id)rdValueForKeyOrIndex:(id)keyOrIndex\n{\n id toReturn = nil;\n if (keyOrIndex) {\n toReturn = self[keyOrIndex];\n }\n return toReturn;\n}\n\n@end\n\n@implementation RDUtilities\n\n+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(id)firstArg,...\n{\n NSMutableArray *mutableKeysAndIndexes = [[NSMutableArray alloc] init];\n id subObject = nil;\n\n va_list args;\n va_start(args, firstArg);\n\n // Iterate through the list of arguments.\n for (id arg = firstArg; arg != nil; arg = va_arg(args, id))\n {\n [mutableKeysAndIndexes addObject:arg];\n }\n\n subObject = JSONObject;\n\n for (id indexOrKey in mutableKeysAndIndexes) {\n subObject = [subObject rdValueForKeyOrIndex:indexOrKey];\n }\n\n return subObject;\n}\n\n@end\n</code></pre>\n\n<p>This code is considerably simpler, and opens up more opportunities for flexibility. One could develop a system of passing strings that represent a key/index path, much like the existing Cocoa key paths work. There are other opportunities for passing arguments now that can allow more dynamic use of the method. You could potentially refactor all of the work into categories, and then simply call a method specifying the order of keys and indexes on the deserialized JSON object without having to involve a separate object.</p>\n\n<p>Bottom line, make sure that any time you are using an Objective-C object's class as control flow, you take a step back and look at how you could simplify that by use of polymorphism and other object oriented principles.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T06:55:15.480", "Id": "48125", "Score": "0", "body": "Carl, thanks for your suggestions. I've read through this and understood most of it (new to iOS [: ). I will take your suggestion and further refactor it to be categories on NSDictionary and NSArray. Also, this was inspired by the idea of NSIndexPath - perhaps I could make something conceptually similar for traversing JSON. My final question -- where can I read about or understand best practices for figuring out \"how you could simplify that by the use of polymorphism and other object oriented principles\". I guess I don't understand what's wrong with using an Object's class conditionals?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T16:15:25.600", "Id": "48187", "Score": "0", "body": "You're welcome! Why to avoid conditional logic based on the type of an object is a big subject, but I'd say it boils down to correct assignment of responsibilities of an object. Consider `NSArray` and `NSDictionary`'s implementation of `valueForKey:`. They both implement what makes sense to them. Now imagine if client code had to implement that, and test the class of an object - there would be a lot of duplicated code, which is bad. Also see the [\"replace conditional with polymorphism\" refactoring](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-12T18:04:40.767", "Id": "29659", "ParentId": "28201", "Score": "3" } } ]
{ "AcceptedAnswerId": "29659", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T17:32:46.420", "Id": "28201", "Score": "2", "Tags": [ "objective-c", "json", "ios" ], "Title": "Pulling Objects & Values From Arbitrarily Nested JSON" }
28201
<p>I have to store and return data on multitasking requests. If data is missing, I schedule loading and return null. I'm using some nubie scheduling by saving current jobs in a list. Also I need data request to be locked during writing. .NET 4.0</p> <p>How can I schedule and lock properly?</p> <pre><code>private ConcurrentDictionary&lt;string, IDataSet&gt; data; private List&lt;string&gt; loadingNow; public IDataSet GetData(string dataId) { if (loadingNow.Contains(dataId)) return null; // Currently loading. Return null if (data.ContainsKey(dataId)) return data[dataId]; // Return data // Schedule loading async. Return null. loadingNow.Add(dataId); dataIoAsync.LoadDataAsync(dataParams); return null; } private void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e) { loadingNow.Remove(e.DataId); data.TryAdd(e.DataId, e.DataSet); OnDataFileLoaded(e.DataId); } </code></pre> <p>EDIT: Dictionary replaced with ConcurrentDictionary</p>
[]
[ { "body": "<p>Instead of keeping track of what's being loaded, you can represent that as a state by wrapping <code>IDataSet</code> into a class:</p>\n\n<pre><code>private sealed class DataSetResult\n{\n public volatile IDataSet Result;\n}\n</code></pre>\n\n<p>When an instance of this class is created, start loading the data. You can then just return the value of the <code>Result</code> field - if it is <code>null</code>, the data is still being loaded:</p>\n\n<pre><code>private readonly ConcurrentDictionary&lt;string, Lazy&lt;DataSetResult&gt;&gt; _data;\n\npublic IDataSet GetData(string dataId)\n{\n var dataSet = _data.GetOrAdd(\n dataId, \n _ =&gt; new Lazy&lt;DataSetResult&gt;(\n () =&gt;\n {\n var result = new DataSetResult();\n dataIoAsync.LoadDataAsync(dataParams);\n return result;\n }\n )\n );\n\n return dataSet.Value.Result;\n}\n\nprivate void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e)\n{\n _data[e.DataId].Value.Result = e.DataSet;\n OnDataFileLoaded(e.DataId);\n}\n</code></pre>\n\n<p>The <code>Lazy&lt;DataSetResult&gt;</code> above ensures that data is retrieved at most once for a given id.</p>\n\n<p>Personally, however, I would prefer to return <code>Task&lt;IDataSet&gt;</code> from this method, as it is really up to the caller to decide whether they want to wait for the result to become available or not. Using <code>Task</code> also allows you to report any exceptions to the client:</p>\n\n<pre><code>private readonly ConcurrentDictionary&lt;string, Lazy&lt;TaskCompletionSource&lt;IDataSet&gt;&gt;&gt; _data;\n\npublic Task&lt;IDataSet&gt; GetDataAsync(string dataId)\n{\n var dataSet = _data.GetOrAdd(\n dataId, \n _ =&gt; new Lazy&lt;TaskCompletionSource&lt;IDataSet&gt;&gt;(\n () =&gt;\n {\n var result = new TaskCompletionSource&lt;IDataSet&gt;();\n dataIoAsync.LoadDataAsync(dataParams);\n return result;\n }\n )\n );\n\n return dataSet.Value.Task;\n}\n\nprivate void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e)\n{\n _data[e.DataId].Value.TrySetResult(e.DataSet);\n OnDataFileLoaded(e.DataId);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T07:15:47.113", "Id": "44086", "Score": "0", "body": "It's very interesting. I have tried something similar. Storing null dataSet in _data, but there was a side effect. This wrapping may solve the problem. I have to read further about Lazy<DataSetResult>. I'll test your solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T06:16:30.170", "Id": "28222", "ParentId": "28203", "Score": "1" } } ]
{ "AcceptedAnswerId": "28222", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T19:28:45.123", "Id": "28203", "Score": "1", "Tags": [ "c#", ".net", "multithreading", "locking" ], "Title": "Loading data async with queue. Proper write only locking and scheduling" }
28203
<p>I've just downloaded a script and would like to use it as a contact form on my site. The problem is I'm a front-end dev with little knowledge of securing PHP code. So, could you please have a look and let me know if there are any glaring problems with security with this script that uses phpMailer to send?</p> <p>As you can see, I haven't done much with the SMTP setting at the bottom, but it still seems to work ok on my server.</p> <pre><code>&lt;?php $name = trim($_POST['name']); $email = $_POST['email']; $comments = $_POST['comments']; $site_owners_email = 'email@someemail.com'; // Replace this with your own email address $site_owners_name = 'Name'; // replace with your name if (strlen($name) &lt; 2) { $error['name'] = "Please enter your name"; } if (!preg_match('/^[a-z0-9&amp;\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) { $error['email'] = "Please enter a valid email address"; } if (strlen($comments) &lt; 1) { $error['comments'] = "Please leave a comment."; } if (!$error) { require_once('class.phpmailer.php'); $mail = new PHPMailer(); $mail-&gt;From = $email; $mail-&gt;FromName = $name; $mail-&gt;Subject = "Website Contact Form"; $mail-&gt;AddAddress($site_owners_email, $site_owners_name); $mail-&gt;AddAddress('email@someemail.com', 'Name'); $mail-&gt;Body=" Name: $name Email: $email Comments: $comments"; $mail-&gt;SMTPAuth = true; // turn on SMTP authentication $mail-&gt;Username = "email@someemail.com"; // SMTP username $mail-&gt;Password = ""; // SMTP password $mail-&gt;Send(); echo "&lt;li class='success' id='successMessage' &gt; Congratulations, " . $name . " We've received your email. We'll be in touch as soon as we possibly can!&lt;/li&gt;&lt;li id='closeBtn'&gt;&lt;a href='#'&gt;close&lt;/a&gt;&lt;/li&gt;&lt;li id='homeLink'&gt;&lt;a href='http://mosaicwebstudio.com/sandbox/forms/mod-ajax2' &gt;return to home page&lt;/a&gt;&lt;/li&gt;"; } # end if no error else { $response = (isset($error['name'])) ? "&lt;li&gt;" . $error['name'] . "&lt;/li&gt; \n" : null; $response .= (isset($error['email'])) ? "&lt;li&gt;" . $error['email'] . "&lt;/li&gt; \n" : null; $response .= (isset($error['comments'])) ? "&lt;li&gt;" . $error['comments'] . "&lt;/li&gt;" : null; echo $response; } # end if there was an error sending ?&gt; </code></pre>
[]
[ { "body": "<p>You are pushing whatever users enter in the comment form via email <strong>unfiltered</strong>.</p>\n\n<p>In simpler words: you will need to filter all data the user enters, to make sure you are safe from the usual mail injects.</p>\n\n<p>Example:</p>\n\n<pre><code>function my_filter($data)\n{\n $data = preg_replace('=((&lt;CR&gt;|&lt;LF&gt;|0x0A/%0A|0x0D/%0D|\\\\n|\\\\r)\\S).*=i', '', $data);\n $data= trim(preg_replace('=[\\r\\n]+=', '', $data)); \n return $data;\n}\n</code></pre>\n\n<p>At least run the user-defined data trough the filter to be safe from email header injects etc. just in case the <em>PHP mailing class</em> you are using doesn't do that for you.</p>\n\n<pre><code>$name = my_filter($_POST['name']);\n$email = my_filter($_POST['email']);\n$comments = my_filter($_POST['comments']);\n</code></pre>\n\n<p>Then, it should be somewhat safe. </p>\n\n<p>Another thing you might considder adding is some kind of captcha to your mailing/comment form to prevent bots to auto-post thousands of messages without anyone stopping them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T06:51:34.533", "Id": "52070", "Score": "0", "body": "`filter_var` to validate the email is all you need. `PHPMailer` does sanitize (not enough, though) the input, but your approach is, IMO, a tad over the top..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T16:17:00.003", "Id": "89653", "Score": "0", "body": "@EliasVanOotegem Note that **OP did not specify which version of PHP is used**. `filter_var` is only available in PHP 5.2.0 and later versions. **Also**, `filter_var` has a lot of problems! Eg: [will not validate valid domain names with foreign characters](http://de2.php.net/manual/en/function.filter-var.php#111828), [there are email addresses FILTER_VALIDATE_EMAIL rejects but RFC5321 specifically permits](http://de2.php.net/manual/en/function.filter-var.php#112492), [it will not protect you from injection-attacks](http://de2.php.net/manual/en/function.filter-var.php#108769), and much more…" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T07:02:29.683", "Id": "89764", "Score": "0", "body": "Come on, 5.2 was released about 8 years ago, is no longer actively maintained either. The common and safe assumption to make is people are working with PHP 5.3 and up (oh, and `filter_var` has its problems, true enough, but since its release, there have been a lot of changes and tweaks to the email filter)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T09:50:55.513", "Id": "165101", "Score": "0", "body": "Your *“common and safe assumption”* breaks as soon as you hit Murphy's law in relation to production servers. Actually, you´re saying it yourself: *“since its release, there have been a lot of changes and tweaks to the email filter”*, which already hints at the differences and issues of different PHP versions. Practically, the “changes and tweaks” contradict your *”safe assumption”*. Anyway – since OP asked about potentially securing his/her PHP code, my answer that OP doesn't use the needed filtering to prevent injections is no where near *“a tad over the top”*. Instead, it's pretty on-point." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T18:24:20.117", "Id": "28424", "ParentId": "28205", "Score": "0" } }, { "body": "<p>As <a href=\"https://codereview.stackexchange.com/a/28424/27237\">@e-sushi remarked in his answer</a>: you're still vulnerable to header injections. Though his approach is rather complex, and (when applied to <code>$email</code>, not required if you validate the email address the way I do (explained further down), but for the subject, and message body, you could use these simpler, and (IMO, therefore) better ways to tackle the header-injection issue:</p>\n\n<pre><code>$mail-&gt;Body = str_ireplace(\n array(\"%0a\", \"%0d\", '0x0A'), '',//PHPMailer replaces \\r\\n already for you\n 'your string here...'\n); \n//a Core-function alternative:\n$body = 'your string here';\nfilter_var($body, FILTER_SANITIZE_EMAIL);//will alter $body\n$mail-&gt;Body = $body;\n</code></pre>\n\n<p>More details on the caveats/benefits of each approach <a href=\"http://www.codeproject.com/Articles/428076/PHP-Mail-Injection-Protection-and-E-Mail-Validatio\" rel=\"nofollow noreferrer\">can be found here</a>. Because you're setting the <code>$name</code> along side the email address, too as the <em>from</em> of the email, you <em>should</em> pass the <code>$name</code> value to either one of these filters, too.</p>\n\n<p>Your code is attempting to validate an email address using a regular expression that is, at best, slightly off. There is a built-in function that can validate email addresses, without an inaccurate, too restrictive and slow regular expression, called <a href=\"http://www.php.net/filter_var\" rel=\"nofollow noreferrer\"><code>filter_var</code></a>.</p>\n\n<pre><code>if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))\n{\n exit('Invalid email');\n}\n</code></pre>\n\n<p>The result is that, while your regex doesn't allow for: <code>some.name@site.info</code> to be used as an email address (even though it's valid), <code>filter_Var</code> <em>will</em> accept it.<Br/>\nUnlike your regex, which, because it uses the <code>s</code> modifier allows for line-breaks in your email (for some reason), this won't... not blindly.<Br/>\nIf, however, you wish to keep on using a regular expression, here's a PCRE expression that is (almost) fully RFC822 compliant:</p>\n\n<pre><code>/(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\&lt;(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\&gt;(?:(?:\\r\\n)?[ \\t])*)|(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\&lt;(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()&lt;&gt;@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\&gt;(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\&lt;(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\&gt;(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)/\n</code></pre>\n\n<p>Source: <a href=\"http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html\" rel=\"nofollow noreferrer\">ex-parrot</a></p>\n\n<p>I think it's clear which one of the validations is the more elegant one...</p>\n\n<p>The name (<code>$name</code>) is a trimmed version of the POST var. That's good, because you <em>know</em> that, if the <code>strlen($name) &gt; 2</code>, you're not just counting whitespace. However, you still <em>are</em> counting possible whitespace-only input when validating the <code>$comment</code> variable. </p>\n\n<p>I'd suggest additional processing on both of these values:</p>\n\n<pre><code>$name = trim(html_entity_decode($_POST['name']));\nif (strlen($name) &lt; 2 || !preg_match('/^[^\\d]+\\s*[^\\d]*/',$name))\n{//nobody is called R2D2 in real-life!\n exit('name is too short ( &lt; 2 chars) or contains numeric chars');\n}\n$comment = trim(strip_tags(html_entity_decode($_POST['comment'])));\nif (!strlen($comment))\n{//empty comment\n exit('No comment supplied');\n}\n</code></pre>\n\n<p>As you can see, I've also used <code>html_entity_decode</code> and, for the comments at least <code>strip_tags</code> to remove any markup that might have been passed. This is often overlooked, so if I were to post a comment saying:</p>\n\n<pre><code>&amp;nbsp;&lt;br/&gt;&amp;nbsp;\n</code></pre>\n\n<p>Even <code>trim</code> would see this as a valid comment, whereas it actually is little more than whitespace</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T15:57:36.023", "Id": "89651", "Score": "0", "body": "`//nobody is called R2D2 in real-life!` – Well, let’s just hope **[Kenny Baker](http://en.wikipedia.org/wiki/Kenny_Baker_%28English_actor%29)** never tries to contact him using that contact form. ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T06:37:50.033", "Id": "32557", "ParentId": "28205", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T19:54:24.633", "Id": "28205", "Score": "4", "Tags": [ "php", "form", "email" ], "Title": "phpMailer script for a contact form" }
28205
<p>I'm trying to find the closest point (Euclidean distance) from a user-inputted point to a list of 50,000 points that I have. Note that the list of points changes all the time. and the closest distance depends on when and where the user clicks on the point.</p> <pre><code>#find the nearest point from a given point to a large list of points import numpy as np def distance(pt_1, pt_2): pt_1 = np.array((pt_1[0], pt_1[1])) pt_2 = np.array((pt_2[0], pt_2[1])) return np.linalg.norm(pt_1-pt_2) def closest_node(node, nodes): pt = [] dist = 9999999 for n in nodes: if distance(node, n) &lt;= dist: dist = distance(node, n) pt = n return pt a = [] for x in range(50000): a.append((np.random.randint(0,1000),np.random.randint(0,1000))) some_pt = (1, 2) closest_node(some_pt, a) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T15:56:12.700", "Id": "168904", "Score": "2", "body": "I was working on a similar problem and found [this](http://stackoverflow.com/questions/10818546/finding-index-of-nearest-point-in-numpy-arrays-of-x-and-y-coordinates). Also, [`Scipy.spatial.KDTree`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html) is the way to go for such approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-12T06:14:33.830", "Id": "176604", "Score": "0", "body": "The part that says \"the list changes all the time\" can be expanded a bit, which might hint some ideas to increase the code performance maybe. Is the list updated randomly, or some points are added every some-seconds, and some points are lost?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-17T01:19:41.270", "Id": "353293", "Score": "0", "body": "The ball tree method in scikit-learn does this efficiently if the same set of points has to be searched through repeatedly. The points are sorted into a tree structure in a preprocessing step to make finding the closest point quicker. http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html" } ]
[ { "body": "<p>It will certainly be faster if you vectorize the distance calculations:</p>\n\n<pre><code>def closest_node(node, nodes):\n nodes = np.asarray(nodes)\n dist_2 = np.sum((nodes - node)**2, axis=1)\n return np.argmin(dist_2)\n</code></pre>\n\n<p>There may be some speed to gain, and a lot of clarity to lose, by using one of the dot product functions:</p>\n\n<pre><code>def closest_node(node, nodes):\n nodes = np.asarray(nodes)\n deltas = nodes - node\n dist_2 = np.einsum('ij,ij-&gt;i', deltas, deltas)\n return np.argmin(dist_2)\n</code></pre>\n\n<p>Ideally, you would already have your list of point in an array, not a list, which will speed things up a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T03:28:57.380", "Id": "44073", "Score": "1", "body": "Thanks for the response, do you mind explaining why the two methods are faster? I'm just curious as I don't come from a CS background" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T03:54:36.320", "Id": "44074", "Score": "6", "body": "Python for loops are very slow. When you run operations using numpy on all items of a vector, there are hidden loops running in C under the hood, which are much, much faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T23:25:23.140", "Id": "28210", "ParentId": "28207", "Score": "41" } }, { "body": "<p>All your code could be rewritten as:</p>\n\n<pre><code>from numpy import random\nfrom scipy.spatial import distance\n\ndef closest_node(node, nodes):\n closest_index = distance.cdist([node], nodes).argmin()\n return nodes[closest_index]\n\na = random.randint(1000, size=(50000, 2))\n\nsome_pt = (1, 2)\n\nclosest_node(some_pt, a)\n</code></pre>\n\n<hr>\n\n<p>You can just write <code>randint(1000)</code> instead of <code>randint(0, 1000)</code>, the documentation of <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html\" rel=\"noreferrer\"><code>randint</code></a> says:</p>\n\n<blockquote>\n <p>If <code>high</code> is <code>None</code> (the default), then results are from <code>[0, low)</code>.</p>\n</blockquote>\n\n<p>You can use the <code>size</code> argument to <code>randint</code> instead of the loop and two function calls. So:</p>\n\n<pre><code>a = []\nfor x in range(50000):\n a.append((np.random.randint(0,1000),np.random.randint(0,1000)))\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>a = np.random.randint(1000, size=(50000, 2))\n</code></pre>\n\n<p>It's also much faster (twenty times faster in my tests).</p>\n\n<hr>\n\n<p>More importantly, <code>scipy</code> has the <code>scipy.spatial.distance</code> module that contains the <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist\" rel=\"noreferrer\"><code>cdist</code></a> function:</p>\n\n<blockquote>\n <p><code>cdist(XA, XB, metric='euclidean', p=2, V=None, VI=None, w=None)</code></p>\n \n <p>Computes distance between each pair of the two collections of inputs.</p>\n</blockquote>\n\n<p>So calculating the <code>distance</code> in a loop is no longer needed.</p>\n\n<p>You use the for loop also to find the position of the minimum, but this can be done with the <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argmin.html\" rel=\"noreferrer\"><code>argmin</code></a> method of the <code>ndarray</code> object.</p>\n\n<p>Therefore, your <code>closest_node</code> function can be defined simply as:</p>\n\n<pre><code>from scipy.spatial.distance import cdist\n\ndef closest_node(node, nodes):\n return nodes[cdist([node], nodes).argmin()]\n</code></pre>\n\n<hr>\n\n<p>I've compared the execution times of all the <code>closest_node</code> functions defined in this question:</p>\n\n<pre><code>Original:\n1 loop, best of 3: 1.01 sec per loop\n\nJaime v1:\n100 loops, best of 3: 3.32 msec per loop\n\nJaime v2:\n1000 loops, best of 3: 1.62 msec per loop\n\nMine:\n100 loops, best of 3: 2.07 msec per loop\n</code></pre>\n\n<p>All vectorized functions perform hundreds of times faster than the original solution.</p>\n\n<p><code>cdist</code> is outperformed only by the second function by Jaime, but only slightly.\nCertainly <code>cdist</code> is the simplest.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-14T22:58:57.373", "Id": "134918", "ParentId": "28207", "Score": "20" } }, { "body": "<p>By using a <a href=\"https://en.wikipedia.org/wiki/K-d_tree\" rel=\"nofollow noreferrer\">kd-tree</a> computing the distance between all points it's not needed for this type of query. It's also <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html\" rel=\"nofollow noreferrer\">built in into scipy</a> and can speed up these types of programs enormously going from O(n^2) to O(log n), if you're doing many queries. If you only make one query, the time constructing the tree will dominate the computation time.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from scipy.spatial import KDTree\nimport numpy as np\nn = 10\nv = np.random.rand(n, 3)\nkdtree = KDTree(v)\nd, i = kdtree.query((0,0,0))\nprint(&quot;closest point:&quot;, v[i])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T13:48:07.273", "Id": "255890", "ParentId": "28207", "Score": "1" } } ]
{ "AcceptedAnswerId": "28210", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T20:19:34.250", "Id": "28207", "Score": "47", "Tags": [ "python", "performance", "numpy", "clustering" ], "Title": "Finding the closest point to a list of points" }
28207