body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I need help with a simple Google Apps Script I've written. The script finds days on which no all-day events have been scheduled, across multiple calendars.</p> <p>I'm fairly certain the main issue is the fact that I'm making an API call to get all owned calendars, <em>then</em> I'm making 5 API calls on each of these calendars to retrieve each day's (Mon - Fri) events.</p> <p>Currently, it takes about 60 seconds to run on an account with 11 owned calendars. Is there anything that can be done to optimize?</p> <pre><code>var one_day = 86400000; //24 * 60 * 60 * 1000 var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var startDay = nextMonday(new Date()); // Script-as-app template. function doGet() { var app = UiApp.createApplication(); var button = app.createButton('Find Blanks').setId('button'); var loader = app.createImage('http://preloaders.net/preloaders/496/Flip%20Flop.gif').setVisible(false).setId('loader'); var blanks = app.createHTML().setId('blanksArea').setHTML('Click button to find calendar blanks for week of ' + startDay); app.add(button); app.add(app.createHTML('&lt;br/&gt;')); app.add(loader); app.add(blanks); var clientHandler = app.createClientHandler().forEventSource().setEnabled(false).forTargets(loader).setVisible(true).forTargets(blanks).setHTML('Processing for week of ' + startDay); var handler = app.createServerHandler('serverHandler'); button.addClickHandler(clientHandler); button.addClickHandler(handler); return app; } function serverHandler(e) { var app = UiApp.getActiveApplication(); var button = app.getElementById('button'); var blanks = app.getElementById('blanksArea'); var calendarsWithBlanks = getCalendarsWithBlanks(); blanks.setHTML(calendarsWithBlanks.length ? calendarsWithBlanks.join('&lt;br/&gt;') : 'There are no blanks'); app.getElementById('loader').setVisible(false); button.setEnabled(true); app.close(); return app; } function getCalendarsWithBlanks() { var calendars = CalendarApp.getAllOwnedCalendars(); var calendarsWithBlanks = []; for(var i = 0; i &lt; calendars.length; i++) { var calendar = calendars[i]; var calendarName = calendar.getName(); var blankDays = checkCalendarForBlanks(calendar, startDay); if(blankDays.length) { calendarsWithBlanks.push(calendarName + ' has ' + blankDays.join(', ') + ' blank') } } return calendarsWithBlanks; } function checkCalendarForBlanks(calendar, startDay) { var blankDays = []; for(var d = 0; d &lt; 5; d++) { var currDay = new Date(startDay.getTime() + (d * one_day)); var events = getEventsForDay(calendar, currDay); var foundAllDayEvent = false; for(var e = 0; e &lt; events.length; e++) { if(events[e].isAllDayEvent()) { foundAllDayEvent = true; break; } } if(!foundAllDayEvent) { blankDays.push(days[currDay.getDay()]); } } return blankDays; } function nextMonday(date) { var today = date; today.setUTCHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0); var day = today.getDay(); var offset = 8 - day var next_monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+offset); return next_monday; } function getEventsForDay(calendar, date) { /* !!!KLUDGE ALERT!!! * This is a kludge. The API method getEventsForDay is wonky: http://stackoverflow.com/questions/11870304/google-apps-script-geteventsforday-returns-invalid-recurring-events */ var startOfDay = new Date(date.getTime()); startOfDay.setUTCHours(0); startOfDay.setMinutes(0); startOfDay.setSeconds(0); startOfDay.setMilliseconds(0); var endOfDay = new Date(startOfDay.getTime() + one_day); return calendar.getEvents(startOfDay, endOfDay) } </code></pre>
[]
[ { "body": "<p>I flipped your logic a bit in the example below. I only do one API call per calendar and then do all of the processing in the client. It seems a bit faster for me, but I'm not seeing the 60 second processing time that you are. So your results my vary.</p>\n\n<pre><code>var one_day = 86400000; //24 * 60 * 60 * 1000\nvar days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nvar startDay = nextMonday(new Date());\n\n// Script-as-app template.\nfunction doGet() {\n var app = UiApp.createApplication();\n\n var button = app.createButton('Find Blanks').setId('button');\n var loader = app.createImage('http://preloaders.net/preloaders/496/Flip%20Flop.gif').setVisible(false).setId('loader');\n var blanks = app.createHTML().setId('blanksArea').setHTML('Click button to find calendar blanks for week of ' + startDay);\n\n app.add(button);\n app.add(app.createHTML('&lt;br/&gt;'));\n app.add(loader);\n app.add(blanks);\n\n var clientHandler = app.createClientHandler().forEventSource().setEnabled(false).forTargets(loader).setVisible(true).forTargets(blanks).setHTML('Processing for week of ' + startDay);\n var handler = app.createServerHandler('serverHandler');\n\n button.addClickHandler(clientHandler);\n button.addClickHandler(handler);\n\n return app;\n}\n\nfunction serverHandler(e) {\n var app = UiApp.getActiveApplication();\n\n var button = app.getElementById('button');\n var blanks = app.getElementById('blanksArea');\n var calendarsWithBlanks = getCalendarsWithBlanks();\n\n blanks.setHTML(calendarsWithBlanks.length ? calendarsWithBlanks.join('&lt;br/&gt;') : 'There are no blanks');\n\n app.getElementById('loader').setVisible(false);\n button.setEnabled(true);\n\n app.close();\n return app;\n}\n\nfunction test_getCalendarsWithBlanks() {\n getCalendarsWithBlanks().forEach(function(calendarResult) {\n Logger.log(calendarResult);\n });\n }\n\nfunction getCalendarsWithBlanks()\n{\n var calendars = CalendarApp.getAllOwnedCalendars();\n var calendarsWithBlanks = [];\n for(var i = 0; i &lt; calendars.length; i++)\n {\n var calendar = calendars[i];\n var calendarName = calendar.getName();\n var blankDays = checkCalendarForBlanks(calendar, startDay);\n if(blankDays.length )\n {\n calendarsWithBlanks.push(calendarName + ' has ' + blankDays.join(', ') + ' blank')\n }\n }\n return calendarsWithBlanks;\n}\n\nfunction checkCalendarForBlanks(calendar, startDay)\n{\n var blankDays = [],\n allDayEventsPerDay = [0,0,0,0,0,0,0],\n endDate = new Date(startDay.getTime() + (4 * one_day)),\n // get all events for the next work week\n allEventsForNextWorkWeek = calendar.getEvents(startDay, endDate);\n\n //count number of all day events on each day\n allEventsForNextWorkWeek.forEach(function(event){\n if(event.isAllDayEvent()) {\n //count each day the event is on\n determineDaysOnWhichEventTakesPlace(event,startDay,endDate).forEach(function(eventDate){\n allDayEventsPerDay[eventDate.getDay()]++; \n });\n }\n });\n\n //figure out which ones have 0 (ie blank days)\n allDayEventsPerDay.forEach(function(count, offset){\n if(count === 0) {\n blankDays.push(days[offset]);\n }\n });\n\n return blankDays;\n}\n\nfunction determineDaysOnWhichEventTakesPlace(event, lowerLimit, upperLimit) {\n var startDate = new Date(Math.max(event.getAllDayStartDate().getTime(), lowerLimit.getTime())),\n endDate = new Date(Math.min(event.getAllDayEndDate().getTime(), upperLimit.getTime())),\n dates =[],\n eventDate;\n\n for(eventDate = startDate; eventDate&lt; endDate; eventDate = new Date(eventDate.getTime() + (one_day))) {\n dates.push(eventDate);\n }\n return dates;\n}\n\nfunction nextMonday(date)\n{\n var today = date;\n today.setUTCHours(0);\n today.setMinutes(0);\n today.setSeconds(0);\n today.setMilliseconds(0);\n var day = today.getDay();\n var offset = 8 - day\n var next_monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+offset);\n return next_monday;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-02T16:05:38.630", "Id": "91531", "Score": "0", "body": "This is definitely faster, but something has gone hinky and it's now reporting false positives (blanks are reported where they don't exist). In any case, you've solved the performance issue. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-02T16:31:00.823", "Id": "91533", "Score": "2", "body": "There could be a bit of wonkiness in `checkCalendarForBlanks()` with respect to how start and end dates are defined by all day events. Perhaps adding the total number of seconds per day isn't the way to go. Maybe you need to explicitly build date objects for each day and then do a comparison." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-01T13:23:19.590", "Id": "52195", "ParentId": "45242", "Score": "3" } } ]
{ "AcceptedAnswerId": "52195", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T17:25:43.657", "Id": "45242", "Score": "7", "Tags": [ "performance", "datetime", "google-app-engine", "google-apps-script" ], "Title": "Google Apps Script for finding empty days on multiple calendars" }
45242
<p>Ok I am making unit converter and I have attached temperature conversion code below. The problem with this code I think is that I have written function for each and every single unit to convert to another unit.</p> <p>So in code below there is one function to covert Celsius into Fahrenheit, Kelvin, Renkien and Newton. Then another function to convert Fahrenheit to Celsius,Kelvin, Renkien and Newton.</p> <p>Now I do understand that every unit is related to one another. But I just can't think of a way if this conversion can be done using single function such that first you choose your source and then destination and using that without using five different function I can just finish in one.</p> <p>Another way I thought of this was I can may be use dictionaries rather then using so many if else conditions but I would like know which one is more optimized in terms of both time and space complexity.</p> <p>class TempConv:</p> <pre><code>def __init__(self,source,dest,val): self.frm=source self.to=dest self.x=val self.ans=0 def setFrm(self,arg): self.frm=arg def setTo(self,arg): self.to=arg def setX(self,arg): self.x=arg def calculate(self): if self.x is "celc": self.ans=self.celcToAny() elif self.x is "farh": self.ans=self.farhToAny() elif self.x is "kel": self.ans=self.kelToAny() elif self.x is "renk": self.ans=self.renkToAny() elif self.x is "newt": self.ans=self.newtToAny() else: self.ans=self.x #Celcius to Any def celcToAny(self): if self.to is "farh": return (float(self.x)*1.8)+32 elif self.to is "kel": return float(self.x)+273.15 elif self.to is "renk": return (flaot(self.x)+273.15)*1.8 elif self.to is "newt": return float(self.x)*0.33 else: return self.x #Fahrenheit to Any def fahrToAny(self): if self.to is "celc": return (float(self.x)-32)*0.555555556 elif self.to is "kel": return (float(self.x)+459.67)*0.555555556 elif self.to is "renk": return float(self.x)+459.67 elif self.to is "newt": return (float(self.x)-32)*0.183333333 else: return self.x #Kelvin to Any def kelToAny(self): if self.to is "farh": return (float(self.x)*1.8)-459.67; elif self.to is "celc": return float(self.x)-273.15 elif self.to is "renk": return float(self.x)*1.8 elif self.to is "newt": return (float(self.x)-273.15)*0.33 else: return self.x #Rankine to Any def renkToAny(self): if self.to is "farh": return float(self.x)-459.67; elif self.to is "celc": return (float(self.x)-491.67)*0.555555556 elif self.to is "kel": return float(self.x)*0.555555556 elif self.to is "newt": return (float(self.x)-491.67)0.183333333 else: return self.x #Newton to Any def newtToAny(self): if self.to is "farh": return (float(self.x)*5.454545455)+32 elif self.to is "kel": return (float(self.x)*3.030303030)+273.15 elif self.to is "renk": return (flaot(self.x)*5.454545455)+491.67 elif self.to is "celc": return float(self.x)*3.030303030 else: return self.x </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:53:21.640", "Id": "78816", "Score": "0", "body": "Does x have to remain constant?" } ]
[ { "body": "<p>There is not much need for a class for what you are after. Storing all the conversion factors in a dictionary, you could simply do something like:</p>\n\n<pre><code>def convert_temp(val, from_, to_):\n if from_[0] == to_[0]:\n return val\n off1, mult, off2 = convert_temp.data[from_[0]][to_[0]]\n return (val + off1) * mult + off2\nconvert_temp.data = {'C' : {'F' : (0, 1.8, 32)},\n 'F' : {'C' : (-32, 0.555555556, 0)}}\n</code></pre>\n\n<p>And now:</p>\n\n<pre><code>&gt;&gt;&gt; convert_temp(50, 'C', 'F')\n122.0\n&gt;&gt;&gt; convert_temp(122, 'F', 'C')\n50.000000039999996\n</code></pre>\n\n<p>You would of course have a larger dictionary with all possible conversions. You could get fancy and store only half the conversions:</p>\n\n<pre><code>def convert_temp2(val, from_, to_):\n if from_[0] == to_[0]:\n return val\n try:\n off1, mult, off2 = convert_temp2.data[from_[0]][to_[0]]\n except KeyError:\n off2, mult, off1 = convert_temp2.data[to_[0]][from_[0]]\n off1 = -off1\n off2 = -off2\n mult = 1 / mult\n return (val + off1) * mult + off2\nconvert_temp2.data = {'C' : {'F' : (0, 1.8, 32)}}\n\n&gt;&gt;&gt; convert_temp2(50, 'C', 'F')\n122.0\n&gt;&gt;&gt; convert_temp2(122, 'F', 'C')\n50.0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:35:52.667", "Id": "45251", "ParentId": "45248", "Score": "3" } }, { "body": "<p>I would probably choose one type as the standard type of which I convert all types to as an intermediate step, to cut down on code.</p>\n\n<pre><code>def farhTocelc(self):\n self.setFrm(\"celc\")\n self.x = (float(self.x)-32)*0.555555556\ndef kelTocalc(self):\n self.setFrm(\"celc\")\n self.x = float(self.x)-273.15\ndef renkTocelc(self):\n self.setFrm(\"celc\")\n self.x = (float(self.x)-491.67)*0.555555556\ndef newtTocelc(self):\n self.setFrm(\"celc\")\n self.x = float(self.x)*3.030303030\ndef celcTocelc(self):\n self.setFrm(\"celc\")\n self.x = float(self.x)\n\ndef celcTofarh(self):\n self.setFrm(\"farh\") \n self.x = (float(self.x)*1.8)+32.0\ndef celcTokel(self):\n self.setFrm(\"kel\")\n self.x = float(self.x)+273.15\ndef celcTorenk(self):\n self.setFrm(\"renk\")\n self.x = (float(self.x)+273.15)*1.8\ndef celcTonewt(self):\n self.setFrm(\"newt\")\n self.x = float(self.x)*0.33\n</code></pre>\n\n<p>Then have the <code>init</code>, <code>setTo,</code> and <code>setFrm</code> functions change the values of <code>to</code> and <code>frm</code> functions instead of strings.</p>\n\n<pre><code>def __init__(self,source,dest,val):\n self.setFrm(source)\n self.setTo(dest)\n self.x = val\n self.ans = 0\n\ndef setFrm(self,arg):\n if arg + \"Tocelc\" in locals().keys():\n self.frm = locals()[arg + \"Tocelc\"]\n else:\n raise Exception(\"invalid source\")\n\ndef setTo(self,arg):\n if arg + \"Tocelc\" in locals().keys():\n self.to = locals()[\"celcTo\"+arg]\n else:\n raise Exception(\"invalid dest\")\n</code></pre>\n\n<p>Now in calculate you can just do</p>\n\n<pre><code>def calculate(self):\n self.frm()\n self.to()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T19:46:33.483", "Id": "45252", "ParentId": "45248", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:32:49.860", "Id": "45248", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Python Unit Coversion Code Optimization in terms of Space and Time Complexity" }
45248
<p>I have a macro that makes comparisons and then this macro exports all of the changes based on if the information doesn't match. I have it so that each column gets their own worksheet in the new workbook. I am using 7 different counting integers and it takes a very long time because I am exporting over 60k rows.</p> <p>Question: is there a faster way to execute this code? Can a UDF be used? if so how?</p> <pre><code>Dim ws As Worksheet Dim wb2 As Workbook Set wb = Application.Workbooks("Total Database Update_WORKING.xlsm") Set ws = wb.Worksheets("Results") Set wb2 = Application.Workbooks.Open("C:\Import Update.xlsx") i = 2 ii = 2 iii = 2 iiii = 2 iiiii = 2 iiiiii = 2 iiiiii = 2 k = 2 wb2.Activate Do While ws.Cells(k, 1) &lt;&gt; "" If ws.Cells(k, 4) = "No Match" Then wb2.Worksheets("AD UPDATE").Cells(i, 1) = ws.Cells(k, 1) wb2.Worksheets("AD UPDATE").Cells(i, 2) = ws.Cells(k, 2) i = i + 1 End If If ws.Cells(k, 7) = "No Match" Then wb2.Worksheets("SENIOR UPDATE").Cells(ii, 1) = ws.Cells(k, 1) wb2.Worksheets("SENIOR UPDATE").Cells(ii, 2) = ws.Cells(k, 5) ii = ii + 1 End If If ws.Cells(k, 10) = "No Match" Then wb2.Worksheets("ID UPDATE").Cells(iii, 1) = ws.Cells(k, 1) wb2.Worksheets("ID UPDATE").Cells(iii, 2) = ws.Cells(k, 8) iii = iii + 1 End If If ws.Cells(k, 13) = "No Match" Then wb2.Worksheets("MINOR UPDATE").Cells(iiii, 1) = ws.Cells(k, 1) wb2.Worksheets("MINOR UPDATE").Cells(iiii, 2) = ws.Cells(k, 11) End If If ws.Cells(k, 16) = "No Match" Then wb2.Worksheets("MAJOR UPDATE").Cells(iiii, 1) = ws.Cells(k, 1) wb2.Worksheets("MAJOR UPDATE").Cells(iiii, 2) = ws.Cells(k, 14) iiii = iiii + 1 End If If ws.Cells(k, 19) = "No Match" Then wb2.Worksheets("CAP UPDATE").Cells(iiiii, 1) = ws.Cells(k, 1) wb2.Worksheets("CAP UPDATE").Cells(iiiii, 2) = ws.Cells(k, 17) iiiii = iiiii + 1 End If If ws.Cells(k, 22) = "No Match" Then wb2.Worksheets("PL UPDATE").Cells(iiiiii, 1) = ws.Cells(k, 1) wb2.Worksheets("PL UPDATE").Cells(iiiiii, 2) = ws.Cells(k, 20) iiiiii = iiiiii + 1 End If k = k + 1 Loop wb2.Save Sleep (1000) wb2.Close SaveChanges:=True wb.Activate End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:46:16.697", "Id": "78932", "Score": "1", "body": "One thing you could do to speed up looping would be dump your sheet into an array and loop that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:49:53.860", "Id": "78933", "Score": "0", "body": "I tried that but I keep getting Object not defined when I try to use a range in an array. Is there a specific way to do that?" } ]
[ { "body": "<p>What are the chances that more than one of your if statements would be true for each row? It looks like you may risk overwriting some of your data if that is the case.</p>\n\n<pre><code>Dim ws As Worksheet\nDim wb2 As Workbook\nSet wb = Application.Workbooks(\"Total Database Update_WORKING.xlsm\")\nSet ws = wb.Worksheets(\"Results\")\n</code></pre>\n\n<p>Using variant your array will be able to size to whatever range you give it, but it will be 1 based.</p>\n\n<pre><code>Dim rng as Variant\nSet rng = wb.worksheetS(\"Results\").Range(\"B2:Your last column/row goes here\")\nSet wb2 = Application.Workbooks.Open(\"C:\\Import Update.xlsx\")\n i = 2\n ii = 2\n iii = 2\n iiii = 2\n iiiii = 2\n iiiiii = 2\n iiiiii = 2\n k = 2\n wb2.Activate\n dim row as long\n dim col as long\n For row = 1 to UBound(rng, 1)\n If rng(row, 4) = \"No Match\" Then\n wb2.Worksheets(\"AD UPDATE\").Cells(i, 1) = rng(row, 1)\n wb2.Worksheets(\"AD UPDATE\").Cells(i, 2) = rng(row, 2)\n i = i + 1\n End If \n k = k + 1\n Next Row\n\n wb2.Save\n Sleep (1000)\n wb2.Close SaveChanges:=True\n wb.Activate\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:11:50.740", "Id": "45313", "ParentId": "45249", "Score": "4" } }, { "body": "<blockquote>\n<pre><code>i = 2\nii = 2\niii = 2\niiii = 2\niiiii = 2\niiiiii = 2\niiiiii = 2\n</code></pre>\n</blockquote>\n\n<p>Doesn't that smell like... something that doesn't smell good?</p>\n\n<p>You haven't listed the entire module, so this might be a non-issue, from the code you posted but you're not declaring all the variables you're using. Systematically stick an <code>Option Explicit</code> at the top of every module - the code won't run if a non-declared identifier is used anywhere.</p>\n\n<p>Naming things is hard, but bad naming is harmful, and in some cases can reveal structural issues.</p>\n\n<p>When you feel the need to stick a \"2\" and then a \"3\" as a suffix to a given identifier, a shiny red flag raises and says <em>you shouldn't be doing that, there has to be a better way</em>... this flag is your subconscious, telling you to split your procedure into multiple, smaller ones.</p>\n\n<p>Let's look at a single block:</p>\n\n<pre><code> If ws.Cells(k, 4) = \"No Match\" Then\n wb2.Worksheets(\"AD UPDATE\").Cells(i, 1) = ws.Cells(k, 1)\n wb2.Worksheets(\"AD UPDATE\").Cells(i, 2) = ws.Cells(k, 2)\n i = i + 1\n End If\n</code></pre>\n\n<p>Several \"magic values\" can become parameters, if we were to see this repeated code block as a function of its own; the parameters would be:</p>\n\n<ul>\n<li><code>{ \"AD UPDATE\", 4, 2 }</code></li>\n<li><code>{ \"SENIOR UPDATE\", 7, 5 }</code></li>\n<li><code>{ \"ID UPDATE\", 10, 8 }</code></li>\n<li><code>{ \"MINOR UPDATE\", 13, 11 }</code></li>\n<li><code>{ \"MAJOR UPDATE\", 16, 14 }</code></li>\n<li><code>{ \"CAP UPDATE\", 19, 17 }</code></li>\n<li><code>{ \"PL UPDATE, 22, 20 }</code></li>\n</ul>\n\n<p>Given how these values are used, the corresponding parameter names could be <code>sheetName</code>, <code>matchColumn</code>, and <code>destinationColumn</code>.</p>\n\n<p><code>i</code> &amp; friends are in fact row counters. This means a method extracted from that code block could look like this:</p>\n\n<pre><code>Private Function SayWhatYouDoDoWhatYouSay(ByRef sourceSheet As Worksheet, _\n ByRef destinationBook As Workbook, _\n ByVal sheetName As String, _\n ByVal sourceRow As Long, _\n ByVal matchColumn As Long, _\n ByVal destinationColumn As Long, _\n ByVal destinationRow As Long) As Long\n\n Set destinationSheet = destinationBook.Sheets(sheetName)\n\n If sourceSheet.Cells(sourceRow, matchColumn) = \"No Match\" Then\n\n destinationSheet.Cells(destinationRow, 1) = sourceSheet.Cells(sourceRow, 1)\n destinationSheet.Cells(destinationRow, destinationColumn) = sourceSheet.Cells(sourceRow, 2)\n\n destinationRow = destinationRow + 1\n\n End If\n\n SayWhatYouDoDoWhatYouSay = destinationRow\n\nEnd Function\n</code></pre>\n\n<p>Notice how <code>sourceRow</code> is much more meaningful than <code>k</code>, and <code>destinationRow</code> than <code>i</code> (or <code>iiiiii</code>); the function returns a new value for <em>destinationRow</em>, which the caller can use to assign a new value for the next destination row.</p>\n\n<p>You could maintain an array of <code>Long</code> (<code>Integer</code>?) values for that:</p>\n\n<pre><code> Dim destinationRow(0 To 6) As Long\n</code></pre>\n\n<p>This gives you 7 \"slots\", one for each update type. To be nice you could give each value a meaningful name as well, with an enum type:</p>\n\n<pre><code>Public Enum UpdateType\n AdUpdate = 0,\n SeniorUpdate,\n IdUpdate,\n MinorUpdate,\n MajorUpdate,\n CapUpdate,\n PlUpdate\nEnd Enum\n</code></pre>\n\n<p>And then in the original loop, instead of the multiple <code>If</code> blocks:</p>\n\n<pre><code>destinationRow(UpdateType.AdUpdate) = SayWhatYouDoDoWhatYouSay(ws, wb2, \"AD UPDATE\", k, 4, 2, destinationRow(UpdateType.AdUpdate))\ndestinationRow(UpdateType.SeniorUpdate) = SayWhatYouDoDoWhatYouSay(ws, wb2, \"SENIOR UPDATE\", k, 7, 5, destinationRow(UpdateType.SeniorUpdate))\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T23:51:30.590", "Id": "46121", "ParentId": "45249", "Score": "3" } } ]
{ "AcceptedAnswerId": "46121", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T18:59:29.643", "Id": "45249", "Score": "6", "Tags": [ "optimization", "vba", "excel" ], "Title": "More efficient update macro in Excel" }
45249
<p>After looking through PHP.net documentation for hours, is this the best way to offset an array from start to finish by using <code>array_slice()</code> with <code>array_merge()</code>?</p> <p>For example: <code>$array = array(1,2,3,4)</code> to offset by 2 to get return <code>$array = array(3,4,1,2)</code>.</p> <p>Here's the code I'm using it in:</p> <pre class="lang-php prettyprint-override"><code> $team = 2; $course = array( array('title'=&gt;1, 'hole'=&gt; 'h01', 'shot1'=&gt;'value="-3"', 'shot2'=&gt;'value="-2"', 'shot3'=&gt;'value="-1"', 'shot4'=&gt;'value="0"', 'shot5'=&gt;'disabled="disabled"'), array('title'=&gt;2, 'hole'=&gt; 'h02', 'shot1'=&gt;'value="-4"', 'shot2'=&gt;'value="-3"', 'shot3'=&gt;'value="-2"', 'shot4'=&gt;'value="-1"', 'shot5'=&gt;'value="0"'), array('title'=&gt;3, 'hole'=&gt; 'h03', 'shot1'=&gt;'value="-3"', 'shot2'=&gt;'value="-2"', 'shot3'=&gt;'value="-1"', 'shot4'=&gt;'value="0"', 'shot5'=&gt;'disabled="disabled"'), array('title'=&gt;4, 'hole'=&gt; 'h04', 'shot1'=&gt;'value="-2"', 'shot2'=&gt;'value="-1"', 'shot3'=&gt;'value="0"', 'shot4'=&gt;'disabled="disabled"', 'shot5'=&gt;'disabled="disabled"'), array('title'=&gt;5, 'hole'=&gt; 'h05', 'shot1'=&gt;'value="-4"', 'shot2'=&gt;'value="-3"', 'shot3'=&gt;'value="-2"', 'shot4'=&gt;'value="-1"', 'shot5'=&gt;'value="0"') ); $array1 = array_slice($course, $team); $array2 = array_slice($course, 0, $team); $merged = array_merge($array1, $array2); } </code></pre>
[]
[ { "body": "<p>If you don't mind modifying the original array, you can shorten the (perfectly adequate code you have) with this:</p>\n\n<pre><code>$head = array_splice($course, 0, $team); // remove and return first $team elements\n$merged = array_merge($course, $head); // append them to the end\n</code></pre>\n\n<p>You should be able to omit the temporary <code>$head</code> array by inserting the <code>array_splice</code> call into the <code>array_merge</code> call at the cost of a little code clarity. Try it out to make sure the order of operations is correct.</p>\n\n<pre><code>$merged = array_merge($course, array_splice($course, 0, $team));\n</code></pre>\n\n<p><strong>Edit:</strong> If you're doing this once per team you can use a loop with <a href=\"http://www.php.net/manual/en/function.array-shift.php\" rel=\"nofollow\"><code>array_shift</code></a> to remove the first element and <a href=\"http://www.php.net/manual/en/function.array-push.php\" rel=\"nofollow\"><code>array_push</code></a> to place it at the end:</p>\n\n<pre><code>for ($team = 0; $team &lt; $numTeams; $team++) {\n array_push($course, array_shift($course));\n // use $course...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:01:47.257", "Id": "78830", "Score": "0", "body": "I'm just trying to loop 18 arrays but have different starting arrays based on team value. So for example, `$team = 5` then output `$array = array(array(5),array(6),array(7),array(8),array(9),array(10),array(11),array(12),array(13),array(14),array(15),array(16),array(17),array(18),array(1),array(2),array(3),array(4));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:09:53.600", "Id": "78832", "Score": "0", "body": "Do you have 18 different starting arrays? Or are you taking the same array and doing the above for `$team = 1`, `$team = 2`, `$team = 3`, etc?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:09:39.543", "Id": "78957", "Score": "0", "body": "The latter, one array with 18 different orders based on team ID." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:24:47.720", "Id": "79048", "Score": "0", "body": "@Conor In that case see my edit." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:44:56.960", "Id": "45256", "ParentId": "45253", "Score": "1" } }, { "body": "<p>Here's what worked best for me.</p>\n\n<pre><code>$team = 2;\n$start = $team - 1;\n$course = array(\narray('title'=&gt;1, 'hole'=&gt; 'h01', 'shot1'=&gt;'value=\"-3\"', 'shot2'=&gt;'value=\"-2\"', 'shot3'=&gt;'value=\"-1\"', 'shot4'=&gt;'value=\"0\"', 'shot5'=&gt;'disabled=\"disabled\"'),\narray('title'=&gt;2, 'hole'=&gt; 'h02', 'shot1'=&gt;'value=\"-4\"', 'shot2'=&gt;'value=\"-3\"', 'shot3'=&gt;'value=\"-2\"', 'shot4'=&gt;'value=\"-1\"', 'shot5'=&gt;'value=\"0\"'),\narray('title'=&gt;3, 'hole'=&gt; 'h03', 'shot1'=&gt;'value=\"-3\"', 'shot2'=&gt;'value=\"-2\"', 'shot3'=&gt;'value=\"-1\"', 'shot4'=&gt;'value=\"0\"', 'shot5'=&gt;'disabled=\"disabled\"'),\narray('title'=&gt;4, 'hole'=&gt; 'h04', 'shot1'=&gt;'value=\"-2\"', 'shot2'=&gt;'value=\"-1\"', 'shot3'=&gt;'value=\"0\"', 'shot4'=&gt;'disabled=\"disabled\"', 'shot5'=&gt;'disabled=\"disabled\"'),\narray('title'=&gt;5, 'hole'=&gt; 'h05', 'shot1'=&gt;'value=\"-4\"', 'shot2'=&gt;'value=\"-3\"', 'shot3'=&gt;'value=\"-2\"', 'shot4'=&gt;'value=\"-1\"', 'shot5'=&gt;'value=\"0\"')\n);\n\n$slice1 = array_slice($course, $start);\n$slice2 = array_slice($course, 0, $start);\n$merged = array_merge($slice1, $slice2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-02T21:28:06.157", "Id": "48820", "ParentId": "45253", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:00:21.657", "Id": "45253", "Score": "3", "Tags": [ "php", "array" ], "Title": "Array offset without losing values" }
45253
<p>As a part of my <a href="https://github.com/Kazark/vim-tabv" rel="nofollow">Tabv</a> Vim plugin (which at this stage is nothing more than a pitiful rag-tag assortment of half-baked hacks), I have a function which attempts to guess the directory paths for main source and unit tests. The first working version of this function is (<a href="https://github.com/Kazark/vim-tabv/blob/cb0f0361feb5f1fd06f6733005c2500b71af40a1/plugin/tabv.vim" rel="nofollow">full source</a>):</p> <pre><code>let g:tabv_grunt_file_path='Gruntfile.js' function s:GuessPathsFromGruntfile() execute "sview " . g:tabv_grunt_file_path global/^\_s*['"].*\*\.spec\.js['"]\_s*[,\]]\_s*/y a let l:matches = matchlist(getreg('a'), '[''"]\(.*\)/\*\.spec\.js[''"]') if len(l:matches) &gt; 1 let g:tabv_javascript_unittest_directory = l:matches[1] endif global/^\_s*['"].*\*\.js['"]\_s*[,\]]\_s*/y a let l:matches = matchlist(getreg('a'), '[''"]\(.*\)/\*\.js[''"]') if len(l:matches) &gt; 1 let g:tabv_javascript_source_directory = l:matches[1] endif close endfunction </code></pre> <p>Also relevant, from the same script, and above the function shown:</p> <pre><code>let g:tabv_javascript_source_directory="src" let g:tabv_javascript_source_extension=".js" let g:tabv_javascript_unittest_directory="unittests" let g:tabv_javascript_unittest_extension=".spec.js" </code></pre> <p>Now, the algorithm needs some help, but that's not what I'm worried about at the moment. (I try to build out this plugin on an as-needed basis, rather than going for the gold, so to speak.) What I do not like is:</p> <ul> <li>The code duplication <ul> <li>The fact that the first and second parts of the function are similar.</li> <li>The fact that I am not using the global variables for the file extensions in the regular expression.</li> </ul></li> <li>The fact that I am actually visually opening and closing the Gruntfile.</li> <li>The <code>execute</code> statement</li> </ul> <p>What else do you see wrong here, and how could I do better? What can I do to correct the problems mentioned above?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-10T13:45:00.157", "Id": "183557", "Score": "0", "body": "In retrospect I think the whole approach is necessarily a hack." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T20:32:53.790", "Id": "45254", "Score": "3", "Tags": [ "regex", "vimscript", "grunt.js" ], "Title": "Scraping paths from a Gruntfile" }
45254
<p>I posted this question <a href="https://stackoverflow.com/questions/22620423/creating-dynamic-tables-with-mysqli-securely">here</a>.</p> <p>And an answer stated that I should <strong>not</strong> do:</p> <pre><code>$table_name = 'survey_'.$_POST['surveyid']; </code></pre> <p>because</p> <blockquote> <p>It is easy for a hacker to exploit your site if you include <code>$_GET</code> or <code>$_POST</code> data directly in any SQL string.</p> </blockquote> <p>Here is the code. Do you see any security exploits?</p> <pre><code>if(ctype_digit($_POST['surveyid']) &amp;&amp; $_POST['surveyid']&gt;0){ $table_name = 'survey_'.$_POST['surveyid']; $query = 'CREATE TABLE '.$table_name.' ( `responseid` INT NOT NULL AUTO_INCREMENT, `textarea1` TEXT NULL, `textarea2` TEXT NULL, `textarea3` VARCHAR(255) NULL, `drop_down1` VARCHAR(255) NULL, `drop_down2` VARCHAR(255) NULL, `bool1` BIT NULL, `bool2` BIT NULL, PRIMARY KEY (`responseid`))'; } </code></pre> <p>I don't see a vulnerability.... why is <code>$_POST['surveyid']</code> vulnerable? It is being sanitized by ctype_digit...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:45:33.460", "Id": "78867", "Score": "0", "body": "A small note: now your code is okay, but when you grow it, with more variables between that if and the assignation of $table_name, it might become a real problem forgetting why the code is there and if it's validated. I'd suggest doing the validation in the same line as the assignation." } ]
[ { "body": "<p>Since you validate that <code>$_POST['surveyid']</code> contains at least one digit and contains only digits, your query is safe.</p>\n\n<p><em>However,</em> the <code>CREATE TABLE</code> operation that you are trying to do strikes me as a horrible thing to do. <code>CREATE TABLE</code> is a <a href=\"http://en.wikipedia.org/wiki/Data_definition_language\">Data Definition Language</a> operation, and DDL commands should be executed only in special situations.</p>\n\n<p>Basically, if you routinely create a new table to store responses from each survey, your database schema will be an unmaintainable mess. I strongly recommend that you post your database schema and describe what you are trying to do in a question to <a href=\"http://dba.stackexchange.com\">http://dba.stackexchange.com</a> to develop a sane schema that does not require new tables to be created routinely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:10:03.877", "Id": "78864", "Score": "2", "body": "Especially when the table name is a string of digits. Talk about a non-indicative name!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:16:35.263", "Id": "45263", "ParentId": "45259", "Score": "12" } }, { "body": "<ol>\n<li><p>Usually what you need is a <code>suvery_id</code> attribute and usage of only one table:</p>\n\n<pre><code>CREATE TABLE 'survey_result' (\n `response_id` INT NOT NULL AUTO_INCREMENT,\n `survey_id` INT NOT NULL,\n `textarea1` TEXT NULL,\n `textarea2` TEXT NULL,\n `textarea3` VARCHAR(255) NULL,\n `drop_down1` VARCHAR(255) NULL,\n `drop_down2` VARCHAR(255) NULL,\n `bool1` BIT NULL,\n `bool2` BIT NULL,\nPRIMARY KEY (`responseid`))';\n</code></pre>\n\n<p>I suppose you'll need proper indexes too (based on your queries).</p></li>\n<li><p>Note that I renamed <code>responseid</code> to <code>response_id</code> since this format is easier to read (especially if the name contains three or more words).</p></li>\n<li><p>Having indexed column names, like</p>\n\n<blockquote>\n<pre><code>`textarea1` TEXT NULL,\n`textarea2` TEXT NULL,\n`textarea3` VARCHAR(255) NULL,\n</code></pre>\n</blockquote>\n\n<p>does not suggest flexible database schema. Number of input boxes on surveys are likely to change. Here is another design approach on Stack Overflow: <a href=\"https://stackoverflow.com/q/429468/843804\">Schema design for when users can define fields</a>, but you can find others, search for <em>survey system database schema</em> or something similar. Knowledge about <a href=\"https://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow noreferrer\">database normalization</a> also useful.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T02:27:24.123", "Id": "45278", "ParentId": "45259", "Score": "4" } } ]
{ "AcceptedAnswerId": "45263", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:49:59.237", "Id": "45259", "Score": "4", "Tags": [ "php", "sql", "security" ], "Title": "Is there a PHP security exploit with $_POST in my code?" }
45259
<p>I was just reading about ring buffer the other day and I was fascinated by how simple yet efficient it is.</p> <p>I've implemented a ring (circular) buffer in Ruby and I'm just wondering if there's anything I can improve, and also how to properly measure its performance.</p> <p>Ring buffer:</p> <pre><code>class RingBuffer attr_accessor :ring, :size, :start, :end def initialize(size) @ring = Array.new(size) @size = size @start, @end = 0, 0 end def full? (@end + 1) % @size == @start end def empty? @end == @start end def write(element) return if full? @ring[@end] = element @end = (@end + 1) % @size end def read return if empty? element = @ring[@start] @start = (@start + 1) % @size element end def clear @ring = Array.new(@size) @start, @end = 0, 0 end end </code></pre> <p>Speed test:</p> <pre><code>require_relative 'ring_buffer.rb' buffer_size = 1024*1024 rb = RingBuffer.new(buffer_size) t0 = Time.now (buffer_size-1).times {|idx| rb.write idx } t1 = Time.now (buffer_size-1).times {|idx| rb.read } t2 = Time.now t_all = (t2-t0) * 1000.0 t_avg_w = (t1 - t0) * 1000.0 * 1000.0 / buffer_size t_avg_r = (t2 - t1) * 1000.0 * 1000.0 / buffer_size printf("All: %.02fms\n", t_all) printf("Avg. write: %.02fμs\n", t_avg_w) printf("Avg. read: %.02fμs\n", t_avg_r) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:46:46.083", "Id": "78835", "Score": "0", "body": "There's a link to github repository." } ]
[ { "body": "<p>I'm no ruby guy but just from a general point of view I try to see data structures from an abstract interface point of view. And your interface looks like a fixed size FIFO queue. The fact that you implemented it as a ring buffer is just an implementation detail really. So I'd be inclined to rename it to <code>FixedSizeQueue</code>, <code>write</code> to <code>enqueue</code> and read to <code>dequeue</code> which seems more natural names for the operations as you have implemented them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T06:55:35.410", "Id": "78874", "Score": "0", "body": "But, fixed size queue doesn't actually wrap around does it? I'm a bit confused." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T06:59:40.753", "Id": "78876", "Score": "0", "body": "@MatjazMuhic: Well, what does it matter to the user? As a user you can write `N` items into the structure until it's full. And you can read from it until it's empty. And you will get the items out of it in the same order as they were put in. To me that's a fixed sized queue. What underlying implementation you use is not really relevant for the user (in most cases)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T07:02:52.787", "Id": "78877", "Score": "0", "body": "Well I guess someone would/could choose a ring buffer over a normal queue when the performance is critical? Because there's no overhead of shifting items?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T16:32:59.357", "Id": "512343", "Score": "0", "body": "A fixed size queue generally blocks or raises an error when full instead of simply overwriting old elements like a ring buffer would" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T18:10:13.567", "Id": "512356", "Score": "0", "body": "@nijave The particular implementation in this case doesn't overwrite elements - `return if full?`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T20:04:25.227", "Id": "512367", "Score": "1", "body": "@ChrisWue I guess more accurately the question is calling a FixedQueue a ring buffer so I guess there's so ambiguity in regards to what problem the original question was trying to solve. It seems `ring buffer` more commonly refers to a data structure that overwrites data automatically https://en.wikipedia.org/wiki/Circular_buffer" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:53:58.453", "Id": "45271", "ParentId": "45260", "Score": "1" } }, { "body": "<p>A few things:</p>\n\n<ul>\n<li><p>You declare accessors: Use them yourself. Don't access instance variables directly if you can help it; you'll keep you code more flexible if your object uses its own accessor methods. In other words: Drop most of those <code>@</code> chars (though you'll have to use <code>self.end</code> to distinguish it from the <code>end</code> keyword)</p></li>\n<li><p><em>However</em>, for the most part, you'll only want public <em>reader</em> methods. Otherwise anyone can just mess with the internal <code>ring</code> array from the outside (sure, you can always mess with stuff in Ruby objects, but making it part of your object's declared interface makes it too easy).<br>\nIn fact, I'd probably pare it allll the way down to just <code>read</code>, <code>write</code>, <code>empty?</code> and <code>full?</code> with no public accessors and keep the rest private.</p></li>\n<li><p>You could consider adding a method to do the oft-duplicated <code>(x + 1) % size</code> trick for you.</p></li>\n</ul>\n\n<hr>\n\n<p>As for performance: Using a normal array with <code>push</code> and <code>shift</code> is much faster I'm afraid. And there's no fixed size. So if you want a fast FIFO buffer/queue in plain Ruby, use an array.</p>\n\n<p>This:</p>\n\n<pre><code>buffer_size = 1024**2\nbuffer = RingBuffer.new(buffer_size)\n\nputs \"RingBuffer#write\"\nputs Benchmark.measure {\n buffer_size.times { |i| buffer.write(i) }\n}\n\nputs \"RingBuffer#read\"\nputs Benchmark.measure {\n buffer_size.times { buffer.read }\n}\n\nputs \"----------------------------------\"\n\narray = []\n\nputs \"Plain Array#push\"\nputs Benchmark.measure {\n buffer_size.times { |i| array &lt;&lt; i }\n}\n\nputs \"Plain Array#shift\"\nputs Benchmark.measure {\n buffer_size.times { array.shift }\n}\n</code></pre>\n\n<p>gets me:</p>\n\n<pre>\nRingBuffer#write\n 0.560000 0.000000 0.560000 ( 0.563023)\nRingBuffer#read\n 0.400000 0.000000 0.400000 ( 0.400563)\n----------------------------------\nPlain Array#push\n 0.120000 0.000000 0.120000 ( 0.139201)\nPlain Array#shift\n 0.170000 0.000000 0.170000 ( 0.164827)\n</pre>\n\n<p>So writing/pushing is ~4.7 times faster, and reading/shifting is ~2.4 times faster with a regular ol' Array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T09:59:17.363", "Id": "94126", "Score": "0", "body": "This is just some excellent input. Thank you very much! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T16:23:53.727", "Id": "94231", "Score": "0", "body": "I'm not sure though, how Array is faster. I've tried benchmarking this scenario: I fill both up (array and ring buffer) then I read/shift, and then a write/push. Shouldn't in this case ring buffer be faster since it's wrapping around and not shifting?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-12T21:16:20.400", "Id": "94274", "Score": "0", "body": "@MatjazMuhic `Array` will likely _always_ be faster because it's compiled C code. It exposes a Ruby API, so it feels like it's just Ruby, but its guts are C. Your implementation, when written in Ruby, is basically an extra layer (interpreted, not compiled) on top of that. So nothing you write in Ruby will be as close to metal as built-in, compiled code. You might be able to make a fast circular buffer in C, though, with bindings for Ruby. But that's a very different topic, of course." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T12:28:44.527", "Id": "94368", "Score": "0", "body": "But I'm not doing anything cpu expensive since underneath it's using the array, but without shifting. This implementation for example should be faster than normal array: https://github.com/bbcrd/CBuffer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T13:06:07.597", "Id": "94371", "Score": "1", "body": "@MatjazMuhic Array, being compiled, isn't even on the same playing field as your code, regardless of what you're doing. I'll also add that there's something fishy with that library you linked. I tried running its `rake benchmark` task, and with no modifications, Array looks slower. But they've wrapped Array in a class, and (for whatever reason), it _murders_ performance. I upped the iterations from 10,000 to 100,000, and it took so long I just pulled the plug. But skip the (unneccessary) wrapper, and Array again handily beats all-comers - by an order of magnitude." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T13:16:47.570", "Id": "94374", "Score": "0", "body": "@MatjazMuhic [Here's an updated benchmark.rb file](http://pastie.org/private/b6sfjvegkvmkl8yulhdeg) you can drop into that library you linked to and try for yourself. It includes that library's implementation, your implementation, their array-wrapper, and the plain array push/shift." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T15:20:22.187", "Id": "94408", "Score": "0", "body": "Thank for the update. But I still don't quite get it. Read from fixed array position should be faster than shift right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-13T16:19:05.300", "Id": "94425", "Score": "0", "body": "@MatjazMuhic Depends on how the array is implemented. I don't know how Ruby's Array is implemented, but a shift could be just a pointer changing - nothing more. In that case it's practically instantaneous. Just `a = b` and done. Your code, meanwhile, does some arithmetic on `start` or `end` values that may or may not even be numeric since Ruby's dynamically typed, so that's checked, which requires some more work, and blah blah. And it _still_ has to access the underlying array. Again, you're not even playing by the same rules as Ruby here. You're comparing apples and oranges." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T17:34:53.773", "Id": "54002", "ParentId": "45260", "Score": "5" } } ]
{ "AcceptedAnswerId": "54002", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:39:46.420", "Id": "45260", "Score": "6", "Tags": [ "performance", "ruby", "circular-list" ], "Title": "Ring buffer in Ruby" }
45260
<p>I have a notification system that looks like this:</p> <pre><code>function notificationMethod(message){ // do stuff // once everything else is setup, attach a click handler to the "Okay" button $('#notificationOkay').click(function () { unBlockScreen(); $(this).off("click"); // once they click the "Okay" button, remove the click event }); } </code></pre> <p>The reason that I'm putting the <code>.click()</code> handler in the <code>notificationMethod()</code> as opposed to the <code>$(document).ready()</code> is to be able to keep the notification code separate from the rest of the code that it has nothing to do with (other than it's on the same page). However, looking at my code it feels odd to have the <code>.off("click")</code> inside of the <code>.click()</code>.</p> <p>Is there anything particularly wrong with this approach? </p>
[]
[ { "body": "<p>For a handler that only fires once using jQuery you can use <a href=\"http://api.jquery.com/one/\">.one()</a>.</p>\n\n<p>A click handler would look something like:</p>\n\n<pre><code>function notificationMethod(message){\n // do stuff\n\n // once everything else is setup, attach a click handler to the \"Okay\" button\n $('#notificationOkay').one(\"click\", unBlockScreen);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T00:43:21.657", "Id": "78855", "Score": "1", "body": "Huh, +2 if I could." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:18:33.067", "Id": "45270", "ParentId": "45269", "Score": "10" } } ]
{ "AcceptedAnswerId": "45270", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:15:29.013", "Id": "45269", "Score": "6", "Tags": [ "javascript", "jquery" ], "Title": "Better alternative to $(this).off(\"click\")" }
45269
<p>I was working on a subtype of <code>list</code> in python that acts as a list that should never raise an IndexError (every key you input that's greater than the length of the list gets wrapped around). I was having quite a few problems however implementing it properly for slices, who have a LOT of base cases. I wrote the following code to handle slices the way I want to (with example slices commented out);</p> <pre><code>class Cycle: def __getitem__(self, key): _self = self._container n = len(self) if isinstance(key, slice): s = key.start e = key.stop stp = key.step r = False if stp is None: stp = 1 elif stp == 0: raise ValueError() elif stp &lt; 0: r = True stp = abs(stp) if s and not e: sliced = [] _len = n - s #[3:] if s &lt; 0: #[-1:] _len = abs(s) elif s &gt;= n: #[7:] _len = n - s % n for i in range(0, _len, stp): index = (i + s) % n sliced.append(_self[index]) elif e and not s: sliced = [] _len = e #[:4] if e &lt;= 0: #[:-1] _len = n - abs(e) % n for i in range(0, _len, stp): index = i % n sliced.append(_self[index]) elif s and e: sliced = [] if s &lt;= e: if s &lt; 0 and e &lt; 0: #[-3:-1] #[-7:-1] _len = abs(s) - abs(e) elif s &lt; 0 and 0 &lt;= e: #[-1:3] #[-7:8] if n + s % n &gt; e: _len = e - s else: _len = e - (n + s) elif 0 &lt;= s and 0 &lt;= e: #[1:3] #[7:19] _len = e - s elif s &gt; e: if s &lt; 0 and e &lt; 0: #[-1:-3] raise ValueError() elif s &gt;= 0 and e &lt; 0: if n + e &lt; s: #[4:-3] raise ValueError() _len = (n + e) - s #[1:-1] elif 0 &lt;= s and 0 &lt;= e: if s &gt;= n: if s % n &lt;= e: #[7:1] _len = e - s % n else: #[7:3] _len = n - s % n + e else: #[4:2] _len = (n - s % n) + e for i in range(0, _len, stp): index = (i + s) % n sliced.append(_self[index]) elif not (s or e): sliced = _self[::stp] if r: sliced = sliced[::-1] return sliced else: key %= n return _self[key] </code></pre> <p>I can't think of any other more compact way to test for all the different cases that can occur. Can someone help me out please?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T02:31:30.120", "Id": "78860", "Score": "0", "body": "Your code is very hard to read. Can you expand your question with a pseudocode algorithm? I don't think everyone here will read into the whole thing." } ]
[ { "body": "<p>I'm not doing a lot of Python but one thing leaping out at me is the usage of all these single letter variables which make the code really hard to read. While longer names will make the code a bit longer I think they will improve readability quite a lot:</p>\n\n<ul>\n<li><code>s</code> should be <code>start</code> or <code>rangeStart</code></li>\n<li><code>e</code> should be <code>end</code> or <code>rangeEnd</code></li>\n<li><code>stp</code> should be <code>step</code></li>\n<li><code>r</code>: from just briefly browsing over the code I had no idea what that flag is supposed to represent. Given that it's set to <code>True</code> when the step is negative I assume it could mean <code>reverse</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T00:08:35.330", "Id": "45274", "ParentId": "45273", "Score": "7" } }, { "body": "<p>Please break this code into sub-functions. This one function is 85 lines of hard to follow zig-zagging indentation. I have no idea what the code is doing or why each if clause is significant. Good function (and variable) names will make the code easier to follow without having to know much about the code.</p>\n\n<hr>\n\n<p>Your code is sprinkled with various comments like the following.</p>\n\n<pre><code>_len = n - s #[3:]\n</code></pre>\n\n<p>This means nothing to me. How does <code>n - s</code> equate to a sub-array starting at the 4th element? Comments should be there to help convey information that the code does not. These comments just confuse me more. If your comment is saying <strong>what</strong> you are doing, that is an indication that the might be better if it was broken down into smaller pieces. In general, comments should say <strong>why</strong> you are doing something. Let function names/descriptions tell you what is happening in the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T01:00:50.210", "Id": "45275", "ParentId": "45273", "Score": "5" } }, { "body": "<p>From what I can tell, a major cause of complexity of your code is trying to pin down the beginning and/or end of an infinitely long sequence. In my mind, a cyclic list cycles infinitely to both positive and negative directions. It has no beginning or end. Leaving out either <code>start</code> or <code>stop</code> of the slice should be flagged as an error.</p>\n\n<p>Given that, you could just loop <code>for i in range(start,stop,step)</code> and take items at <code>i % len_of_cycle</code>.</p>\n\n<hr>\n\n<p>Trying to figure out what your code does, I added these methods to make your code runnable. (It would be very good to post runnable code to begin with, by the way.)</p>\n\n<pre><code> def __init__(self, iterable):\n self._container = list(iterable)\n\n def __len__(self):\n return len(self._container)\n</code></pre>\n\n<p>I don't quite find the behavior consistent. </p>\n\n<p>Example 1: Here are three ways of selecting the last two items of the cycle. Wouldn't it be logical for the fourth case to do the same?</p>\n\n<pre><code>&gt;&gt;&gt; c = Cycle(range(5))\n&gt;&gt;&gt; c[3:]\n[3, 4]\n&gt;&gt;&gt; c[-2:]\n[3, 4]\n&gt;&gt;&gt; c[8:]\n[3, 4]\n&gt;&gt;&gt; c[-7:]\n[3, 4, 0, 1, 2, 3, 4]\n</code></pre>\n\n<p>Example 2: Why does this slice not start from 2?</p>\n\n<pre><code>&gt;&gt;&gt; c[2::-1]\n[4, 3, 2]\n</code></pre>\n\n<p>Example 3: The first two cases treat -1 and 4 the same, like a regular list would. I would expect -4 and 1 behave identically in the latter two cases, even if the behavior differs from list's.</p>\n\n<pre><code>&gt;&gt;&gt; c[1:4]\n[1, 2, 3]\n&gt;&gt;&gt; c[1:-1]\n[1, 2, 3]\n&gt;&gt;&gt; c[4:1]\n[4, 0]\n&gt;&gt;&gt; c[4:-4]\nTraceback (most recent call last):\n ...\nValueError\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:10:37.167", "Id": "45329", "ParentId": "45273", "Score": "2" } }, { "body": "<p>The easiest way to go about this problem is to convert all the input parameters into a standard form.</p>\n\n<p>Lets say the start and end indices will be contained in the following sets:</p>\n\n<pre><code>lowbound -&gt; [0,len) #meaning that the value starts from 0 up to but not including len\nhighbound -&gt; (0,len] #meaning that the value starts from but not including 0 up to len\n</code></pre>\n\n<p>and our step variable is in the range</p>\n\n<pre><code>step -&gt; (-inf,0) U (0, inf) #meaning step can be any value but 0\n</code></pre>\n\n<p>If start or end aren't given, lets set them to there max/min values... \nNow lets make some formatting functions!!</p>\n\n<pre><code>def FormatLowBound(start, length):\n if start is None:\n return 0\n # if start is less that 0, we need to convert it to a positve number\n # in order to be contained in our defined set for start -&gt; [0,len)\n while start &lt; 0:\n # for example -1 -&gt; len -1 \n # if a number is larger than len it must be subtracted again\n # a while loop will achieve this goal\n start = length + start\n # now imagine start could have be larger than len, so lets mod it:\n start %= length\n # Were done here, return that junk!\n return start\n</code></pre>\n\n<p>The FormatHighBound function will be very similar to the last, but it has a slightly different range</p>\n\n<pre><code>def FormatHighBound(end, length):\n if end is None:\n return length\n while end &lt; 0:\n end = length + end\n end %= length\n # if end is now the value of zero lets set it to length instaed!\n if end == 0:\n end = length\n return end\n</code></pre>\n\n<p>Now all we have to do is raise a value error if step is 0, because its the only incorrect value for step- \nAnd we also must define our default value as 1</p>\n\n<pre><code>def FormatStep(step):\n if step is None:\n return 1\n if step == 0:\n raise ValueError()\n return step\n</code></pre>\n\n<p>After this we're left with one final condition that could give us trouble,. If step is negative and and start &lt; end, or step is positive and and start > end; we get an empty array returned...</p>\n\n<p>This however it does not cause an error, so lets leave it as an expected result</p>\n\n<p>Because all the values are now contained in the appropriate range, we can return a slice of Cycle items in that simplified range!</p>\n\n<pre><code>class Cycle(object):\n def __init__(self, val):\n self._container = val\n def __repr__(self):\n return str(self._container)\n def __getitem__(self, key):\n _self = self._container\n length = len(_self)\n if isinstance(key, slice):\n step = FormatStep(key.step)\n # if step is negative there are special none cases to consider\n # this is to include all values for reverse slices with empty params\n if step &lt; 0:\n if key.stop is None:\n end = -1\n else:\n end = FormatLowBound(key.stop, length)\n if key.start is None:\n start = length-1\n else:\n start = FormatLowBound(key.start, length)\n\n else:\n start = FormatLowBound(key.start, length)\n end = FormatHighBound(key.stop, length)\n return [_self[index] for index in range(start,end,step)]\n else:\n return _self[key % length]\n</code></pre>\n\n<p>As you can see, it works nicely!!</p>\n\n<pre><code>&gt;&gt;&gt; c = Cycle(range(10))\n&gt;&gt;&gt; c[9::-1]\n[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n&gt;&gt;&gt; c[9:0:-1]\n[9, 8, 7, 6, 5, 4, 3, 2, 1]\n&gt;&gt;&gt; c[0]\n0\n&gt;&gt;&gt; c[10]\n0\n&gt;&gt;&gt; c[9]\n9\n&gt;&gt;&gt; c[-12341234]\n6\n&gt;&gt;&gt; c[1:-1:2]\n[1, 3, 5, 7]\n&gt;&gt;&gt; c[1:-11:2]\n[1, 3, 5, 7]\n&gt;&gt;&gt; \n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:33:38.553", "Id": "45410", "ParentId": "45273", "Score": "1" } } ]
{ "AcceptedAnswerId": "45274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:56:52.120", "Id": "45273", "Score": "11", "Tags": [ "python" ], "Title": "Custom slice() on list subtype" }
45273
<p>I'm running code which works fast locally, but when it's on Heroku it's slow. Heroku says this is because there is less memory and CPU power on my hosting than locally. I'm trying to rewrite my code so it's more efficient, but I'm not sure how.</p> <p>This is what they said:</p> <blockquote> <p>...[my] method (especially, a.each part) is taking time. I think a itself is pretty long, and you're transpose it with subs.keys, and do some process for each of them. Even though <code>s.gsub!(*pair)</code> is not "long running" code, if you run this million times (actually runs 1,161,216 times for the word "startup"), it'll be "slow" request.</p> </blockquote> <p>Here is my code:</p> <pre><code>def substitute(word) subs = Hash.new Section.all.to_a.each do |s| alternates_array = Array.new s.substitutions.each do |alt| alternates_array &lt;&lt; alt.alternate end alternates_array &lt;&lt; s.part new_hash = Hash.new subs[s.part] = alternates_array end a = subs.values a = a.first.product(*a.drop(1)) alternates = Array.new a.each do |a| new_string = [subs.keys, a].transpose.each_with_object(word.dup){|pair, s| s.gsub!(*pair)} end return alternates end </code></pre> <p>Section Model</p> <pre><code>class Section include Mongoid::Document field :part, type: String embeds_many :substitutions accepts_nested_attributes_for :substitutions end </code></pre> <p>Substitution Model</p> <pre><code>class Substitution include Mongoid::Document field :alternate, type: String embedded_in :section end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:18:29.097", "Id": "78866", "Score": "0", "body": "Section model is added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T06:54:08.313", "Id": "78873", "Score": "3", "body": "Could you add some explanation what your code is supposed to do? This will make it easier for people to review it." } ]
[ { "body": "<p><strong>Read with batches</strong><br>\nLooping over <code>Section.all.to_a</code> is very memory greedy (it reads <em>everything</em> to memory before starting to process it). You will be far better off using <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Batches.html\" rel=\"nofollow\">batches</a>:</p>\n\n<pre><code>Section.find_each do |section|\n # ...\nend\n</code></pre>\n\n<p><strong>Naming</strong><br>\nUsing member names like <code>s</code>, <code>a</code>, etc. is not very readable, and makes understanding what your code does very difficult. For that reason, it is very hard for us reviewers to give you an intelligent advice on how your code can be improved - we just don't understand what it does...</p>\n\n<p><strong>Shadowing</strong><br>\n<code>a.each do |a|</code> - to add insult to injury, you <em>shadow</em> the <code>a</code> member when you loop over it. This makes your code <em>totally</em> unreadable. I still don't understand what that loop is all about.</p>\n\n<p><strong>Loop bloat</strong><br>\nThe line <code>a = a.first.product(*a.drop(1))</code> is very suspicious, since it bloats the amount of data your are looping on by several scales. Are you sure that is what you want to do?</p>\n\n<p><strong>Where does your data go?</strong><br>\nThe <code>new_string</code>, which holds the result for each iteration is not seemed to be saved anywhere...</p>\n\n<p><strong>Filter your data</strong><br>\nAt the bottom line, you are substituting words in your input. Not all sections exist in all inputs, but you search for them over and over again. You might save a lot of calculations if you filter irrelevant sections in your code, before looping on them:</p>\n\n<pre><code>Section.find_each do |section|\n next unless word[section.part]\n alternate_array #...\nend\n</code></pre>\n\n<p><strong>Doing stuff over and over again</strong><br>\nI'm pretty sure, though I might be wrong, that at the end <code>s.gsub!(*pair)</code> ends up running the same \"pairs\" more than once on the same string (or its duplicates). It will be better strategy to cache results, or maybe pre-process your data (build a template, and only set the variables, or something).</p>\n\n<hr>\n\n<p><em><strong>Edit</em></strong><br>\nYou could use a variant of <a href=\"http://www.ruby-doc.org/core-2.1.0/String.html#method-i-gsub\" rel=\"nofollow\"><code>gsub!</code></a> which receives a hash as the replacement:</p>\n\n<blockquote>\n <p>If the second argument is a <code>Hash</code>, and the matched text is one of its\n keys, the corresponding value is the replacement string.</p>\n</blockquote>\n\n<p>So you could write:</p>\n\n<pre><code>replace_regexp = Regexp.union(subs.keys)\n\nreplaced_words = a.map do |alts|\n word.gsub(replace_regexp, Hash[[subs.keys, alts].transpose])\nend\n</code></pre>\n\n<p>This does a <em>single</em> <code>gsub</code> per combination (instead of once <em>per key</em>), and further reduces the run complexity of your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:33:19.393", "Id": "45306", "ParentId": "45276", "Score": "6" } } ]
{ "AcceptedAnswerId": "45306", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T01:23:57.873", "Id": "45276", "Score": "5", "Tags": [ "performance", "ruby" ], "Title": "Speed up long running Ruby code" }
45276
<p>See the proposed changes in <a href="https://github.com/Freeseer/freeseer/pull/533/files#diff-1c2ac91deea642c6d24c522c834b474fR61" rel="nofollow">this Pull Request</a> under <code>def add_talk</code>.</p> <pre><code>date = self.talkDetailsWidget.dateEdit.date() time = self.talkDetailsWidget.timeEdit.time() presentation = Presentation( unicode(self.talkDetailsWidget.titleLineEdit.text()).strip(), unicode(self.talkDetailsWidget.presenterLineEdit.text()).strip(), unicode(self.talkDetailsWidget.descriptionTextEdit.toPlainText()).strip(), unicode(self.talkDetailsWidget.categoryLineEdit.text()).strip(), unicode(self.talkDetailsWidget.eventLineEdit.text()).strip(), unicode(self.talkDetailsWidget.roomLineEdit.text()).strip(), unicode(date.toString(Qt.ISODate)), unicode(time.toString(Qt.ISODate))) </code></pre> <p>There's a lot of boilerplate code (e.g. <code>unicode()</code>, <code>seld.talkDetailsWidget</code>, <code>text()</code>, <code>strip()</code>, etc.) How could you reduce that and still have the code be easy to understand?</p> <p>My thinking is if something along the lines of this were possible:</p> <pre><code>map(str.strip, map(unicode, map(QLineEdit.text, map(self.talkDetailsWidget, fields)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:27:18.247", "Id": "78903", "Score": "2", "body": "Had you used Python 3.4, you could have used `functools.singledispatch` to create an overload of `Presentation.__init__` taking a `TalkDetailsWidget` parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:18:58.457", "Id": "78925", "Score": "0", "body": "@Morwenn that's good to know! We want to move over to Python3, but like most other projects, we need our dependencies to be compatible first. We should look into it again, maybe we're much closer now than the last time we checked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:25:30.463", "Id": "78927", "Score": "0", "body": "Moving to Python 3 can be pretty tricky, but it's worth. I would say that the biggest problem is the current lack of some libraries (I'm looking at you, PIL)." } ]
[ { "body": "<p>Your <a href=\"https://github.com/Freeseer/freeseer/blob/54cbe80d577b2fe1632679426f99435da5fafa28/src/freeseer/frontend/talkeditor/TalkDetailsWidget.py\"><code>TalkDetailsWidget</code></a> is underdeveloped, I think. You could say that you have a view but no model, and that is causing you problems.</p>\n\n<p>You want to be able to write</p>\n\n<pre><code>talk = self.talkDetailsWidget\npresentation = Presentation(title=talk.title,\n speaker=talk.presenter, # ← Why the inconsistent vocabulary?\n description=talk.description,\n category=talk.category,\n event=talk.event,\n room=talk.room,\n date=unicode(talk.date.toString(Qt.ISODate)),\n time=unicode(talk.time.toString(Qt.ISOTime)))\n</code></pre>\n\n<p>Therefore, you'll need to implement new properties in <code>TalkDetailsWidget</code>. To avoid copy-and-paste programming in <code>TalkDetailsWidget</code>, I suggest writing those getters using metaprogramming.</p>\n\n<pre><code>class TalkDetailsWidget(QWidget):\n …\n\n def _field_reader(field, method='text'):\n return property(fget=lambda self: unicode(getattr(getattr(self, field), method)()).strip(),\n doc=\"Returns a Unicode string from the %s field with spaces stripped from each end\" % (field))\n\n title = _field_reader('titleLineEdit')\n presenter = _field_reader('presenterLineEdit')\n description = _field_reader('descriptionTextEdit', method='toPlainText')\n category = _field_reader('categoryLineEdit')\n event = _field_reader('eventLineEdit')\n room = _field_reader('roomLineEdit')\n\n @property\n def date(self):\n self.dateEdit.date()\n\n @property\n def time(self):\n self.timeEdit.time()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:19:25.083", "Id": "79019", "Score": "0", "body": "Unrelated note - your code violates PEP8 with aligning lines and 80 characters per columns limit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:23:44.100", "Id": "79021", "Score": "0", "body": "@RuslanOsipov I am aware that it violates PEP8. The `fget` parameter could use a proper function instead of a lambda. Not sure what to do about the docstring. As for the unusual alignment by the equals sign for the arguments of `Presentation`, I think the violation aids readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:57:05.700", "Id": "79039", "Score": "0", "body": "Makes sense. The docstring can be wrapped in `(\"line 1\"\\n\"line 2\")`, but it's not important in the context." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T05:41:10.693", "Id": "45282", "ParentId": "45280", "Score": "8" } } ]
{ "AcceptedAnswerId": "45282", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:52:36.693", "Id": "45280", "Score": "7", "Tags": [ "python", "python-2.x", "pyqt" ], "Title": "Creating an object in Python with lots of long arguments" }
45280
<p>This is a wonky PHP function I came up with to merge some select values from child arrays into the original. It could really use some help simplifying / making it more elegant.</p> <p>Is there a built-in method I'm overlooking? <code>array_push</code> didn't work for me because the data needed to be flat.</p> <h2>The problem</h2> <p>What I've got:</p> <pre><code>array( array( 'nice_value' =&gt; 'yup', 'nice_value2' =&gt; 'yup again', 'ono' =&gt; array( 'nice_value3' =&gt; 'yup yup yup', 'bad value' =&gt; 'nope' ) ), // array with the same format [...] ); </code></pre> <p>What I need:</p> <pre><code>array( array( 'nice_value' =&gt; 'yup', 'nice_value2' =&gt; 'yup again', 'nice_value3' =&gt; 'yup yup yup' ), // array with the same format [...] ); </code></pre> <h2>The wonky solution</h2> <pre><code>// calling in multidimensional array from an api $lists = $all_lists['data']; // keys to merge into the parent array, 'key_to_be' =&gt; 'key_that_is' $keys_to_merge = array('members' =&gt; 'member_count'); // init the function $newList = merge_selected_values($lists, $keys_to_merge); // start writing our function function merge_selected_values($list, $keys_to_merge) { // initialize our return array $newList = array(); // start a counter $ii = 0; // begin loop foreach($list as $key =&gt; $value) { // get first series of array, this is what we want to merge into if (is_array($value)) { // loop through these values foreach ($value as $kk =&gt; $vv) { // find all arrays that are children of our parent array if (is_array($vv)) { // loop through these child arrays foreach ($vv as $stats_key =&gt; $stats_value) { // start looping through the keys that we want to merge foreach ($keys_to_merge as $keys =&gt; $vals) { // if the key matches if ($stats_key === $vals) { // create a variable to hold it ${$vals} = $stats_value; } } } } } // start looping through keys to merge again foreach ($keys_to_merge as $keys =&gt; $vals) { // find the keys we merged if (${$vals}) { // create an array that is the merger, merge to existing array if it .. exists if($newList[$ii]) { $newList[$ii] = array_merge($newList[$ii], array($keys =&gt; ${$vals})); } else { $newList[$ii] = array_merge($value, array($keys =&gt; ${$vals})); } } } } $ii++; } return $newList; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-19T09:54:44.380", "Id": "458272", "Score": "0", "body": "you can check this solution too: [https://stackoverflow.com/questions/13877656/php-hierarchical-array-parents-and-childs](https://stackoverflow.com/questions/13877656/php-hierarchical-array-parents-and-childs)" } ]
[ { "body": "<p>What's the criteria for deciding which keys to keep?</p>\n\n<p>Check out the <a href=\"http://www.php.net/manual/en/function.array-walk-recursive.php\" rel=\"nofollow\">array_walk_recursive()</a> function. For example, the following matches any element with a key that starts with \"nice_value\".</p>\n\n<pre><code>$array = /*your array example*/;\n$filtered = array();\narray_walk_recursive($array, function($val, $key) use(&amp;$filtered) {\n if (strpos($key, 'nice_value') === 0) {\n $filtered[$key] = $val;\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T06:11:41.370", "Id": "45372", "ParentId": "45281", "Score": "4" } }, { "body": "<h3>What's wonky</h3>\n\n<ul>\n<li>The <code>function</code> line is at the same indentation level as its body.</li>\n<li>The placement and verbosity of the comments.</li>\n<li>Use of variably-named variables. Gather the key-value pairs to be merged using an associative array instead.</li>\n</ul>\n\n<h3>Suggested solution</h3>\n\n<ul>\n<li>Use <code>array_walk_recursive()</code> as suggested by @jbarreiros to find the key-value pairs you want.</li>\n<li>Use <code>array_replace()</code> (or maybe <code>array_merge()</code>) to add those key-value pairs back to the original.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:29:37.253", "Id": "45472", "ParentId": "45281", "Score": "1" } } ]
{ "AcceptedAnswerId": "45372", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T04:45:30.640", "Id": "45281", "Score": "7", "Tags": [ "php", "array" ], "Title": "Merge some child values back into the parent multidimensional array" }
45281
<p>This is one way to make a boolean in C. </p> <pre><code>typedef enum { false = 1 == 0, true = 0 == 0 } bool; </code></pre> <p>Recently I made some like</p> <pre><code>typedef enum { true = ~(int)0, //true is the opposite of false false = (int)0 //the smallest enum is equal to sizeof int } bool; int main(void) { return false; } </code></pre> <p>Can this be improved upon?</p>
[]
[ { "body": "<p>Well, according to the ANSI book:</p>\n\n<blockquote>\n <p>The identifiers in an enumerator list are declared as constants of type <code>int</code></p>\n</blockquote>\n\n<p>So the cast is redundant:</p>\n\n<pre><code>typedef enum {\n true = ~0,\n false = 0\n} bool;\n</code></pre>\n\n<p>Also, in C, a \"true\" value is anything other than zero, so <code>~0</code> is no more \"true\" than <code>1</code> - might as well keep it simple:</p>\n\n<pre><code>typedef enum {\n false = 0,\n true = 1\n} bool;\n</code></pre>\n\n<p>In fact, <code>0</code> and <code>1</code> are the standard choice for representing boolean values where there's no native boolean type (for example, the <code>bit</code> type in SQL uses <code>0</code>/<code>1</code>).</p>\n\n<p>Now you might ask yourself, \"so - did we just redefine zero and one?\" - well, we certainly did. As an experiment in using <code>typedef</code>/<code>enum</code> it's okay. But don't use it in actual C code, because it'll make <code>if</code> clauses unnecessarily complex.</p>\n\n<p>For example, let's say we want to compare <code>str</code> and <code>str2</code> and to do something if they're not equal. We'll use <code>strcmp</code> which compares two strings and returns 0 if they're equal.</p>\n\n<pre><code>// without bool\nif(strcmp(str1,str2))\n{\n ...\n}\n\n// with bool\nif(strcmp(str1,str2) == 0 ? false : true)\n{\n ...\n}\n</code></pre>\n\n<p>In conclusion, as an experiment your code is OK and can be slightly improved. Generally, the lack of <code>bool</code> type in C seems scary at first, but it's actually quite convenient when you get used to it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T08:44:21.843", "Id": "78882", "Score": "0", "body": "It would be less surprising to put `false` before `true` so that the members are listed in ascending order as usual in an `enum`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:47:39.110", "Id": "79013", "Score": "0", "body": "My C++ instructor comes from Pascal, and would always require explicit casts... I guess it stuck." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T07:07:35.797", "Id": "45286", "ParentId": "45284", "Score": "4" } } ]
{ "AcceptedAnswerId": "45286", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T06:07:54.887", "Id": "45284", "Score": "5", "Tags": [ "c", "enum" ], "Title": "Enumerating a boolean in C" }
45284
<pre><code>private string ExtractExceptionMesssage(string exceptionMessage) { const string startWord = "Message&amp;gt"; int startWordLength = startWord.Length; const string endWord = "/Message&amp;gt"; var length = exceptionMessage.Length; int index = 0; var sb = new StringBuilder(); while (index &lt; length) { var startIndex = exceptionMessage.IndexOf(startWord, index, StringComparison.Ordinal); if (startIndex &lt; 0) break; var endIndex = exceptionMessage.IndexOf(endWord, startIndex, StringComparison.Ordinal); if (endIndex &lt; 0) { break; } var len = endIndex - 4 - (startIndex + startWord.Length); // -4 is ".&amp;lt" sb.AppendLine(exceptionMessage.Substring(startIndex + startWordLength, len)); index = endIndex + endWord.Length + 1; } if (sb.Length == 0) sb.Append("Unknown error"); return sb.ToString(); } </code></pre> <p>I'll appreciate any idea of how to make it better</p>
[]
[ { "body": "<p><strong>Consistent style</strong><br>\nYou kind of mixing your styles with curly braces - your indentation is inconsistent, and for two duplicate <code>if</code>s with single statement you once omit the braces, and on the other not. Choose a style, and stick to it - it will make your code more readable</p>\n\n<p><strong>Magic numbers</strong><br>\nYou made a curious choice to omit the <code>\"&amp;lt;\"</code> from you start and end indicators, which made you add the mysterious <code>- 4</code> to your <code>len</code> calculation. This is a major maintenance issue, since tomorrow you will want to extract with unescaped text, where the <code>\"&amp;lt;\"</code> will be reduced to <code>\"&lt;\"</code>, and your code will stop working...</p>\n\n<p><strong>Use the powers of the tools at hand</strong><br>\nYour solution could be much simpler if you used <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx\" rel=\"nofollow\"><code>Regex</code></a> to solve it:</p>\n\n<pre><code>private string ExtractExceptionMesssage(string exceptionMessage) {\n string pattern = @\"&amp;lt;Message&amp;gt;(.+?)lt;/Message&amp;gt;\";\n Regex rgx = new Regex(pattern);\n var sb = new StringBuilder();\n MatchCollection matches = rgx.Matches(input);\n if (matches.Count &gt; 0) {\n foreach (Match match in matches) {\n sb.AppendLine(match.Value);\n }\n } else {\n return \"Unknown error\";\n }\n return sb.ToString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:11:21.180", "Id": "45300", "ParentId": "45292", "Score": "4" } }, { "body": "<p>This looks like XML in XML (that's why there are <code>&amp;gt;</code>s instead of <code>&gt;</code>s). When working with XML, you should use a XML parsing library, like LINQ to XML, instead of trying parse it manually.</p>\n\n<p>Assuming you can use LINQ to XML to get the XML unencoded (with <code>&gt;</code>s) and that it's actually valid XML (with a single root element), then you can use something like:</p>\n\n<pre><code>private string ExtractExceptionMesssage(string exceptionMessage)\n{\n var doc = XElement.Parse(exceptionMessage);\n return string.Join(\"\\n\", doc.Descendants(\"Message\").Select(m =&gt; m.Value));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:22:40.767", "Id": "45315", "ParentId": "45292", "Score": "2" } } ]
{ "AcceptedAnswerId": "45300", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T09:49:03.187", "Id": "45292", "Score": "5", "Tags": [ "c#", "strings", "complexity" ], "Title": "Helper method to extract a specific string from long message" }
45292
<p>Problem Statement:</p> <blockquote> <p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</p> <p>Find the largest palindrome made from the product of two 3-digit numbers.</p> </blockquote> <p>This code is in C++ 11, please review my code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;math.h&gt; using namespace std; int palindrom(int num); int main() { auto n1 = 999u; auto n2 = 999u; unsigned int n = 0u; unsigned int largest = 0; for (; n1&gt;=100; n2--) { if (n2 &lt; 100) { n1--; n2 = 999; continue; } if (palindrom(n1*n2) == n1*n2) { cout &lt;&lt; "n1 &lt;&lt; " &lt;&lt; n1 &lt;&lt; " n2 " &lt;&lt; n2 &lt;&lt; endl; cout &lt;&lt; n1*n2; if (largest &lt; n1*n2) largest = n1*n2; } } cout &lt;&lt; "Largest" &lt;&lt; largest &lt;&lt; endl; return 0; } int palindrom(int num) { int new_num = 0; int digit = 0; while (num != 0) { digit = num % 10; new_num = new_num*10 + digit; num /= 10; } return new_num; } </code></pre> <p>Output (project Euler solution kept secret)</p> <blockquote class="spoiler"> <p> 906609</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:53:31.037", "Id": "79078", "Score": "0", "body": "Note this meta post concerning this question: [Keeping 'Competitive Results' private](http://meta.codereview.stackexchange.com/questions/1669/keeping-competitive-results-private)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T02:23:47.273", "Id": "79100", "Score": "0", "body": "@rolfl Thanks for posting. Next time I will not add output in question. Secondly, I think Project Euler sort of sites are for self improvement, and you can harm yourself if you are cheating." } ]
[ { "body": "<p><code>n</code> is an unused variable. Your compiler should have warned you about it (and you should compile with warnings enabled).</p>\n\n<p>Declaring variables with <code>auto</code> and an unsigned integer literal is unconventional. Just <code>int n1 = 999</code> would have been more readable.</p>\n\n<p>Your for-loop is weird. The three fields of a for-loop header should clearly state how the loop behaves. Testing for <code>n1 &gt;= 100</code> while decrementing <code>n2</code>, then having a separate test for <code>n2 &lt; 100</code> that decrements <code>n1</code> and resets <code>n2</code> is a really convoluted way of writing a nested for-loop!</p>\n\n<p>Since <code>n1</code> and <code>n2</code> are symmetric, you can cut the work in half by making the inner loop condition <code>n2 &gt;= n1</code> instead of <code>n2 &gt;= 100</code>.</p>\n\n<p><code>palindrom()</code> would be better named <code>reverse()</code> or <code>reverse_digits()</code>.</p>\n\n<p>Testing whether the product exceeds the largest palindrome so far is cheaper than testing whether the product is a palindrome, so do the cheaper test first.</p>\n\n<pre><code>#include &lt;iostream&gt;\n// You don't need &lt;math.h&gt;\n\nint reverse(int num)\n{\n int new_num = 0;\n while (num != 0)\n {\n int digit = num % 10; // Move the declaration inside the loop\n new_num = new_num * 10 + digit;\n num /= 10;\n }\n return new_num;\n}\n\nint main()\n{\n int largest = 0;\n for (int n1 = 999; n1 &gt;= 100; n1--)\n {\n for (int n2 = 999; n2 &gt;= n1; n2--)\n {\n int product = n1 * n2;\n if (product &gt; largest &amp;&amp; reverse(product) == product)\n {\n largest = product;\n }\n }\n }\n std::cout &lt;&lt; \"Largest \" &lt;&lt; largest &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:21:31.967", "Id": "78899", "Score": "0", "body": "+1. One query why. `int digit = num % 10;` in loop, why shoul I not declare variable only once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:22:59.707", "Id": "78901", "Score": "2", "body": "Declaring the variable inside a loop does _not_ make it any less efficient. It just makes it more tightly scoped so that it is only accessible from inside the loop. That makes it easier to maintain the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:16:50.620", "Id": "45294", "ParentId": "45293", "Score": "3" } }, { "body": "<ol>\n<li><p>The way you've constructed your loop is awkward and hard to reason about.</p>\n\n<p>Why not just use a pair of nested loops?</p>\n\n<pre><code>for(int i=100; i&lt;1000; ++i) {\n for(int j=i; j&lt;1000; ++j) {\n ...do stuff with (i,j)...\n }\n}\n</code></pre></li>\n<li><p>Don't use unsigned values unless you really need them.</p></li>\n<li><p>I'd make <code>palindrome()</code> into a boolean predicate personally:</p>\n\n<pre><code>bool is_palindrome(int n) { ... }\n</code></pre></li>\n<li><p>Don't recalculate the value of <code>n1*n2</code> over and over again, assign it to a named variable and refer to that. It makes your code more readable &amp; reduces the opportunity for errors to creep in.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:26:26.103", "Id": "78902", "Score": "0", "body": "Note that (d) is really about reducing the opportunity for errors to creep into your code. It's better to assign n1*n2 to a suitably named variable & use that everywhere that you need it. That way you know you've used the same value everywhere and make the code more readable at the same time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:28:05.537", "Id": "78904", "Score": "0", "body": "Can you please elaborate, (c). Are you taking about overloading `() operator`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:30:20.667", "Id": "78905", "Score": "1", "body": "A function named `palindrome()` sounds like it should return `true` if it is a palindrome and `false` if it isn't. A function named `reverse()` has no such connotation. If you keep the name `palindrome()`, then make it test for whether the parameter is a palindrome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:34:00.120", "Id": "78906", "Score": "0", "body": "Exactly. Let me clarify the comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:26:03.117", "Id": "78918", "Score": "0", "body": "Since multiplication is commutative you can also avoid half of that loop (it even makes the code 2 digits shorter!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:35:46.460", "Id": "78920", "Score": "0", "body": "I did point that out in the comment :) Maybe it would be clearer just to do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:51:16.997", "Id": "78923", "Score": "4", "body": "\"b) Don't use unsigned values unless you really need them.\" I disagree strongly. Signed integers may overflow with undefined behavior, but unsigned integers don't, which is a plus. Second, the range of unsigned integers is twice as large, hence it may be necessary to use `int64_t` instead of `int32_t`, but `uint32_t` may be sufficient. Yes, one has to be careful with unsigned integers (preventing unintentional overflow), but it's definitively not strictly worse than signed integers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:52:01.127", "Id": "78934", "Score": "0", "body": "@stefan The range of signed integers is exactly as large as the range of unsigned integers. It just doesn't start at zero." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:58:20.970", "Id": "78937", "Score": "1", "body": "@FrerichRaabe Well yes, but I guess you already got what I meant to say: the size of the positive range (and in this problem we only want positive numbers) is roughly twice as large for unsigned counterparts." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:21:15.337", "Id": "45296", "ParentId": "45293", "Score": "5" } }, { "body": "<p>Your function <code>palindrom</code> just \"reverses\" your number without actually checking it is a palindrom. It would probably be more appropriate to give this function a proper name like <code>reverse_number()</code> and to use it in a different function which can be called <code>is_palindrome()</code>.</p>\n\n<p>Please note that a faster implementation for this could be done differently as one could stop as soon as 2 digits do not match but we can consider that this is good enough: it's easy to test and it's easy to understand how it works.</p>\n\n<p>Also, you could get rid of the magic number <code>10</code>. You could for instance provide the base with a default argument.</p>\n\n<p>You should always try to define your variable in the smallest possible scope.</p>\n\n<p>Here's what I have for the helper function :</p>\n\n<pre><code>int reverse_number(int num, int base = 10)\n{\n int new_num = 0;\n\n while (num != 0)\n {\n int digit = num % base;\n new_num = new_num*base + digit;\n num /= base;\n }\n return new_num;\n}\n\nbool is_palindrom(int num)\n{\n return num == reverse_number(num);\n}\n</code></pre>\n\n<hr>\n\n<p>You should compile your code with all warnings activated as they can provide you good hints :</p>\n\n<pre><code>euler3.cpp:28:18: warning: unused variable ‘n’ [-Wunused-variable]\n</code></pre>\n\n<hr>\n\n<p>The way you are iterating is super weird. If you want to iterate over a range with <code>n1</code> and iterate over another range with <code>n2</code>, just use two nested for loops:</p>\n\n<pre><code>for (auto n1 = 999u; n1&gt;=100; n1--)\nfor (auto n2 = 998u; n2&gt;=100; n2--)\n</code></pre>\n\n<p>Also, without any loss of generality, one can assume that <code>n1 &gt;= n2</code> :</p>\n\n<pre><code>for (auto n1 = 999u; n1&gt;=100; n1--)\nfor (auto n2 = n1; n2&gt;=100; n2--)\n</code></pre>\n\n<hr>\n\n<p>Because the values will get smaller, you can break when you find a value smaller that the one you have already found.</p>\n\n<p>At the stage, my code looks like:</p>\n\n<pre><code>int main()\n{\n unsigned int largest = 0;\n\n for (auto n1 = 999u; n1&gt;=100; n1--)\n {\n for (auto n2 = n1; n2&gt;=100; n2--)\n {\n auto prod = n1*n2;\n if (prod &lt; largest)\n break;\n\n if (is_palindrom(prod))\n {\n cout &lt;&lt; \"n1 &lt;&lt; \" &lt;&lt; n1 &lt;&lt; \" n2 \" &lt;&lt; n2 &lt;&lt; \" -&gt; \" &lt;&lt; prod &lt;&lt; endl;\n largest = prod;\n }\n }\n }\n cout &lt;&lt; \"Largest\" &lt;&lt; largest &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:23:45.107", "Id": "78944", "Score": "0", "body": "Wouldn't it be better to have a variable for n2 limit (`n2>=n2_limit`) and set it to n2 when we find a palindrom?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:34:52.320", "Id": "78947", "Score": "0", "body": "It could probably do the trick but I am not quite sure I see the benefit compared to my solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T19:49:09.430", "Id": "79225", "Score": "1", "body": "I like the `break` in the inner loop. If you change the inner loop limits so that `n2` goes from 999 down to `n1`, you would probably find the largest palindrome sooner and make the `break` even more effective." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T10:29:35.600", "Id": "45297", "ParentId": "45293", "Score": "8" } }, { "body": "<p>You could use a <code>while</code> loop instead of this:</p>\n\n<blockquote>\n<pre><code>for(; n1&gt;=100; n2--)\n</code></pre>\n</blockquote>\n\n<p>It would look cleaner like this:</p>\n\n<pre><code>while(n1 &gt;= 100) {\n // ... some code here\n n2--;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T01:24:52.487", "Id": "224449", "ParentId": "45293", "Score": "0" } } ]
{ "AcceptedAnswerId": "45296", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T09:50:47.113", "Id": "45293", "Score": "10", "Tags": [ "c++", "c++11", "programming-challenge", "palindrome" ], "Title": "Project Euler #4 - Largest Palindrome Product" }
45293
<p>C11 is a standard for the C programming language. It replaces the previous C99 standard. C11 introduces a number of features to the language, most notably a detailed memory model focussed on multi-threaded applications. New keywords <code>_Generic</code>, static assertions, library support for multithreading and unicode and more.</p> <p>More details can be found on <a href="http://en.wikipedia.org/wiki/C11_%28C_standard_revision%29" rel="nofollow">the wikipedia C11 entry</a>.<br> More technical details can be found on <a href="http://www.open-std.org/JTC1/SC22/WG14/" rel="nofollow">the open standards organization site</a>, too</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:00:36.947", "Id": "45298", "Score": "0", "Tags": null, "Title": null }
45298
C11 is a standard for the C programming language. It replaces the previous C99 standard. C11 added type-generic expressions, alignment support, static assertions, library support for multithreading and unicode as well as multiple other language and library fixes and additions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:00:36.947", "Id": "45299", "Score": "0", "Tags": null, "Title": null }
45299
<p>This is a byte stream implementation in C. Its usage and purpose should be evident from main.</p> <p>Implementation is not finished; this is just start. Comments are still welcome.</p> <p><strong>.h:</strong></p> <pre><code>#include &lt;stdint.h&gt; typedef struct { uint8_t * data; uint32_t length; uint32_t offset; } ByteStream; int32_t BSInitWithSize(ByteStream *bs, uint32_t len); uint32_t BSNrOfRemainingBytes(ByteStream *bs); int32_t BSFreeUnderlyingArray(ByteStream *bs); void BSPrintContents(ByteStream *bs); void BSRewind(ByteStream *bs); int32_t BSPutU8(ByteStream *bs, uint8_t v); int32_t BSGetU8(ByteStream *bs, uint8_t *out); int32_t BSPutU16LE(ByteStream *bs, uint16_t v); </code></pre> <p><strong>.c:</strong></p> <pre><code>#include "ByteStream.h" #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int32_t BSInitWithSize(ByteStream *bs, uint32_t len) { if (NULL == bs) return -1; // Allocate data array of sufficient length bs-&gt;data = (uint8_t*)malloc(len); // Note: Probably should check return value here memset(bs-&gt;data,0,len); // set values to nil bs-&gt;length = len; bs-&gt;offset = 0; return 0; } uint32_t BSNrOfRemainingBytes(ByteStream *bs) { return bs-&gt;length - bs-&gt;offset; } void BSRewind(ByteStream *bs) { bs-&gt;offset=0; } int32_t BSPutU8(ByteStream *bs, uint8_t v) { if(BSNrOfRemainingBytes(bs)&lt;1) return -1; bs-&gt;data[bs-&gt;offset]=v; bs-&gt;offset++; return 0; } int32_t BSGetU8(ByteStream *bs, uint8_t *out) { if(BSNrOfRemainingBytes(bs)&lt;1) return -1; bs-&gt;offset++; *out= bs-&gt;data[bs-&gt;offset-1]; return 0; } int32_t BSPutU16LE(ByteStream *bs, uint16_t v) { if(BSNrOfRemainingBytes(bs)&lt;2) return -1; // This code compiles on LE machine, so // copying a integer to buffer will write // the integer into the buffer in a little endian way // exactly what this method is supposed to do // Note: Probably this is not portable memcpy(&amp;bs-&gt;data[bs-&gt;offset],&amp;v,2); bs-&gt;offset+=2; return 0; } void BSPrintContents(ByteStream *bs) { int i = 0; for(i=0; i&lt;bs-&gt;offset; i++) { printf("%02X ",bs-&gt;data[i]); } } int32_t BSFreeUnderlyingArray(ByteStream *bs) { // Free underlying data array of BS object if it is not NULL if(NULL != bs-&gt;data) { free(bs-&gt;data); bs-&gt;data=NULL; // Set to NULL return 0; } return -1; } </code></pre> <p><strong>main:</strong></p> <pre><code>#include "stdafx.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; extern "C" { #include "ByteStream.h" } int _tmain(int argc, _TCHAR* argv[]) { ByteStream b; memset(&amp;b,0,sizeof(b)); // Init bs BSInitWithSize(&amp;b,14); // Add values for(int i=0;i&lt;12;i++) { if(-1 == BSPutU8(&amp;b, (uint8_t)i)) printf("Error putting data \n"); printf("Remaining Free Bytes: %d\n",BSNrOfRemainingBytes(&amp;b)); } // Rewind printf("---\n"); BSRewind(&amp;b); // Print values for(int i=0;i&lt;12;i++) { uint8_t t; if(-1 == BSGetU8(&amp;b, &amp;t)) { printf("ERROR Getting value \n"); } else printf("Value at %d is %d \n", i, t); } // Put short integer in a little endian way if(-1 == BSPutU16LE(&amp;b,765)) printf("Error putting short \n"); BSPrintContents(&amp;b); // Free underlying buffer BSFreeUnderlyingArray(&amp;b); return 0; } </code></pre> <p>In many cases I decided to return error code from functions, and pass return values as out parameters.</p>
[]
[ { "body": "<p>A few things:</p>\n\n<ul>\n<li>You are casting the result of your calls to <code>malloc</code>. That is <a href=\"https://stackoverflow.com/a/605858/1364752\">something you shouldn't do</a> actually.</li>\n<li>If possible, try not to used fixed-size integer types (<code>uint32_t</code>, <code>int32_t</code>, etc...) for they are only conditionally supported by the compiler. For example, I doubt that you need a fixed-size type for your error codes. At least, use <code>int_least32_t</code> instead.</li>\n<li>When you are not using any format string, you should consider using <code>puts</code> to <code>printf</code> (<em>e.g.</em> <code>puts(\"---\")</code> instead of <code>printf(\"---\\n\")</code>. That's both shorther and safer.</li>\n<li>Also, you initialize <code>i</code> to <code>0</code> twice in <code>BSPrintContents</code>. That seems pretty useless.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:39:22.033", "Id": "45307", "ParentId": "45302", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T12:01:13.453", "Id": "45302", "Score": "7", "Tags": [ "c", "stream" ], "Title": "Byte Stream implementation in C" }
45302
<p>While the MVC4 template provided by Microsoft is useful, I feel there are a few scenarios that should be covered to help out users trying to log in.</p> <ol> <li>Allow the user to log in with their email address instead of their user name (they can still choose to use their user name). The former is generally easier to remember.</li> <li>If they don't have a local account and try to use one, check if they have previously used an external provider (such as google) to log in and let them know to use it instead.</li> <li>If they have registered an account locally but have not yet confirmed their email, let them know. The current template just warns that the username or password is wrong.</li> </ol> <p>Maybe I'm over-thinking it, but I want to provide the user every opportunity to successfully log in and use the site. My questions:</p> <ol> <li>Is this the correct approach to add these options? </li> <li>Are there any glaring errors with this code, aside from the fact I can probably refactor it? </li> <li>Any glaring security issues I missed?</li> </ol> <pre><code>&lt;HttpPost()&gt; _ &lt;AllowAnonymous()&gt; _ &lt;ValidateAntiForgeryToken()&gt; _ Public Function Login(ByVal model As LoginModel, ByVal returnUrl As String) As ActionResult If ModelState.IsValid Then If IsEmail(model.UserName) Then 'the username is an email address Dim username = GetUserNamebyEmail(model.UserName) If username IsNot Nothing Then If WebSecurity.Login(username, model.Password, persistCookie:=model.RememberMe) Then Return RedirectToLocal(returnUrl) End If 'check if there is a local account Dim localID = GetUserIDbyEmail(model.UserName) If localID Is Nothing Then 'no local account means the username is wrong ModelState.AddModelError("", "The user name or password provided is incorrect.") Else If Not OAuthWebSecurity.HasLocalAccount(localID) Then 'registered via external provider ModelState.AddModelError("", "Please login with the External Provider you have previously used.") Else If Not WebSecurity.IsConfirmed(model.UserName) Then 'has a local account, but hasn't confirmed email ModelState.AddModelError("", "You have not yet confirmed your email.") Else 'password is wrong ModelState.AddModelError("", "The user name or password provided is incorrect.") End If End If End If Else ModelState.AddModelError("", "The email you entered is incorrect.") End If Else 'must be the regular user name, so log in as normal If WebSecurity.Login(model.UserName, model.Password, persistCookie:=model.RememberMe) Then Return RedirectToLocal(returnUrl) End If 'check if there is a local account Dim localID = GetUserIDbyUserName(model.UserName) If localID Is Nothing Then 'no local account means the username is wrong ModelState.AddModelError("", "The user name or password provided is incorrect.") Else If Not OAuthWebSecurity.HasLocalAccount(localID) Then 'registered via external provider ModelState.AddModelError("", "Please login with the External Provider you have previously used.") Else If Not WebSecurity.IsConfirmed(model.UserName) Then 'has a local account, but hasn't confirmed email ModelState.AddModelError("", "You have not yet confirmed your email.") Else 'password is wrong ModelState.AddModelError("", "The user name or password provided is incorrect.") End If End If End If End If End If Return View(model) End Function 'check if input is an email address Public Function IsEmail(ByVal input As String) As Boolean Return Regex.IsMatch(input, "\A(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z") End Function Public Function GetUserNamebyEmail(ByVal email As String) As String Dim username As String = Nothing Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString) Dim cmd As SqlCommand = New SqlCommand("select username from user_info where Email = @Email", conn) cmd.Parameters.Add(New SqlParameter("@Email", System.Data.SqlDbType.NVarChar)) cmd.Parameters("@Email").Value = email conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Try While reader.Read username = reader(0) End While Finally reader.Close() End Try conn.Close() Return username End Function Public Function GetUserIDbyEmail(ByVal email As String) As Integer? Dim userID As Integer? Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString) Dim cmd As SqlCommand = New SqlCommand("select UserID from user_info where Email = @Email", conn) cmd.Parameters.Add(New SqlParameter("@Email", System.Data.SqlDbType.NVarChar)) cmd.Parameters("@Email").Value = email conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Try While reader.Read userID = reader(0) End While Finally reader.Close() End Try conn.Close() Return userID End Function Public Function GetUserIDbyUserName(ByVal username As String) As Integer? Dim userID As Integer? Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString) Dim cmd As SqlCommand = New SqlCommand("select UserID from user_info where UserName = @username", conn) cmd.Parameters.Add(New SqlParameter("@username", System.Data.SqlDbType.NVarChar)) cmd.Parameters("@username").Value = username conn.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() Try While reader.Read userID = reader(0) End While Finally reader.Close() End Try conn.Close() Return userID End Function </code></pre>
[]
[ { "body": "<p>Just a quick comment (my background is mostly C# &amp; VB6 - I never really played with VB.NET): you're hitting the database too often. When you hit it here:</p>\n\n<blockquote>\n<pre><code>Dim username = GetUserNamebyEmail(model.UserName)\n</code></pre>\n \n <p><sub>(isn't that declaration missing a <em>type</em>? Is it <code>Object</code> or <code>String</code>?)</sub></p>\n</blockquote>\n\n<p>...Instead of returning a <code>String</code>, I'd be returning a <code>User</code>, so this call would be moot:</p>\n\n<blockquote>\n<pre><code>Dim localID = GetUserIDbyEmail(model.UserName)\n</code></pre>\n \n <p><sub>(isn't that declaration missing a <em>type</em>? Is it <code>Object</code> or <code>String</code>?)</sub></p>\n</blockquote>\n\n<p>And then in the <code>Else</code> block you're making another one:</p>\n\n<blockquote>\n<pre><code>Dim localID = GetUserIDbyUserName(model.UserName)\n</code></pre>\n \n <p><sub>(again)</sub></p>\n</blockquote>\n\n<p>I think I'd try to restructure the code so as to be able to return a <code>User</code> object regardless of whether <code>model.UserName</code> is an email address or not (i.e. move the <code>IsEmail</code> check into the logic that fetches the <code>User</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:37:28.960", "Id": "78949", "Score": "1", "body": "You can use implicit declaration in VB.Net. If you look at the function 'GetUserNamebyEmail' it returns a string of the username, which is then used in 'Websecurity.Login'. As for hitting the DB - at most it gets hit twice (user uses email to login, but then login fails), at best it never gets hit when user uses their correct username and password to login. I will consider grabbing both username and email for the first scenario (IsEmail = true), or moving that call into the logic that grabs it. Thanks. And thanks for the EDIT. I didn't realize C# tag screws up the formatting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:40:52.173", "Id": "78951", "Score": "0", "body": "@merlot interesting.. so it's like C#'s `var` then. I'll get back to this post when I have a chance, I want to take a deeper look at your code ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:08:16.213", "Id": "45311", "ParentId": "45308", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:42:47.197", "Id": "45308", "Score": "7", "Tags": [ "asp.net", "vb.net", "asp.net-mvc-4" ], "Title": "Customized Template Login" }
45308
<p>Some context: I have code that looks like this (minor issue noted <a href="https://stackoverflow.com/q/22636151/14065">here</a>):</p> <pre><code>Statement select("SELECT * FROM People WHERE ID &gt; ? AND ID &lt; ?"); select.execute(1462, 1477, [](int ID, std::string const&amp; person, double item1, float item2){ std::cout &lt;&lt; "Got Row:" &lt;&lt; ID &lt;&lt; ", " &lt;&lt; person &lt;&lt; ", " &lt;&lt; item1 &lt;&lt; ", " &lt;&lt; item2 &lt;&lt; "\n"; }); </code></pre> <p>Anyway this connects to the MySQL DB and starts pulling data from the server. So inside execute I loop over the results and call the lambda for each row:</p> <pre><code> template&lt;typename Action, typename ...Args&gt; void execute(Args... param, Action action) { // STUFF TO SET up connection. // Start retrieving rows. while(row = results-&gt;getNextRow()) { call(action, row); } } </code></pre> <p>So here row gets a single row from the socket connection with mysql (so it calls the lambda as it receives each row (no pulling the rows into memory first)). So the code I want to review is pulling the data and calling the lambda.</p> <pre><code> // Statement::call template&lt;typename Action&gt; void call(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp; row) { typedef CallerTraits&lt;decltype(action)&gt; trait; typedef typename trait::AllArgs AllArgs; Caller&lt;trait::size, 0, AllArgs, Action&gt;::call(action, row); } </code></pre> <p>This utilizes the helper class <code>CallerTraits</code> and <code>Caller</code> to pull the required rows from the stream and then call the lambda:</p> <pre><code>// CallerTraits // Get information about the arguments in the lambda template &lt;typename T&gt; struct CallerTraits : public CallerTraits&lt;decltype(&amp;T::operator())&gt; {}; template&lt;typename C, typename ...Args&gt; struct CallerTraits&lt;void (C::*)(Args...) const&gt; { static const int size = sizeof...(Args); typedef std::tuple&lt;Args...&gt; AllArgs; }; </code></pre> <p>Then the <code>Caller</code>: </p> <pre><code>// Caller::call() // Reads the next argument required by the lambda from the stream. // An exception will be generated if the next argument on the stream // does not match the type expected by the lambda. template&lt;int size, int index, typename ArgumentTupple, typename Action, typename ...Args&gt; struct Caller { static void call(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp; row, Args... args) { // Get the next argument type required by the lambda. // As defined by index. Then remove all ref and const // bindings. typedef typename std::tuple_element&lt;index, ArgumentTupple&gt;::type NextArgBase; typedef typename std::remove_reference&lt;NextArgBase&gt;::type NextArgCont; typedef typename std::remove_const&lt;NextArgCont&gt;::type NextArg; // Read the next value from the stream. NextArg val; row-&gt;getValue(val); // Recursively call Caller::call() (via doCall()) // To get the next argument we need. All the arguments // are accumulated in the var args parameter `args` doCall&lt;size-1, index+1, ArgumentTupple&gt;(action, row, args..., val); } }; </code></pre> <p>Specialization when no more args need to be retrieved:</p> <pre><code>// Specialization of Caller::call() when we have got all the arguments. // This simply calls the lambda with the arguments we have accumulated. template&lt;int index, typename ArgumentTupple, typename Action, typename ...Args&gt; struct Caller&lt;0, index, ArgumentTupple, Action, Args...&gt; { static void call(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp;, Args... args) { action(args...); } }; </code></pre> <p>Function to deduce parameter types:</p> <pre><code>// Function template needed because we // can not deduce the Args... parameter manually in the call. // so we let the compiler deduce it for us. template&lt;int size, int index, typename ArgumentTupple, typename Action, typename ...Args&gt; void doCall(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp; row, Args... args) { Caller&lt;size, index, ArgumentTupple, Action, Args...&gt;::call(action, row, args...); } </code></pre>
[]
[ { "body": "<p>I would have probably applied the following changes:</p>\n\n<ul>\n<li>Make <code>size</code> a <code>static constexpr</code> variable in <code>CallerTraits</code> instead of simply <code>static const</code>.</li>\n<li><p>Wherever a function simply passes variadic arguments whose types have been deduced, I would have passed <code>args</code> by <a href=\"https://stackoverflow.com/a/3582313/1364752\"><em>universal reference</em></a> (now officially called <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4164.pdf\" rel=\"nofollow noreferrer\"><em>forwarding reference</em></a>) and used <code>std::forward</code> to forward the results to the following functions:</p>\n\n<pre><code>template&lt;int size, int index, typename ArgumentTupple, typename Action, typename ...Args&gt;\nvoid doCall(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp; row, Args&amp;&amp;... args)\n{\n Caller&lt;size, index, ArgumentTupple, Action, Args...&gt;::call(action, row, std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n\n<p>It's a bit hard and quite long to explain how it works exactly - you can find a great explanation in the answer linked above -, but the main point is that using this particular recipe implements perfect forwarding:</p>\n\n<pre><code>template&lt;typename X&gt;\nvoid foo(X&amp;&amp; arg)\n{\n bar(std::forward&lt;X&gt;(arg));\n}\n</code></pre>\n\n<p>The type of the parameters of <code>X&amp;&amp;...</code> in <code>foo</code> will have the same <code>const</code> and reference qualifications than the type of the corresponding parameters in <code>bar</code>. Anyway, the link is by far clearer than I am. Simply remember the recipe and that for this recipe to work, the type <code>X</code> <strong><em>has</em></strong> to be deduced by the function; it may not work if <code>X</code> is known from somewhere else.</p></li>\n<li><p>Instead of creating functions that take a <code>std::unique_ptr&lt;ResultSetRow&gt;&amp;</code> parameters, I would have had <code>Caller&lt;...&gt;::call</code> and <code>doCall</code> them take a <code>ResultSetRow&amp;</code> and dereferenced <code>row</code> right away. I don't know what is the exact return type of <code>results-&gt;getNextRow()</code> so I won't try to assume anything about it and the type that the main <code>call</code> should take as a parameter.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T00:04:06.377", "Id": "79090", "Score": "1", "body": "@LokiAstari For universal references: http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:31:36.503", "Id": "45316", "ParentId": "45310", "Score": "18" } }, { "body": "<p>I find your implementation a bit more complex than necessary. What you want to do is</p>\n\n<ol>\n<li><p>fetch arguments from your \"result set\" <code>row</code> by calling its <code>getValue()</code> in a particular order;</p></li>\n<li><p>use them (as arguments) to call <code>operator()</code> on function object <code>action</code>.</p></li>\n</ol>\n\n<p>This can be done without recursion in <strong>two lines</strong>:</p>\n\n<pre><code>Do{row-&gt;getValue(std::get&lt;N&gt;(args))...};\naction(std::get&lt;N&gt;(args)...);\n</code></pre>\n\n<p>where <code>args</code> is a tuple.</p>\n\n<p><strong>Range</strong></p>\n\n<hr>\n\n<p>Ok, now let's step back to see how this is possible. First, we learn how to count from <code>0</code> to a given number <code>L</code>, in order to construct range <code>0, ..., L-1</code>:</p>\n\n<pre><code>// holds any number of size_t parameters\ntemplate &lt;size_t... N&gt;\nstruct sizes { using type = sizes &lt;N...&gt;; };\n\n// given L&gt;=0, generate sequence &lt;0, ..., L-1&gt;\ntemplate &lt;size_t L, size_t I = 0, typename S = sizes &lt;&gt; &gt;\nstruct Range;\n\ntemplate &lt;size_t L, size_t I, size_t... N&gt;\nstruct Range &lt;L, I, sizes &lt;N...&gt; &gt; : Range &lt;L, I+1, sizes &lt;N..., I&gt; &gt; { };\n\ntemplate &lt;size_t L, size_t... N&gt;\nstruct Range &lt;L, L, sizes &lt;N...&gt; &gt; : sizes &lt;N...&gt; { };\n</code></pre>\n\n<p>This is a very common task, actually borrowed from <a href=\"https://codereview.stackexchange.com/a/44832/39083\">here</a>. There's a better implementation with logarithmic (rather than linear) template depth, but I want to keep it simple here.</p>\n\n<p><strong>\"Do\"?</strong></p>\n\n<hr>\n\n<p>Next, an extremely helpful <code>struct</code> lets us evaluate expressions in a given order:</p>\n\n<pre><code>// using a list-initializer constructor, evaluate arguments in order of appearance\nstruct Do { template &lt;typename... T&gt; Do(T&amp;&amp;...) { } };\n</code></pre>\n\n<p>But beware, due to a <a href=\"http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51253\" rel=\"nofollow noreferrer\">bug</a> since at least version 4.7.0, GCC evaluates in the opposite order, <a href=\"https://stackoverflow.com/a/22515948/2644390\">right-to-left</a>. A workaround is to provide a range in the opposite order, <code>L-1, ..., 0</code>, but I'm not doing this here.</p>\n\n<p><strong>Caller</strong></p>\n\n<hr>\n\n<p>Now, <code>Caller</code> has a generic definition with only two actual parameters, <code>ArgumentTuple</code> and <code>Action</code>. It also reads that tuple's size, say <code>L</code>, and constructs range <code>0, ..., L-1</code> in a third parameter:</p>\n\n<pre><code>// generic Caller\ntemplate&lt;\n typename ArgumentTuple, typename Action,\n typename Indices = typename Range&lt;std::tuple_size&lt;ArgumentTuple&gt;{}&gt;::type\n&gt;\nstruct Caller;\n</code></pre>\n\n<p>Finally, a specialization deduces the generated range as variadic <code>size_t</code> parameters <code>N...</code>. A local tuple of type <code>ArgumentTuple</code> is used to store the arguments, and <code>std::get&lt;N&gt;</code> accesses its <code>N</code>-th element. That's it:</p>\n\n<pre><code>// Caller specialization, where indices N... have been deduced\ntemplate&lt;typename ArgumentTuple, typename Action, size_t... N&gt;\nstruct Caller&lt;ArgumentTuple, Action, sizes&lt;N...&gt; &gt;\n{\n static void call(Action action, std::unique_ptr&lt;ResultSetRow&gt;&amp; row)\n {\n ArgumentTuple args;\n Do{row-&gt;getValue(std::get&lt;N&gt;(args))...};\n action(std::get&lt;N&gt;(args)...);\n }\n};\n</code></pre>\n\n<p>Please note that all the above code compiles but I have not seen it in action since I don't have the database infrastructure. I have just made a minimal definition</p>\n\n<pre><code>struct ResultSetRow { template&lt;typename T&gt; void getValue(T) { } };\n</code></pre>\n\n<p>So I can only hope it works for you.</p>\n\n<p>I am sorry if this looks like a complete rewrite rather than a review, but I couldn't help it :-) At least I've kept the part of your code where you deduce <code>ArgumentTuple</code> from the lambda.</p>\n\n<p><strong>PS-1</strong> If your <code>ResultSetRow::getValue()</code> is <code>void</code>, then you need to adjust its variadic call to</p>\n\n<pre><code>Do{(row-&gt;getValue(std::get&lt;N&gt;(args)), 0)...};\n</code></pre>\n\n<p>so that each sub-expression evaluates to <code>int</code> rather than <code>void</code> (you cannot have a list-initializer made of <code>void</code> arguments).</p>\n\n<p><strong>PS-2</strong> I suspect you're not really managing resources here, so you don't need <code>std::unique_ptr</code>; a plain <code>ResultSetRow&amp;</code> would suffice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T05:00:40.873", "Id": "79108", "Score": "0", "body": "@iavr: Do you have any good references for using templates in the way you do. I am still having trouble reading the templates above (even after studying them, ie. I could probably not write that from scratch myself)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:16:34.820", "Id": "79123", "Score": "2", "body": "@LokiAstari Well, I'm a bit self-taught. The best resource I know on templates is the book by Vardevoorde and Josuttis, but even this has only one (limited) chapter on metaprogramming, and unfortunalety there's no edition covering C++11 (yet). Stroustrup's 4th edition of \"the C++ programming language\" does cover C++11 and again has one chapter on metaprogramming. Anyhow, these are good places to start. Specifically for `Do`, check [variadic templates](http://en.wikipedia.org/wiki/Variadic_templates) and look for `struct pass`. There's some explanation there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:20:29.283", "Id": "79124", "Score": "0", "body": "@LokiAstari For the \"logarithmic depth\" version of `Range`, check [this answer](http://stackoverflow.com/a/21943425/2644390) and look for `make_indexes`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:52:41.953", "Id": "45334", "ParentId": "45310", "Score": "17" } } ]
{ "AcceptedAnswerId": "45334", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:06:35.640", "Id": "45310", "Score": "31", "Tags": [ "c++", "c++11", "template", "lambda" ], "Title": "Dynamically call lambda based on stream input" }
45310
<p>Let's assume I have an enum type</p> <pre><code>enum ComponentState { TURNED_OFF, TURNED_ON, SUSPENDED, TO_REPAIR; } </code></pre> <p>This enum describes a state of some component. Now let's assume I want to export my component to as XML file. Then, of course, I'm going to import my component. So:</p> <pre><code>//Export: componentElement.setAttribute("state", getState.name()); // results in &lt;element state="TURNED_ON"&gt; //Import try { state = ComponentState.valueOf(element.getAttributeValue("state")); } catch (IllegalArgumentException e) { //... } </code></pre> <p>Everything is fine, but problems starts when I change the name of some enum constants, because it sounds better:</p> <pre><code>enum ComponentState { TURNED_OFF, TURNED_ON, SLEEPING, // &lt;- the same sense, but CRASHED; // &lt;- different name (PM's "I want to have") } </code></pre> <p>Note, that doing this I'm loosing a backward compatibility.</p> <p>Question: How do you cope normally with such situations?</p> <h2>1</h2> <pre><code>public String getXMLValue(){ // ... implementation independent from name() } </code></pre> <p>and </p> <pre><code>static ComponentState parseXMLString(String s) { // ... checking if s matches any name() } </code></pre> <p>OR</p> <h2>2</h2> <p>My approach is OK - it should not be expected, that the name on enum will change just because it sounds better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:21:26.250", "Id": "78959", "Score": "0", "body": "@Vogel612 Sorry. Now it's visible (code was not tagged). Fo example suspended -> sleeping. Making that I'm loosing the backward comaptibility... I cannot import values exported by the previous version" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:25:08.683", "Id": "78961", "Score": "0", "body": "@Vogel612 I meant enum constatnts... I've already edited" } ]
[ { "body": "<p>A standard way to do this is to introduce a static method in addition to <code>valueOf(...)</code> that goes something like:</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\n\npublic enum DummyEnum {\n\n TOM, DICK, HARRY;\n\n private static final Map&lt;String, DummyEnum&gt; FUZZY = buildMap();\n\n private static Map&lt;String, DummyEnum&gt; buildMap() {\n Map&lt;String, DummyEnum&gt; mapto = new HashMap&lt;&gt;();\n mapto.put(\"OTOM\", TOM);\n mapto.put(\"ODICK\", DICK);\n mapto.put(\"OHARRY\", HARRY);\n for (DummyEnum de : values()) {\n mapto.put(de.name(), de);\n }\n return mapto;\n }\n\n private static final DummyEnum fuzzyValueOf(String name) {\n return FUZZY.get(name);\n }\n\n public static void main(String[] args) {\n System.out.println(DummyEnum.fuzzyValueOf(\"OHARRY\"));\n System.out.println(DummyEnum.fuzzyValueOf(\"HARRY\"));\n }\n\n}\n</code></pre>\n\n<p>You can change what goes in the <code>buildMap</code> method to suit your needs.... pull data from a database, a config file, whatever.</p>\n\n<p>Note that the <code>valueOf()</code> method throws an exception for invalid names, but the <code>fuzzyValueOf()</code> will return null.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:44:35.663", "Id": "79031", "Score": "0", "body": "Yeah, this is how I solved this problem, but I hoped I can avoid creating a new static logic - 've got tens of similar enums, and I like short code very much :D But I find your approach perfectly correct (sadly :D )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:47:32.277", "Id": "79033", "Score": "1", "body": "@guitar_freak - technically the problem is with the change in the naming of the Enums. It is one of those things that you just have to get right the first time, and changing them is a royal PITA. Try to avoid it (and now you know why)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:26:25.580", "Id": "45325", "ParentId": "45317", "Score": "4" } }, { "body": "<p>instead of the name of the enum you can save the ordinal </p>\n\n<pre><code>//Export:\ncomponentElement.setAttribute(\"state\", getState.ordinal()); // results in &lt;element state=\"1\"&gt;\n\n//Import\ntry {\n state = ComponentState.values()[Integer.parseInt(element.getAttributeValue(\"state\"))];\n} catch (ArrayIndexOutOfBoundsException e) {\n //... \n} catch (NumberFormatException e) {\n //... \n}\n</code></pre>\n\n<p>this makes the code independent of the name but will make it dependent on the order the enums are declared in. and makes the file less human readable </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:49:52.447", "Id": "79015", "Score": "0", "body": "I would beware when using this approach, see the bottom part of my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:41:33.377", "Id": "79030", "Score": "0", "body": "Yeah, right, but - as you've mentioned - this would be order-dependent and therefore more error prone." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:17:55.923", "Id": "45330", "ParentId": "45317", "Score": "1" } }, { "body": "<p>I like rolfl's approach, but I have one thing to add which would make it more compact and flexible:</p>\n\n<p>Use a private constructor to provide a custom save value.</p>\n\n<p>The biggest benefits of using either my or rolfl's approach is that you don't need to remember to add new enum values to the HashMap. In my approach especially, it gives you a clear overview of the enum values with their corresponding save values. As long as you only use one constructor (which I highly recommend) it is impossible to forget to give a save value for the enum. </p>\n\n<p>This approach also allows you to customize their save-values much easier. You can rename your enums all you want, all you need to remember is to not change the saveValue, unless you want incompatibility issues.</p>\n\n<pre><code>enum ComponentState {\n TURNED_OFF(\"off\"),\n TURNED_ON(\"on\"),\n SUSPENDED(\"susp\"),\n TO_REPAIR(\"repair\");\n\n private final String saveValue;\n\n private ComponentState(String saveAs) {\n this.saveValue = saveAs;\n }\n\n private static final Map&lt;String, ComponentState&gt; FUZZY = buildMap();\n\n private static Map&lt;String, ComponentState&gt; buildMap() {\n Map&lt;String, ComponentState&gt; mapto = new HashMap&lt;&gt;();\n for (ComponentState state : ComponentState.values()) {\n mapto.put(state.saveValue, state);\n }\n return mapto;\n }\n\n private static final ComponentState fuzzyValueOf(String name) {\n return FUZZY.get(name);\n }\n\n public String getSaveValue() {\n return this.saveValue;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If you want to have multiple possible save values for the same enum, then use a <code>String...</code> parameter: (However, in this case you need to make sure that you don't use an empty constructor for a field, as that wouldn't give it a specified save value)</p>\n\n<pre><code> private final String[] saveValues;\n private ComponentState(String... saveAs) {\n this.saveValues = saveAs;\n }\n public String getSaveValue() {\n return this.saveValues[0];\n }\n</code></pre>\n\n<hr>\n\n<p>I really can't recommend using the <code>.ordinal</code> approach as ratchet freak suggested, even though it is nice and tidy, consider this enum:</p>\n\n<pre><code>Suit {\n DIAMONDS, HEARTS, SPADES, CLUBS;\n}\n</code></pre>\n\n<p>Now what if you'd like to re-order them?</p>\n\n<pre><code>Suit {\n CLUBS, SPADES, DIAMONDS, HEARTS;\n}\n</code></pre>\n\n<p>Congratulations, spades has become diamonds, clubs is hearts. <a href=\"http://youtu.be/KzNO4Bg5Iog?t=20m50s\" rel=\"nofollow noreferrer\">Down is up and up is down. Logic goes on ski vacation with it's buddy reason</a>.</p>\n\n<p>If you use the <code>.ordinal</code> approach, remember to never ever ever switch places of them. (Me, talking from experience? <a href=\"https://codereview.stackexchange.com/questions/36916/weekend-challenge-poker-hand-evaluation#comment60836_36936\">What makes you think that?</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:49:31.280", "Id": "45337", "ParentId": "45317", "Score": "6" } }, { "body": "<p>If you are using Java 7 or later, a really concise string-to-enum translation method using a can be constructed using a switch statement:</p>\n\n<pre><code>public static ComponentState toEnum(String name) {\n if (name == null) {\n return null;\n }\n\n switch(name) {\n // handle removed enum values\n case \"SUSPENDED\":\n return ComponentState.SLEEPING;\n case \"TO_REPAIR\":\n return ComponentState.CRASHED;\n\n // revert to normal translation\n default:\n return ComponentState.valueOf(name);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:48:56.637", "Id": "79034", "Score": "0", "body": "Hehe, thanks for this tip. I use switch quite rarely, but if I do it I miss this feature. \"<>\" notation as well:D But I'm using Java6 :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:35:51.433", "Id": "45340", "ParentId": "45317", "Score": "1" } } ]
{ "AcceptedAnswerId": "45325", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T14:40:17.070", "Id": "45317", "Score": "7", "Tags": [ "java", "enum" ], "Title": "Saving enum value using name()" }
45317
<p><a href="http://meta.codereview.stackexchange.com/q/1695">Obsolete</a> tag. Do not use.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:34:14.603", "Id": "45318", "Score": "0", "Tags": null, "Title": null }
45318
Obsolete tag. Do not use.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T15:34:14.603", "Id": "45319", "Score": "0", "Tags": null, "Title": null }
45319
<p>I have an algorithm for checking whether one line is contained within another. The lines I have are made up of an ordered array of points, which are just data structures with values for x, y and z. The lines are no necessarily straight. The subline does not need to be going in the same direction as the main line.</p> <p>The algorithm I have currently is:</p> <pre><code>public static bool IsSubline(Point[] subline, Point[] line) { int prevIndex = int.MaxValue; bool contains = false; foreach (Point point in subline) { for (int i = 0; i &lt; line.Length; i++) { if (Equal(point, line[i])) { if (prevIndex == int.MaxValue || System.Math.Abs(prevIndex - i) == 1) { prevIndex = i; contains = true; break; } } contains = false; } if (!contains) { break; } } return contains; } </code></pre> <p><code>Equal</code> is:</p> <pre><code>internal static bool Equal(Point point1, Point point2, float epsilon = CoordinateEpsilon) { return System.Math.Abs(point1.x - point2.x) &lt; epsilon &amp;&amp; System.Math.Abs(point1.y - point2.y) &lt; epsilon &amp;&amp; System.Math.Abs(point1.z - point2.z) &lt; epsilon; } </code></pre> <p>I feel like this could be done in a faster way, anyone have any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:07:36.700", "Id": "78965", "Score": "0", "body": "It's Equal, sorry. I'm away from the computer for an hour or so, but it literally just compares the x's, y's, and z's to within an epsilon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:15:42.330", "Id": "78968", "Score": "0", "body": "just to clarify what you mean: contained means, whether each point in subline is also contained in line, correct? (line: {0,1,1},{1,3,3}; subline:{0.5,2,2}, {0.75, 2.5, 2.5} should not return true?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:21:12.010", "Id": "78971", "Score": "0", "body": "Ah, that's a good points you bring up actually. No, all we really have to check is that the actual points forming the line are matched, not any points that might be on the line between points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T23:53:27.547", "Id": "79087", "Score": "1", "body": "There are a variety of [well-known substring algorithms](https://en.wikipedia.org/wiki/String_searching_algorithm) which you could apply here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T21:49:32.440", "Id": "104911", "Score": "0", "body": "what if you have a line of 5 points and a sub-line of 3 points where the first and the last points of the line are not part of the subline? will this program say that the sub-line is not part of the line?" } ]
[ { "body": "<p>Yes it can be done faster. Your algorithm has a \\$O(n^2)\\$ time.</p>\n\n<p>Idea: store the indexes of the points of the line in a dictionary and use the points as key (I assume that two distinct points never have the same coordinates. If this is not the case, then an index list would have to be stored for each point).</p>\n\n<pre><code>var lineIndexes = new Dictionary&lt;Point, int&gt;();\n\n//TODO: add the points of the line to the dictionary\n\nforeach (int i = 0; i &lt; subline.Length - 1; i++) {\n Point sublinePoint1 = subline[i];\n Point sublinePoint2 = subline[i + 1];\n\n int k; // Index in line.\n If (lineIndexes.TryGetValue(sublinePoint1, out k) &amp;&amp; // We found one matching point AND\n ( k &gt; 0 &amp;&amp; sublinePoint2.Equals(line[k - 1]) || // (previous one matches OR\n k &lt; line.Lengh - 1 &amp;&amp; sublinePoint2.Equals(line[k + 1]))) {// next one matches)\n\n return true;\n }\n}\nreturn false;\n</code></pre>\n\n<p>This is \\$O(n)\\$, since the dictionaries have a constant access time.</p>\n\n<hr>\n\n<p><strong><code>Equal</code> vs. <code>Equals</code></strong></p>\n\n<p>Every object (other than <code>System.Object</code>) inherits <code>Equals</code> and <code>GetHashCode</code> from <code>System.Object</code>. Do not introduce your own <code>Equal</code> method but override <code>Equals</code> and <code>GetHashCode</code> in your own objects. This is necessary for right functioning of the dictionary and other .NET data structures.</p>\n\n<p>If you cannot do that, there are overloads of the dictionary's constructor accepting an <code>IEqualityComparer&lt;TKey&gt;</code>. Provide your own implementation of <code>IEqualityComparer&lt;Point&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:30:52.910", "Id": "78975", "Score": "0", "body": "you kinda break the abstraction level. your code requires a high level of understanding the problem in itself, and thus is hard to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:34:00.383", "Id": "78977", "Score": "0", "body": "Yes (where I assume that one of the two is for filling the dictionary), but `O(m + n)` is equal to `O(n)` since only the behavior for n's going towards infinity is considered. The big-O notation is not a calculation of the actual time in seconds. `O(n)` only says: It's linear, but no more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:39:14.147", "Id": "78978", "Score": "0", "body": "thanks for the lesson ;) my other point is still standing though. I think you should extract the if statement to a method, to make more clear what actually happens there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:44:35.060", "Id": "78979", "Score": "2", "body": "Ah, I was just about to ask about Equals there. Unfortunatly the Point object is from an API, and I can't update it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:26:08.053", "Id": "45324", "ParentId": "45320", "Score": "6" } }, { "body": "<p>That random <code>static bool Equal</code> method with an optional parameter, is confusing.</p>\n\n<p>There's already <code>object.Equals</code> with that name <em>and functionality</em> - what you need here is <em>custom equality behavior</em>... and that is achieved by overriding <code>object.Equals</code>:</p>\n\n<pre><code>public struct LinePoint\n{\n public Point ApiPoint { get; set; }\n\n public override bool Equals(object obj)\n {\n return Equals(obj, CoordinateEpsilon);\n }\n\n public bool Equals(object obj, float epsilon)\n {\n // your implementation\n }\n}\n</code></pre>\n\n<p>Note the optional parameter is replaced with a method overload.</p>\n\n<p>The fact that <code>Point</code> is from an API that you can't modify, shouldn't stop you from <em>extending</em> the type, or to <em>compose</em> a new structure with it, which you can modify at will.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:55:56.603", "Id": "78983", "Score": "0", "body": "Also, as @Olivier mentioned in his answer, you should also override `GetHashCode` when overriding `Equals`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:54:50.740", "Id": "78999", "Score": "1", "body": "There is a certain amount of allowance that his `Equals` method allows for. When dealing with `float` and `double`, the value is subject to change slightly due to the way it is stored, so when comparing point you need to give a certain amount of leeway in-case the value has changed. this kind of equals is also used a lot in 3d engines when you want to know if something is \"roughly\" in the same position." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:47:10.293", "Id": "45326", "ParentId": "45320", "Score": "6" } }, { "body": "<p>Just looking at the code, you could eliminate one Nested <code>if</code> statement from this</p>\n\n<pre><code>foreach (Point point in subline)\n{\n for (int i = 0; i &lt; line.Length; i++)\n {\n if (Equal(point, line[i]))\n {\n if (prevIndex == int.MaxValue || System.Math.Abs(prevIndex - i) == 1)\n {\n prevIndex = i;\n contains = true;\n break;\n }\n }\n\n contains = false;\n }\n\n if (!contains)\n {\n break;\n }\n}\n</code></pre>\n\n<p>and make it</p>\n\n<pre><code>foreach (Point point in subline)\n{\n for (int i = 0; i &lt; line.Length; i++)\n {\n if (Equal(point,line[i]) &amp;&amp; (prevIndex == int.MaxValue || System.Math.Abs(prevIndex - i) == 1))\n {\n prevIndex = i;\n contains = true;\n break;\n }\n contains = false;\n }\n\n if (!contains)\n {\n break;\n }\n}\n</code></pre>\n\n<p>It will look at the first expression and evaluate it, if it is true it will evaluate the second expression and decide if that is true, if both expressions are true then it will run the code inside the <code>then</code> block.</p>\n\n<hr>\n\n<p>It looks like we can eliminate another if statement, the one that asks if contains is false. instead of that we can use a return because we don't want to keep going if something doesn't match we already know that the subline doesn't match.</p>\n\n<pre><code>foreach (Point point in subline)\n{\n for (int i = 0; i &lt; line.Length; i++)\n {\n if (Equal(point,line[i]) &amp;&amp; \n (prevIndex == int.MaxValue || System.Math.Abs(prevIndex - i) == 1))\n {\n prevIndex = i;\n contains = true;\n break;\n }\n return false;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The big problem that I am seeing is that the code you have currently will show that a line is not a sub-line if the sub-line is in the middle of the line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:57:04.413", "Id": "78984", "Score": "0", "body": "The first break is because we have a a matching value at this value in the subline, and it's within 1 index of the previous one, so set contains to true and move on to the next one. The second break is there because, if we reach that point and contains is false, it means the current value of subline is not present in line at all, and so we mayaswell quit now, because subline is, in fact, not a subline (the liar)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:58:00.647", "Id": "78985", "Score": "0", "body": "EDIT: I just noticed your edit, and I'm not sure what you mean, there only is one subline to be checked, we're looping through the points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:03:09.623", "Id": "78989", "Score": "0", "body": "The break exits the first for loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:05:16.640", "Id": "78991", "Score": "1", "body": "http://msdn.microsoft.com/en-us/library/adbctzc4.aspx The first example there shows a break within an if exiting the enclosing for. I might be misunderstanding you though." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:54:18.230", "Id": "45328", "ParentId": "45320", "Score": "1" } }, { "body": "<ol>\n<li><p>I think what you've got here would go much better in Extension Methods. I also have done this with the IsSubline Method of yours, but I've renamed it to ContainsSubLine, and changed it around a bit, that's my next point.</p>\n\n<pre><code>public static class Extensions\n{\n internal static bool RoughlyEquals(this Point point1, Point point2, float epsilon = CoordinateEpsilon)\n {\n return System.Math.Abs(point1.x - point2.x) &lt; epsilon &amp;&amp;\n System.Math.Abs(point1.y - point2.y) &lt; epsilon &amp;&amp;\n System.Math.Abs(point1.z - point2.z) &lt; epsilon;\n }\n}\n</code></pre></li>\n<li><p>While my algorithm for your problem does contain many nested loops, I will go through it and explain my reasoning.</p>\n\n<p>I started off by creating a list of all possible locations within the main <code>line</code> where the <code>subline</code> could have been starting.</p>\n\n<pre><code>var possibleStartingLocations = new List&lt;int&gt;();\n\nfor (int i = 0; i &lt; line.Count; i++)\n{\n if (line[i].RoughlyEquals(subline.First()))\n possibleStartingLocations.Add(i);\n}\n</code></pre></li>\n<li><p>Now any calculations we do from here, we will be starting with one of these points. you could call a method doing this calculation on every one of these starting indices, or have awesome nested for-loops!</p>\n\n<pre><code>foreach (int i in possibleStartingLocations)\n{\n</code></pre></li>\n<li><p>Because the subline could be traveling either direction down the main line, we need to check both directions. </p>\n\n<pre><code>foreach (int direction in new int[] { 1, -1 })\n{\n</code></pre></li>\n<li><p>At this point all we have to do is travel down the main line alongside the subline, and check to see if every point is equal in succession. If at any point they are not, we break out and try our next series. But if we do finish going through the points and they were all equal, we have a match</p>\n\n<pre><code>int newPos;\nvar found = true;\nfor (int offset = 0; (newPos = offset * direction + i) &gt;= 0 &amp;&amp; newPos &lt; line.Count; offset++)\n{\n if (!line[newPos].RoughlyEquals(subline[offset]))\n {\n found = false;\n break;\n }\n}\nif (found)\n{\n return true;\n}\n</code></pre></li>\n<li><p>If we never find a match, defaultly return false at the end of this method.</p></li>\n<li><p>This is \\$O(n)\\$ because you only ever iterate over the entire loop once. Then you only iterate over the parts you need, which does not add to your \\$O\\$.</p></li>\n</ol>\n\n<hr>\n\n<p>Here is the full dump of the new Extension methods class</p>\n\n<pre><code>public static class Extensions\n{\n public static bool ContainsSubLine(this IList&lt;Point&gt; line, IList&lt;Point&gt; subline)\n {\n //TODO: Implement argument checking to make sure line and subline are not null and contain points.\n\n var possibleStartingLocations = new List&lt;int&gt;();\n\n //Find all possible starting points\n for (int i = 0; i &lt; line.Count; i++)\n {\n if (line[i].RoughlyEquals(subline.First()))\n possibleStartingLocations.Add(i);\n }\n\n foreach (int i in possibleStartingLocations)\n {\n //Checking backwards and forwards from that point\n foreach (int direction in new int[] { 1, -1 })\n {\n int newPos;\n var found = true;\n for (int offset = 0; (newPos = offset * direction + i) &gt;= 0 &amp;&amp; newPos &lt; line.Count; offset++)\n {\n if (!line[newPos].RoughlyEquals(subline[offset]))\n {\n found = false;\n break;\n }\n }\n if (found)\n {\n return true;\n }\n }\n }\n\n return false;\n }\n\n internal static bool RoughlyEquals(this Point point1, Point point2, float epsilon = CoordinateEpsilon)\n {\n return System.Math.Abs(point1.x - point2.x) &lt; epsilon &amp;&amp;\n System.Math.Abs(point1.y - point2.y) &lt; epsilon &amp;&amp;\n System.Math.Abs(point1.z - point2.z) &lt; epsilon;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-28T19:22:35.147", "Id": "104657", "Score": "0", "body": "I think it's only O(n) if you assume that there are no repeated points." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:01:25.947", "Id": "45338", "ParentId": "45320", "Score": "5" } } ]
{ "AcceptedAnswerId": "45338", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:01:21.623", "Id": "45320", "Score": "10", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Increase performance in sub-line detection" }
45320
<p>I am stuck to define a generic repository with AutoFac IOC container. I am keeping thing very simple and only showing relevant information. </p> <p><strong><code>BaseEntity</code></strong></p> <pre><code>public abstract class BaseEntity { public int Id { get; set; } } </code></pre> <p><strong><code>IRepository</code></strong></p> <pre><code>public interface IRepository&lt;TEntity&gt; where TEntity : BaseEntity { List&lt;TEntity&gt; GetAll(); void Insert(TEntity entity); void Update(TEntity entity); void Delete(TEntity entity); } </code></pre> <p><strong><code>IUnitOfWork</code></strong> </p> <pre><code>public interface IUnitOfWork : IDisposable { int SaveChanges(); void Dispose(bool disposing); IRepository&lt;TEntity&gt; Repository&lt;TEntity&gt;() where TEntity : BaseEntity; } </code></pre> <p><strong><code>IService</code></strong></p> <pre><code>public interface IService { IUnitOfWork UnitOfWork { get; } } </code></pre> <p><strong><code>IService&lt;TEntity&gt;</code></strong> </p> <pre><code>public interface IService&lt;TEntity&gt; : IService where TEntity : BaseEntity { List&lt;TEntity&gt; GetAll(); TEntity GetById(int id); void Add(TEntity entity); void Update(TEntity entity); void Delete(TEntity entity); } </code></pre> <p><strong><code>UnitOfWork</code></strong> </p> <pre><code>public class UnitOfWork : IUnitOfWork { private readonly IEntitiesContext _context; private bool _disposed; private ObjectContext _objectContext; private Hashtable _repositories; private DbTransaction _transaction; public UnitOfWork(IEntitiesContext context) { _context = context; } public int SaveChanges() { return _context.SaveChanges(); } public IRepository&lt;TEntity&gt; Repository&lt;TEntity&gt;() where TEntity : BaseEntity { if (_repositories == null) { _repositories = new Hashtable(); } var type = typeof(TEntity).Name; if (_repositories.ContainsKey(type)) { return (IRepository&lt;TEntity&gt;)_repositories[type]; } var repositoryType = typeof(EntityRepository&lt;&gt;); _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context)); return (IRepository&lt;TEntity&gt;)_repositories[type]; } } </code></pre> <p><strong><code>Service&lt;TEntity&gt;</code></strong></p> <pre><code>public class Service&lt;TEntity&gt; : IService&lt;TEntity&gt; where TEntity : BaseEntity { public IUnitOfWork UnitOfWork { get; private set; } public Service(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } public List&lt;TEntity&gt; GetAll() { return UnitOfWork.Repository&lt;TEntity&gt;().GetAll(); } } </code></pre> <p><strong><code>EntityRepository&lt;TEntity&gt;</code></strong> </p> <pre><code>public class EntityRepository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : BaseEntity { private readonly IEntitiesContext _context; private readonly IDbSet&lt;TEntity&gt; _dbEntitySet; public EntityRepository(IEntitiesContext context) { _context = context; _dbEntitySet = _context.Set&lt;TEntity&gt;(); } public List&lt;TEntity&gt; GetAll() { return _dbEntitySet.ToList(); } } </code></pre> <p>Now these are generic repository, services and unit-of-work. In my presentation I am using <code>IService&lt;T&gt;</code> which will be injected through AutoFac. Now I have 2 concerns:</p> <ol> <li><p>I am directly using <code>EntityRepository</code> inside <code>UnitOfWork var repositoryType = typeof(EntityRepository&lt;&gt;)</code>, which is a problem for me because I am injecting dependencies through IOC.</p></li> <li><p>If I need to use a custom Repository (by inheriting <code>EntityRepository</code>) in future, how can I inject it in my <code>UnitOfWork</code>?</p></li> </ol>
[]
[ { "body": "<p>First, I would caution against using the generic repository + unit of work pattern that was super trendy a few years ago because it has problems not unlike the problems you're facing (along with problems stemming from the fact that EF crosses traditional DAL/Domain/BL boundaries). Simply put, I would not use repositories with EF unless absolutely necessary, and if I had to, I would not use the generic repository pattern.</p>\n\n<p>If you're hell-bent on using this pattern, then you will need to understand the origins of the problem you're facing. Because you have a generic type being returned by your UnitOfWork \"factory,\" you aren't able to instantiate it during your bootstrapping, you are being forced to to instantiate it on-demand at runtime, resolving using the type you're using in your <code>UnitOfWork</code> method call. </p>\n\n<p>If you are okay with using the same repository instance for all of your resolutions, then just make your objects require <code>Repository&lt;SomeType&gt;</code> in your object constructors or properties with public setters, then use <code>RegisterGeneric()</code>. You can see how that is used <a href=\"https://stackoverflow.com/questions/15226536/register-generic-type-with-autofac\">here</a>. This bypasses the entire \"at runtime\" requirement. </p>\n\n<p>If you want to maintain the pattern of fetching a repository using a method, then you need to treat your <code>UnitOfWork</code> class as a factory and use <a href=\"http://autofac.readthedocs.org/en/latest/resolve/relationships.html#dynamic-instantiation-func-b\" rel=\"nofollow noreferrer\">dynamic instantation</a>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-24T20:51:48.877", "Id": "97990", "ParentId": "45322", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:23:03.897", "Id": "45322", "Score": "4", "Tags": [ "c#", "asp.net", "entity-framework", "dependency-injection", "autofac" ], "Title": "Generic Repository, UnitOfWork and IOC container" }
45322
<p>I have an axis-aligned bounding box (AABB) that I've coded, but at the moment it is very redundant. I feel like there are variables that I can get rid of. I need the AABB to be very fast, and I'd like it to be more lightweight than it is.</p> <pre><code>#pragma once #include "Engine.h" // Collision #include "Vec2D.h" // End Collision #include "Renderer.h" struct ENGINE_API AABB { private: Vec2D min; Vec2D max; double x; double y; double width; double height; double xwidth; // x + width double yheight; // y + height double vertMid; // vertical mid, cached for quadtree double horzMid; // horizontal mid, cached for quadtree // Normalize void calcMid() { vertMid = x + (width / 2); horzMid = y + (height / 2); xwidth = x + width; yheight = y + height; } void init(Vec2D, Vec2D); // End Normalize public: // Constructor AABB(Vec2D min, Vec2D max) { init(min, max); } AABB(double x, double y, double width, double height){ init(Vec2D(x, y), Vec2D(x + width, y + height)); } // End Constructor // Getters double getX()const { return x; } double getY()const { return y; } double getWidth()const { return width; } double getHeight()const { return height; } double getHorzMid()const { return horzMid; } double getVertMid()const { return vertMid; } double getXWidth()const { return xwidth; } double getYHeight()const { return yheight; } // End Getters // Base bool collides(AABB other) { if (xwidth &lt; other.x || x &gt; other.xwidth) { return false; } if (yheight &lt; other.y || y &gt; other.yheight) { return false; } return true; } bool contains(Vec2D point) { if (x &gt; point.getX() || xwidth &lt; point.getX()) { return false; } if (y &gt; point.getY() || yheight &lt; point.getY()) { return false; } return true; } void move(double x, double y) { this-&gt;x = x; this-&gt;y = y; calcMid(); } // End Base // Testing void render(Renderer&amp; renderer) { sf::RectangleShape shape; shape.setPosition(x, y); shape.setOutlineColor(sf::Color::Red); shape.setOutlineThickness(3); shape.setSize(sf::Vector2f(width, height)); renderer.render(shape); } // End Testing }; </code></pre> <p>And the messy part:</p> <pre><code>void AABB::init(Vec2D one, Vec2D two) { double x1 = one.getX(); double y1 = one.getY(); double xx = two.getX(); double yy = two.getY(); if (x1 &gt; xx) { if (y1 &gt; yy) { min = Vec2D(xx, yy); max = Vec2D(x1, y1); } else { min = Vec2D(xx, y1); max = Vec2D(x1, yy); } } else { if (y1 &gt; yy) { min = Vec2D(x1, yy); max = Vec2D(xx, y1); } else { min = Vec2D(x1, y1); max = Vec2D(xx, yy); } } x = min.getX(); y = min.getY(); width = max.getX() - x; height = max.getY() - y; calcMid(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:08:34.473", "Id": "78992", "Score": "0", "body": "Please add the definition of your `init` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:49:39.223", "Id": "79052", "Score": "0", "body": "Sorry @ChrisW, added" } ]
[ { "body": "<p>adding and halving is cheap, don't bother optimizing it out unless it is a problem</p>\n\n<p>all you need is <code>min</code> and <code>max</code> and derive the rest from that:</p>\n\n<pre><code>double getMinX()const {\n return min.getX();\n}\n\n\ndouble getWidth()const {\n return max.getX()-min.getX();\n}\n\n\ndouble getXMid()const {\n return (max.getX()+min.getX())/2;\n}\n\n\ndouble getMaxX()const {\n return max.getX();\n}\n\nbool contains(Vec2D point) {\n if (min.getX() &gt; point.getX() || max.getX() &lt; point.getX()) { return false; }\n if (min.getY() &gt; point.getY() || max.getY() &lt; point.getY()) { return false; }\n\n return true;\n}\n</code></pre>\n\n<p>and so on</p>\n\n<p>however given that this is just a POD you can make the fields public and not bother with the accessor methods</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:19:17.470", "Id": "78995", "Score": "0", "body": "FWIW compiler can usually optimize the overhead of getter/setter call away, so I'd prefer having it encapsulated..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:47:37.243", "Id": "45327", "ParentId": "45323", "Score": "2" } }, { "body": "<p>In <a href=\"https://codereview.stackexchange.com/questions/45172/determine-quadrant-of-code#comment78680_45176\">a comment in your other question</a> you claimed,</p>\n\n<blockquote>\n <p>Thank you, Caching vertMid and horzMid really helped.</p>\n</blockquote>\n\n<p>Whether caching is helpful depends on:</p>\n\n<ul>\n<li>How often you used the cached data</li>\n<li>How tight your performance requirements are</li>\n<li>Whether your cache implementation is reliable</li>\n</ul>\n\n<p>One of your comments says,</p>\n\n<pre><code>// vertical mid, cached for quadtree\n</code></pre>\n\n<p>Only your testing can show whether that optimization is helpful.</p>\n\n<p>From a performance point of view, in general:</p>\n\n<ul>\n<li>If it's not used it's harmful to cache</li>\n<li>If it's used once then it's harmless/useless to cache</li>\n<li>If it's used several times then it's useful to cache</li>\n</ul>\n\n<p>However making something bigger (by caching extra values) can also have some negative effect on performance, e.g. because you can't fit so many objects in the CPU cache (which is faster than memory): which is why you should profile/test to see whether caching makes it faster in practice as well as in theory.</p>\n\n<hr>\n\n<p>If you want to eliminate duplicate variables, you only need 4 doubles:</p>\n\n<ul>\n<li>min and max</li>\n<li>or, x and either width or xwidth, and y and either height and yheight</li>\n</ul>\n\n<hr>\n\n<p>I found your xwidth and yheight names confusing to read; I would have preferred 'right' and 'bottom'.</p>\n\n<hr>\n\n<p>If you have large structs, you may improve performance by <strong>curing your habit of passing objects by value instead of by reference</strong>. For example, this ...</p>\n\n<pre><code>bool collides(AABB other)\n</code></pre>\n\n<p>... should be ...</p>\n\n<pre><code>bool collides(const AABB&amp; other) const\n</code></pre>\n\n<hr>\n\n<p>You can also <strong>use different classes for different purposes</strong>. For example, the <code>AABB bounds</code> member of <a href=\"https://codereview.stackexchange.com/q/45178/34757\">your Quadtree class</a> needs getHorzMid() and getVertMid() members, but those methods aren't needed/used by the AABB which you return using Locatable::getAABB(). So you could use two classes, e.g. AABB (without getHorzMid and getVertMid members), and a SplittableAABB class (used as a member of Quadtree) which adds those members.</p>\n\n<hr>\n\n<p>I don't much like AABB as a class name: partly because all-upper-case looks like a macro to me: consider <code>Bounds</code> or <code>Rect</code> or <code>Rectangle</code> instead.</p>\n\n<hr>\n\n<p>Your current code creates but doesn't read the initialize the min and max data members.</p>\n\n<p>Your move method doesn't update the data in these members (rendering that data untrue).</p>\n\n<p>Maybe Vec2D min and Vec2D max should be (temporary) local variables of your init function, not (permanent) member data of the class.</p>\n\n<p>The parameters passed to the <code>AABB(Vec2D min, Vec2D max)</code> constructor should probably be named one and two not min and max (and should possibly be passed by reference not by value).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:17:27.133", "Id": "79058", "Score": "0", "body": "I've decided to do a couple things:\nVec2D x and y are now public, \nAABB no longer has x, y, width, height, \nThere are now two methods `getWidth()` and `getHeight()`, \nand `min` and `max` are now public, and are used regularly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T17:48:01.100", "Id": "45332", "ParentId": "45323", "Score": "4" } }, { "body": "<p><strong>Synopsis</strong></p>\n\n<p>I see there's already an accepted answer for this question and that the question is a few years old. I'd like to add my review and feedback anyway since I believe it would add over what's already been said.</p>\n\n<p>I've written code for an AABB structure before so I've had opportunity to think of this problem in the past. That said, I agree that there are variables that you can get rid of and having taken a look at your code, I'd prefer the AABB to be lighter weight as well &mdash; though what's \"lighter weight\" is more subjective of course than a count of variables.</p>\n\n<p><strong>Review</strong></p>\n\n<p>I'm just reciting here points from the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"nofollow noreferrer\">C++ Core Guidelines</a> that come first to mind for me on looking at your code:</p>\n\n<ol>\n<li>\"Prefer initialization to assignment in constructors\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors\" rel=\"nofollow noreferrer\">C.49</a>).</li>\n<li>\"Make a function a member only if it needs direct access to the representation of a class\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c4-make-a-function-a-member-only-if-it-needs-direct-access-to-the-representation-of-a-class\" rel=\"nofollow noreferrer\">C.4</a>).</li>\n<li>\"Use <code>class</code> if the class has an invariant; use <code>struct</code> if the data members can vary independently\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c2-use-class-if-the-class-has-an-invariant-use-struct-if-the-data-members-can-vary-independently\" rel=\"nofollow noreferrer\">C.2</a>).</li>\n<li>I'd rather the AABB class itself didn't cache data. Or: \"use compact data structures\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#per16-use-compact-data-structures\" rel=\"nofollow noreferrer\">Per.16</a>), \"space is time\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#per18-space-is-time\" rel=\"nofollow noreferrer\">Per.18</a>), but also \"don't make claims about performance without measurements\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#per6-dont-make-claims-about-performance-without-measurements\" rel=\"nofollow noreferrer\">Per.6</a>).</li>\n<li>Your AABB code doesn't seem to have a default constructor: \"Ensure that a value type class has a default constructor\" (<a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c43-ensure-that-a-value-type-class-has-a-default-constructor\" rel=\"nofollow noreferrer\">C.43</a>).</li>\n</ol>\n\n<p><strong>Alternative Approach</strong></p>\n\n<p>An approach that I liked taking when I had worked on an AABB before was to step back and think in terms of invariants: i.e. recognize what properties really have to be maintained for the end result to reliably represent an axis aligned bounding box. From that perspective, there's really only the min and max values on each axis.</p>\n\n<p>For two dimensional space as it seems you're using, would you believe that the AABB only needs two variables then? And moreover that these two variables are completely independent of each other such that the AABB can be a class that simply publicly exposes the two variables? I was happily surprised and pleased when I realized that indeed this was the case.</p>\n\n<p>For the moment, let's call the type of each of this AABB class <code>I</code> and see this AABB:</p>\n\n<pre><code>struct aabb {\n // The following could instead be a 2-element array of I.\n // That'd be preferable IMO but not for here/now.\n I x; // data relates to the x-axis\n I y; // data relates to the y-axis\n};\n</code></pre>\n\n<p>As is, this AABB class needs only non-friend non-member functions to manipulate its instances. I prefer these and put forward that:</p>\n\n<ol>\n<li>we should prefer non-friend non-member functions, and</li>\n<li>we should avoid writing functions as methods unless the function needs unfettered access to non-public data.</li>\n</ol>\n\n<p>At least that is, if we want to <a href=\"http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197\" rel=\"nofollow noreferrer\">improve encapsulation</a>.</p>\n\n<p>Okay so now back to <code>I</code>... What is this class <code>I</code> perhaps you ask?? It's a class that represents an interval defined by a minimum value and a maximum value. That's really the only invariant needed to be maintained in an AABB. Here's a skeleton of class for this (written herein by hand and which could itself be improved more I'd bet but hopefully serves for illustration):</p>\n\n<pre><code>class interval {\n using value_type = double; // or float, or templated type, etc. \n\n // Use infinity if has_infinity() true, else max() &amp; lowest()...\n // Where min &amp; max are initialized crossed-over.\n value_type min_ = +std::numeric_limits&lt;value_type&gt;::infinity();\n value_type max_ = -std::numeric_limits&lt;value_type&gt;::infinity();\n\n using pair_type = std::pair&lt;value_type, value_type&gt;;\n\n interval(pair_type pair):\n min_{pair.first}, max_{pair.second} {}\n\npublic:\n interval() = default;\n\n interval(const value_type&amp; a, const value_type&amp; b):\n interval{std::minmax(a, b)} {}\n\n // add copy constructor, copy assignment, etc.\n\n value_type get_min() const { return min_; }\n value_type get_max() const { return max_; }\n\n // some non-const methods needed if the interval needs to be modifiable\n\n // say we need to be able shift the interval...\n interval&amp; shift(const value_type&amp; arg) {\n min_ += arg;\n max_ += arg;\n }\n\n // or to include a new point (possibly expanding interval)\n interval&amp; include(const value_type&amp; arg) {\n min_ = std::min(arg, min_);\n max_ = std::max(arg, max_);\n }\n};\n\n// Now just using interval::get_min() and interval::get_max()\n// the following can be written as a \"free function\".\nbool is_overlapping(const interval&amp; a, const interval&amp; b);\n</code></pre>\n\n<p>Here the interval class is certainly more involved than the AABB class. Through the composition however, I think we can agree that the AABB class itself has at least been simplified.</p>\n\n<p>For instance, the collides functionality for the AABB can this way be implemented something like the following (also as a \"free function\"):</p>\n\n<pre><code>bool is_overlapping(const aabb&amp; arg1, const aabb&amp; arg2)\n{\n return is_overlapping(arg1.x, arg2.x) &amp;&amp; is_overlapping(arg1.y, arg2.y);\n}\n</code></pre>\n\n<p>Or, say for example to include a <code>Vec2D</code> into an <code>aabb</code>:</p>\n\n<pre><code>aabb&amp; include(aabb&amp; var, const Vec2D&amp; val) {\n var.x.include(val.getX());\n var.y.include(val.getY());\n}\n</code></pre>\n\n<p>Is the composition using the interval class simpler overall??</p>\n\n<p>Recall that in your code, you have all this code combined into the methods of the AABB class. It's basically got twice the code for maintaining the invariant of the interval compared to having two instances of an <code>interval</code> class. That duplication is unnecessary of course if the same result can be had without the duplication, to wit is the <code>interval</code> class.</p>\n\n<p>I'm not a fan of the dogma I see us wielding (us coders that is), but the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">\"single responsibility principle\"</a> (in \"SOLID\") comes to mind here and is probably worthwhile bringing up nevertheless. If you're not familiar with it already, take a gander at the link I've provided for it (to Wikipedia).</p>\n\n<p>For complete and working examples of interval and AABB classes (though by no means meant to be perfect examples; only complete &amp; working ones), you can take a look at <a href=\"https://github.com/louis-langholtz/PlayRho/blob/master/PlayRho/Common/Interval.hpp\" rel=\"nofollow noreferrer\">Interval</a> and <a href=\"https://github.com/louis-langholtz/PlayRho/blob/master/PlayRho/Collision/AABB.hpp\" rel=\"nofollow noreferrer\">AABB</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-03T07:40:10.850", "Id": "181900", "ParentId": "45323", "Score": "1" } } ]
{ "AcceptedAnswerId": "45332", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:25:03.290", "Id": "45323", "Score": "5", "Tags": [ "c++" ], "Title": "Eliminate axis-aligned bounding box (AABB) variables" }
45323
<p><strong>Fast Time conversion</strong></p> <p>I'm trying to write a very fast time-to-string and string-to-time function.</p> <p>I noticed that on low CPU mobile devices this function has, even if minimal, impact on the performance of the overall canvas animation.</p> <p><strong>Milliseconds to Time string (HH:MM:SS.mss)</strong></p> <p>In this function: is there a shorter &amp; faster way to pad the numbers?</p> <pre><code>function ms2TimeString(a,ms,s,m,h){// time(ms) return ms=a%1e3|0, s=a/1e3%60|0, m=a/6e4%60|0, h=a/36e5%24|0, (h&gt;0?(h&lt;10?'0'+h:h)+':':'')+ //display hours only if necessary (m&lt;10?'0'+m:m)+':'+ (s&lt;10?'0'+s:s)+'.'+ (ms&lt;100?(ms&lt;10?'00'+ms:'0'+ms):ms) } </code></pre> <p>Here are some other ways to pad the numbers, but I guess executing <code>new array</code>,<code>join</code>,<code>slice</code> or <code>substr</code> has more impact on the performance than <code>(m&lt;10?'0'+m:m)</code>.</p> <pre><code>function padL2(a){//number or string return a+='','00'.substr(0,2-a.length)+a; } function padL(a,b,c){//string,length=2,char=0 return (new Array(b||2).join(c||0)+a).slice(-b); } </code></pre> <p><strong>Time string (HH:MM:SS.mss) to Milliseconds</strong></p> <p>This function uses 2 <code>split</code> and the array <code>a</code> is not cached.</p> <pre><code>function timeString2ms(a,b,c){// time(HH:MM:SS.mss) return c=0, a=a.split('.'), !a[1]||(c+=a[1]*1), a=a[0].split(':'),b=a.length, c+=(b==3?a[0]*3600+a[1]*60+a[2]*1:b==2?a[0]*60+a[1]*1:s=a[0]*1)*1e3, c } </code></pre> <hr> <p><strong>UPDATE</strong></p> <p>the first most important part of this function should be the performance, the second is to have a very short code. it should be a one line function. </p> <p><strong>ms2TimeString</strong> (4 updates)</p> <pre><code>function ms2TimeString(a,k,s,m,h){ return k=a%1e3, // optimized by konijn s=a/1e3%60|0, m=a/6e4%60|0, h=a/36e5%24|0, (h?(h&lt;10?'0'+h:h)+':':'')+ // optimized (m&lt;10?0:'')+m+':'+ // optimized (s&lt;10?0:'')+s+'.'+ // optimized (k&lt;100?k&lt;10?'00':0:'')+k // optimized } </code></pre> <p><strong>Description:</strong></p> <pre><code>function ms2TimeString(inputInMilliseconds,milliseconds,seconds,minutes,hours){ </code></pre> <p>The milliseconds, seconds, minutes, hours are just placeholders. They are undefined variables which I set inside the function before I need them. Sometimes they are really useful so you don't have to write multiple times <code>var</code>.</p> <pre><code> return </code></pre> <p>I start with return (another point why I don't want use <code>var</code>) as this function is meant to be a one-line-function, even if it's a long function.</p> <pre><code> milliseconds=inputInMilliseconds%1e3, </code></pre> <p>I removed the unecessary <code>|0</code>.</p> <p>The strange number <code>1e3</code> means <code>1000</code>.</p> <p><em>1e7 means that the first number is followed by 7 zeros</em></p> <pre><code> seconds=inputInMilliseconds/1e3%60|0, </code></pre> <p>To get only the seconds I need to divide the milliseconds per 1000 (so 1e3) then apply the modulo calculation and finally floor the number.</p> <p>But there is a trick. Using the bitwise operator <code>|</code> or <code>&gt;&gt;</code>, you can floor numbers up to 32bit, so numbers up to 10 decimal digits. As this function is meant to be for a a/v player that's enough. And the cool thing is that this bitwise operator is much much faster than the <code>Math.floor</code> function. </p> <pre><code> minutes=inputInMilliseconds/6e4%60|0, </code></pre> <p>Same as above, <code>ms/60000%60|0</code> gives you the seconds. You will notice the <code>,</code> as I started with <code>return</code> the comma allows me to apply some calculations before I output the final result.</p> <pre><code> hours=inputInMilliseconds/36e5%24|0, </code></pre> <p>to get the hours <code>60*60*1000</code>=<code>3600000</code>=<code>36e5</code> .....<code>Math.floor(ms/3600000%24)</code> in this case we have 24 hours max.</p> <pre><code> (hours?(hours&lt;10?'0'+hours:hours)+':':'')+ </code></pre> <p>Now if you look at the first function, I made some optimizations. As <code>hours&gt;0</code> and <code>hours</code> will give you the same value, I removed those 2 chars. If hours is bigger than 0, then it's true, else false, same as hours is 0 it will return 0 which is false or null. It works like a charm and it does not have to check with another value which in this case is 0.</p> <pre><code> (minutes&lt;10?0:'')+minutes+':'+ (seconds&lt;10?0:'')+seconds+'.'+ </code></pre> <p>Also in these two lines I optimized the code a little. As we already appending to a string, I can pass 0 as number, and don't need the <code>''</code>. I also don't need to write 3 times minutes or seconds. I saved a char, but also added performance as when compiling the var s(seconds) appears 2 times vs 3.</p> <pre><code> (milliseconds&lt;100?milliseconds&lt;10?'00':0:'')+milliseconds </code></pre> <p>I can't apply the above number trick because 00 is always 0 if interpreted as a number.</p> <pre><code>} </code></pre> <p><strong>Usage:</strong></p> <pre><code>console.log(ms2timeString(89754)); // milliseconds </code></pre> <hr> <p><strong>timeString2ms</strong> (3 updates)</p> <pre><code>function timeString2ms(a,b){// time(HH:MM:SS.mss) // optimized return a=a.split('.'), // optimized b=a[1]*1||0, // optimized a=a[0].split(':'), b+(a[2]?a[0]*3600+a[1]*60+a[2]*1:a[1]?a[0]*60+a[1]*1:a[0]*1)*1e3 // optimized } </code></pre> <p><strong>Description</strong></p> <pre><code>function timeString2ms(a,b){ </code></pre> <p>At the moment <code>a</code> is the input as a Time String <code>HH:MM:SS.mss</code> and <code>b</code> is a placeholder. I don't give special names to this 2 variables as they change the role inside the function. These are just 2 temp variables. If you prefer, I can call them <code>temp1</code> and <code>temp2</code>.</p> <pre><code> return a=a.split('.'), </code></pre> <p>Here I split the string in 2 pieces where the first is <code>HH:MM:SS</code> and the second is <code>milliseconds</code>.</p> <pre><code> b=a[1]*1||0, </code></pre> <p>If the input contains milliseconds I multiply them by one to avoid the slow <code>parseInt</code> function and set <code>b</code> the first temp variable to the milliseconds, else I set it to 0.</p> <pre><code> a=a[0].split(':'), </code></pre> <p>Here I reuse <code>a</code> which is the input string as an array where I store hours, minutes and seconds.</p> <pre><code> b+ </code></pre> <p>add my milliseconds with</p> <pre><code> (a[2]? </code></pre> <p>if the array length is 3, and so I have hours, minutes and seconds </p> <pre><code> a[0]*3600+a[1]*60+a[2]*1 </code></pre> <p>I multiply the hours with 3600 add them to minutes multiplied with 60 add seconds multiplied with 1 (to avoid <code>parseInt</code>). In this case <code>a</code> contains <code>hours</code>, <code>minutes</code>, <code>seconds</code>, <code>b</code> <code>milliseconds</code>.</p> <pre><code> :a[1]? </code></pre> <p>else if no hours. In this case <code>a</code> contains <code>minutes,seconds</code>,<code>b</code> <code>milliseconds</code></p> <pre><code> a[0]*60+a[1]*1 </code></pre> <p>minutes multiplied with 60 add seconds multiplied with 1 (to avoid <code>parseInt</code>)</p> <pre><code> : </code></pre> <p>else. In this case <code>a</code> contains only <code>seconds</code>,<code>b</code> <code>milliseconds</code></p> <pre><code> a[0]*1 </code></pre> <p>I multiplied the seconds with 1 (to avoid <code>parseInt</code>)</p> <pre><code> )*1e3 </code></pre> <p>and finally multiply everything with 1000</p> <pre><code> } </code></pre> <p><strong>Usage:</strong></p> <pre><code>console.log(timeString2ms('10:21:32.093')); // hh:mm:ss.mss console.log(timeString2ms('21:32.093')); // mm:ss.mss console.log(timeString2ms('21:32')); // mm:ss console.log(timeString2ms('32.093')); // ss.mss console.log(timeString2ms('32')); // ss console.log(timeString2ms('32467.784')); // seconds.ms console.log(timeString2ms(32467.784+'')); // seconds.ms </code></pre> <hr> <p><strong>Extra</strong></p> <p><strong>Notes</strong></p> <p>I did not use any minifier or compressor. The purpose of this code is already explained in the first lines of the post (performance and byte-saving).</p> <p>Using bitwise operators and shorthand makes this function faster in the real world (if you don't think so create your own function and show me a jsperf). If you don't understand, ask.</p> <p>No memoization.</p> <p>Executing/initializing functions inside other functions is slower.</p> <p><a href="http://jsperf.com/multiple-functions" rel="nofollow">http://jsperf.com/multiple-functions</a></p> <p>Accessing objects is slower than arrays or single vars.</p> <p><a href="http://jsperf.com/store-array-vs-obj" rel="nofollow">http://jsperf.com/store-array-vs-obj</a></p> <p>Maybe the result between every second would be more fluid, but I would see a higher performance loss when the second value changes. So in this case, I prefer some random lag that every second a fixed lag.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:37:04.233", "Id": "79008", "Score": "4", "body": "Obfuscation/minification != optimization. Your code wouldn't run any slower if you made it more readable. Also, you can use [jsperf.com](http://jsperf.com) to benchmark your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:46:10.123", "Id": "79011", "Score": "0", "body": "i don't think you can minify more this code except the ms var.btw i'm asking for tips to improve the code. i know jsperf but if i have no new ideas on how to change the code. So there is no reason to use jsperf.if you are talking about the pad functions... then yep, i have already tested ... and no... they are slower... i just added them to just to show more ways to implement the padding maybe writing it in another way could also improve the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:09:50.433", "Id": "79017", "Score": "0", "body": "At the other side ... i wanna contradict you as shorthand and bitwiser is faster than normal readable code most of the time... only in the advanced chrome and maybe firefox the compilation is done properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:18:03.467", "Id": "79018", "Score": "0", "body": "@cocco For fast code, you write it out long, and then feed it through an minifier when you go to deploy. Minifying it yourself only makes it harder for you to find algorithmic simplifications, while a minifier program has the advantage that it can minify it _well past_ the limit of comprehensibility, as well as optimize the code minification." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:21:46.180", "Id": "79020", "Score": "0", "body": "minifiers can't interprete/rewrite the code and convert math.round to bitwise, remove useless variables. They just convert it to shorthand and shorten the variable names.In the edit area is a link about minifiers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:27:42.237", "Id": "79022", "Score": "0", "body": "@cocco If you really need that sort of speed, you should be using an existing time API, because that API can implement it as an assembly routine, which is much, much faster than anything you could ever write in javascript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:28:24.147", "Id": "79023", "Score": "0", "body": "time api? new Date()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:29:39.610", "Id": "79024", "Score": "2", "body": "@cocco You are also disregarding the golden rules of optimization, which are: Don't do it, don't do it yet, and don't do it unless test results show that a particular piece of code needs it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:31:43.793", "Id": "79027", "Score": "0", "body": "what you mean with test data ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:34:27.270", "Id": "79028", "Score": "0", "body": "Looks like you are all talking about how unreadable this code is. but i'm searching for maximum performance. i could change the s to seconds,m to minutes, h to hours but i guessed h,m,s are enough to understand the function btw in the second one all variables are just temp ms variables.No concrete answers.\n\nexplain :\n\n\"Don't do it, don't do it yet, and don't do it unless test results show that a particular piece of code needs it.\"\n\nwhat has this to do with coding?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:20:58.057", "Id": "79046", "Score": "0", "body": "Looks pretty optimized to me, I can't see any faster ways of doing the operations you are doing." } ]
[ { "body": "<p>To start,</p>\n\n<p>I would like to offer an analogy; you have built a really fast car with a hood that wont open ( it's hard to maintain ), and you keep insisting that it's okay, because the car is fast. We keep telling you that you're doing it wrong.</p>\n\n<p>As for \"Don't do it, don't do it yet, and don't do it unless test results show that a particular piece of code needs it.\", the commenter is referring to <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\">Premature Optimization is the root of all evil</a>.</p>\n\n<p>For <code>function ms2TimeString(a,ms,s,m,h){// time(ms)</code></p>\n\n<ul>\n<li><p>You made your function lie about parameters, to avoid a <code>var</code> statement, this is considered a code golf trick, not production code, there would be no slowdown by declaring a <code>var</code> statement</p></li>\n<li><p><code>a</code> is an unfortunate parameter name</p></li>\n<li><p><code>ms=a%1e3|0;</code> &lt;- No need for <code>|0</code> since you are not dividing</p></li>\n<li><p><code>//display hours only if necessary</code> is out of place, you comment on this obvious line of code, but do not comment on your <code>1e3</code> numbers which do deserve a comment or the <code>|0</code> trick</p></li>\n<li><p>Other than that, I think this function is readable/understandable once you rename <code>a</code> and add a few more comments. I see no opportunities to optimize it.</p></li>\n</ul>\n\n<p>For <code>function timeString2ms(a,b,c){// time(HH:MM:SS.mss)</code></p>\n\n<ul>\n<li><p>Avoiding <code>var</code> again, not documenting well how to call this</p></li>\n<li><p><code>a</code>,<code>b</code>,<code>c</code>, you're not even trying now to make this readable, those parameter names are terrible</p></li>\n<li><p><code>!a[1]||(c+=a[1]*1)</code> &lt;- You are avoiding an <code>if</code> statement, again, I would applaud you in CodeGolf, I cringe when I see this in any other setting</p></li>\n<li><p><code>c+=(b==3?a[0]*3600+a[1]*60+a[2]*1:b==2?a[0]*60+a[1]*1:s=a[0]*1)*1e3,</code> &lt;- Wow, you just managed to write Perl in JavaScript, that's a bad thing.</p></li>\n</ul>\n\n<p>All in all, if you have a performance problem with this function on canvas, then I assume you call it more than once per second, you probably call it several times per second.</p>\n\n<p>You might want to try memoization, something like this:</p>\n\n<pre><code>function cachedMsToString(ms/*milliSeconds*/){\n\n var seconds = ms - (ms % 1000);\n ms = ms % 1000; \n //Is this similar to our last call ?\n if( cachedMsToString.seconds == seconds )\n return cachedMsToString.time + (ms&lt;100?(ms&lt;10?'00'+ms:'0'+ms):ms);\n\n /* It is different, \n set cachedMsToString.seconds, \n set cachedMsToString.time, \n return the correct value\n */\n}\n\n//Initialize the cache\ncachedMsToString.seconds = 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:27:25.800", "Id": "79215", "Score": "0", "body": "thx for your help, i added more info about everything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T21:51:44.143", "Id": "79257", "Score": "0", "body": "Looks like the post is locked now.Anyway here are some performance examples that show my decisions. http://jsperf.com/parseint-multi\nhttp://jsperf.com/bw-math\nhttp://jsperf.com/multiple-functions\nhttp://jsperf.com/store-array-vs-obj\nhttp://jsperf.com/if-short" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:11:41.903", "Id": "45403", "ParentId": "45335", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:00:29.673", "Id": "45335", "Score": "2", "Tags": [ "javascript", "performance", "strings", "datetime", "converting" ], "Title": "Milliseconds to Time string & Time string to Milliseconds" }
45335
<p>I'm currently facing a problem where I have to shift data in a multidimensional JS array in different directions, but I think the first solution I whipped up is not as efficient as it could be (some fancy math I don't know of maybe?).</p> <p>Let me explain the problem a bit better with some examples of my data.</p> <p>This is the array in question:</p> <pre><code>[1][0][1][0][1][0] [0][1][1][0][0][0] [0][0][1][0][1][1] [0][0][0][0][1][1] [0][0][1][1][0][0] [1][0][0][1][1][1] </code></pre> <p>If I shifted it to the left, it should look like this:</p> <pre><code>[1][1][1][0][0][0] [1][1][0][0][0][0] [1][1][1][0][0][0] [1][1][0][0][0][0] [1][1][0][0][0][0] [1][1][1][1][0][0] </code></pre> <p>Or down</p> <pre><code>[0][0][0][0][0][0] [0][0][0][0][0][0] [0][0][1][0][1][0] [0][0][1][0][1][1] [1][0][1][1][1][1] [1][1][1][1][1][1] </code></pre> <p>To put it simple - shift <strong>1's</strong> as <em>far</em> as possible.</p> <p>The code I wrote is fairly simple</p> <pre><code>for (w = 0; w &lt; arraySize; w++) { for (h = 0; h &lt; arraySize; h++) { tiles = $('.arrayContainer .row').eq(w).children(); if (tiles.eq(h).html() != "" &amp;&amp; tiles.eq(h - 1).html() == "" &amp;&amp; (h-1) &gt;= 0) { tiles.eq(h - 1).html(tiles.eq(h).html()); tiles.eq(h).html(""); } } } </code></pre> <p>This will shift values left-to-right by one step. <code>arraySize</code> is the variable that determines the size of the array, <code>tiles</code> gets each row of the array output.</p> <p>If I wasn't here, posting and wouldn't think this could be done better I'd create four of these structures and just live with it, but I'm pretty sure this can be done better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:55:01.493", "Id": "79080", "Score": "0", "body": "Are you always dealing with just 0s and 1s?" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>You should consider MVC, your data should live in an object you created, you should update your model, and then from your model update the UI</p></li>\n<li><p>If you dont want to do this, then you should at least find all cells and assign each cell to a 2d JS array</p>\n\n<pre><code>var tiles = [];\nfor (w = 0; w &lt; arraySize; w++) {\n tiles[w] = [];\n for (h = 0; h &lt; arraySize; h++) {\n tiles[w][h] = $('.arrayContainer .row').eq(w).children().eq(h);\n }\n}\n</code></pre>\n\n<p>Otherwise you are executing <code>$('.arrayContainer .row')</code> far too many times, and that operation takes a lot of time, then you can do your logic like this:</p>\n\n<pre><code>for (w = 0; w &lt; arraySize; w++) {\n for (h = 0; h &lt; arraySize; h++) {\n tile = tiles[w][h]\n if (tile.html() != '' &amp;&amp; tiles[w][h-1].html() == '' &amp;&amp; (h-1) &gt;= 0) {\n tiles[w][h-1].html(tile.html());\n tile.html('');\n }\n }\n}\n</code></pre>\n\n<p>You could consider assigning <code>tiles[w][h-1]</code> to a variable as well to make it more readable</p></li>\n<li><p>Consider <code>c</code> and <code>r</code> as variables ( <code>column</code> and <code>row</code> if you are feeling verbose ). Those are better names than <code>h</code>eight and <code>w</code>idth.</p></li>\n<li><p>I hope you declared <code>tiles</code> with <code>var</code> somewhere else, otherwise you have global namespace pollution.</p></li>\n<li><p>As for not having to repeat the same 2 loops for every direction, you could think about passing a columnDelta and RowDelta ( for your 2 loops, columnDelta would be -1, rowDelta would be 0 ) I am not sure it is worth it, since you only have 4 cardinal directions, up to you.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:39:23.527", "Id": "79051", "Score": "1", "body": "Thanks for all the great suggestions, they truly make sense. What about the for loops, though. Is there any way to avoid creating this structure for every direction I want the data to be shifted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:01:52.043", "Id": "79055", "Score": "0", "body": "Updated question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:26:37.347", "Id": "79322", "Score": "0", "body": "Thanks for the great answer!\nI'll stick to these suggestions." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:12:59.710", "Id": "45343", "ParentId": "45342", "Score": "2" } } ]
{ "AcceptedAnswerId": "45343", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T19:57:44.603", "Id": "45342", "Score": "3", "Tags": [ "javascript", "algorithm", "matrix" ], "Title": "Shift data in multidimensional array" }
45342
<p>I've written a small webapp in JavaScript, and am now essentially rewriting it to use RequireJS. I'm doing this partly to get more familiar with RequireJS (which I have little experience with), as well as for ease of maintaining and upgrading the app.</p> <p>I'm hoping to get feedback on whether the structure I'm looking at implementing is reasonable/useful/extensible/totally insane. I've been through the require docs, reading related SO posts and some samples on GitHub, but I'm not sure I'm totally 'getting' Require. </p> <p>If there are fundamental flaws in the logic it'd be great to get some links to resources (either JS or RequireJS specific), and to get feedback about the overall structure of the app itself. Suggestions for design patterns also very much appreciated, there's some stuff in there that feels kind of counter intuitive.</p> <p><strong>main.js</strong></p> <pre><code>require({ paths: { jquery: '../bower_components/jquery/jquery' } }, function() { 'use strict'; require(['jquery', 'app', 'reader', 'env'], function($, App, Reader, Env) { $(document).ready(function() { var app = new App( new Reader(), new Env() ); }); }) }); </code></pre> <p><strong>app.js</strong></p> <pre><code>define(function() { return function(reader, env) { this.reader = reader, this.env = env }; }); </code></pre> <p><strong>reader.js</strong> (it's an online e-reader)</p> <pre><code>define(['jquery'], function($) { return function() { this.components = [], this.firstPage = null, this.lastPage = null, this.maxFontSize = function() { return this.env.isIOS() ? 120 : 160; } }; }); </code></pre> <p><strong>env.js</strong></p> <pre><code>define(['jquery'], function($) { return function() { this.isIOS = function() { return navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; // for example. } }; }); </code></pre>
[]
[ { "body": "<p>This is honestly pretty good. I usually use <code>requirejs.config</code> to set the paths and configurations on require (it's going to grow a lot as you add things like shims, urlArgs, etc). You will also probably want to reuse it in several places. <a href=\"https://github.com/togakangaroo/Blog/blob/master/setting-up-requirejs.md\" rel=\"nofollow\">See my blog article on how I recommend doing this.</a> The general idea is that you don't use <code>data-main</code> to bootstrap things, you instead have a request for the configuration file and another to actually bootstrap the specific page of your application.</p>\n\n<p>Next, I'll ask why bother injecting <code>reader</code> and <code>env</code> manually into <code>application</code>? Injecting dependencies is what RequireJs already does.</p>\n\n<p><strong>app.js</strong></p>\n\n<pre><code>define(['reader', 'env'], function(Reader, Env) {\n return function() {\n this.reader = new Reader(),\n this.env = new Env()\n };\n});\n</code></pre>\n\n<p>Finally, a couple notes on your specific files - you probably want to name those top-level functions even when returning immediately</p>\n\n<p><strong>env.js</strong></p>\n\n<pre><code>define(['jquery'], function($) {\n return function Env() {\n ...\n };\n});\n</code></pre>\n\n<p>That both makes it clear from within what module you're in, the fact that you expect it to be used with <code>new</code>, and will generate nicer stacktraces.</p>\n\n<p>I'll also point out that - it's a matter of style but you're on CR so I consider it solicited - hardly ever is code made more bugproof or more legible by using constructor functions. <strong>reader.js</strong> could just as easily be the following and not depend on someone remembering to use <code>new</code> and always bind functions.</p>\n\n<pre><code>var env = {\n components: [],\n firstPage: null,\n lastPage: null,\n maxFontSize: function() {\n return this.env.isIOS() ? 120 : 160;\n }\n};\nreturn env;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:34:05.990", "Id": "79126", "Score": "0", "body": "hey thanks very much! injecting the deps manually was part of what was feeling strange about what i had going on in the Q. i set up the `require.config`, named the top level fns (the `console.log` looks _logical_ now) and removed constructors (`reader.js`) where superfluous. thanks also for the link!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:20:46.180", "Id": "45354", "ParentId": "45344", "Score": "2" } } ]
{ "AcceptedAnswerId": "45354", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:13:05.760", "Id": "45344", "Score": "4", "Tags": [ "javascript", "design-patterns", "require.js" ], "Title": "Structure a webapp using RequireJS" }
45344
<p>I got the following ugly code:</p> <pre><code>template &lt; class _Coeff, unsigned _nVars, typename _Expo=int, template &lt;class, class&gt; class _Map = _Map &gt; class Polynomial : boost::ring_operators&lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt; , boost::addable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, _Coeff , boost::addable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, std::pair&lt; std::array&lt;_Expo,_nVars&gt;, _Coeff &gt; , boost::subtractable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, _Coeff , boost::subtractable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, std::pair&lt; std::array&lt;_Expo,_nVars&gt;, _Coeff &gt; , boost::multipliable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, _Coeff , boost::multipliable &lt; Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;, std::pair&lt; std::array&lt;_Expo,_nVars&gt;,_Coeff &gt; &gt; &gt; &gt; &gt; &gt; &gt; &gt; { </code></pre> <p>In particular, I hate to repeat <code>Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;</code>. Is there a way to improve this syntax without using the preprocessor ? I can't manage to get any help from the <code>using</code> keyword here.</p> <p>Just for the infos: I'm writing multivariate polynomials where <code>_Coeff</code> is the class of the coefficients and the terms <code>X1^4x2^4</code> are represented as <code>std::array&lt;_Expo,_nVars&gt;</code>.</p>
[]
[ { "body": "<p>Easy, with default template arguments:</p>\n\n<pre><code>template &lt; class _Coeff,\n unsigned _nVars,\n typename _Expo=int,\n template &lt;class, class&gt; class _Map = _Map\n typename Poly = Polynomial&lt;_Coeff,_nVars,_Expo,_Map&gt;,\n typename Pair = std::pair&lt; std::array&lt;_Expo,_nVars&gt;, _Coeff &gt; &gt;\nclass Polynomial\n : boost::ring_operators&lt; Poly\n , boost::addable &lt; Poly, _Coeff\n , boost::addable &lt; Poly, Pair\n , boost::subtractable &lt; Poly, _Coeff\n , boost::subtractable &lt; Poly, Pair\n , boost::multipliable &lt; Poly, _Coeff\n , boost::multipliable &lt; Poly, Pair\n &gt; &gt; &gt; &gt; &gt; &gt; &gt; {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T07:03:37.163", "Id": "79111", "Score": "2", "body": "I don't like it that much because it expose non-sensical parameter to the user. But then I can re-hide them by a front-end using template... OK !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:05:08.863", "Id": "79122", "Score": "0", "body": "@hivert Indeed I, would also name this `Polynomial_Impl` or something, then add a template alias to this. The remaining default template arguments would go to the interface, not the implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T17:40:52.187", "Id": "142481", "Score": "0", "body": "Add a `std::enable_if` at the end to check the user did not change those extra parameters" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T23:03:15.050", "Id": "45358", "ParentId": "45345", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:03:30.390", "Id": "45345", "Score": "4", "Tags": [ "c++", "template", "boost" ], "Title": "Template with boost::operators extremely verbose and repeating" }
45345
<p>Below is some code I have written today to test out some bits I have learnt. It isn't much nor is it spectacular. Please critique and let me know what I could/should have done differently or anything I could do to improve it so far.</p> <pre><code>package easy8; import java.util.Scanner; public class song99bottles { public static void main(String[] args) { // Declare a reference variable of type song99bottles - new object song99bottles go = new song99bottles(); // calls the method "queston" for object "go". go.question(); } public void question(){ song99bottles start = new song99bottles(); String answer; System.out.println("Would you like to hear a nursery rhyme?\nPlease enter yes or no:"); Scanner input = new Scanner(System.in); answer = input.next(); if(answer.equalsIgnoreCase("yes")){ start.lyrics(); } else{ System.out.println("Bye"); } } public void lyrics() { int peeps = 10; String intro = "There were "; String intro2 = " in the bed and the little one said rollover"; String fall = "\nSo they all rolled over and 1 fell out."; String end = "And the little said 'I'm lonely'."; while (peeps &gt; 0){ System.out.println( intro + peeps + intro2 + fall); peeps--; if (peeps == 1){ System.out.println(end); return; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:31:41.330", "Id": "79125", "Score": "0", "body": "Missing \"one\". \"And the little _one_ said 'I'm lonely'.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:41:44.450", "Id": "79127", "Score": "1", "body": "According to this video the last line is \"There was one in the bed and the little one said 'I'm lonely'\" https://www.youtube.com/v/TdDypyS_5zE%26start=130%26end=138%26version=3" } ]
[ { "body": "<p>There are a number of improvements you can make, but removing the declaration for <code>peeps</code> in <code>lyrics()</code> and changing the <code>while</code> loop to a <code>for</code> loop would be a good start:</p>\n\n<pre><code>for(int peeps=10;peeps&gt;0;peeps--) {\n System.out.println( intro + peeps + intro2 + fall); \n}\nSystem.out.println(end);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:28:33.607", "Id": "45347", "ParentId": "45346", "Score": "3" } }, { "body": "<ol>\n<li>Class names should be PascalCase (<code>song99bottles -&gt; Song99Bottles</code>)</li>\n<li><p>You should indent your code or you will end up with a long code and you don't understand the various <code>{ }</code> pairs (and an horrible code!)</p>\n\n<pre><code>public class song99bottles {\npublic static void main(String[] args) {\n// Declare a reference variable of type song99bottles - new object \nsong99bottles go = new song99bottles();\n// calls the method \"queston\" for object \"go\".\ngo.question(); \n}\n// [...]\n</code></pre>\n\n<p>if you want to follow <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395\" rel=\"nofollow\">Code conventions</a>, you code should look like this</p>\n\n<pre><code>public class Song99Bottles {\n\n public static void main(String[] args) {\n // Declare a reference variable of type song99bottles - new object\n Song99Bottles go = new Song99Bottles();\n // calls the method \"queston\" for object \"go\".\n go.question();\n }\n\n // [...]\n</code></pre>\n\n<p>Personally i follow the new-line style, but you will see with time you will get \"your style\".</p>\n\n<p>i hope you understand the concept. Read <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow\">wikipedia page</a>.</p></li>\n<li><p>You should give to your variables a more descriptive name, you should understand the scope of the variable by just reading the name. (<code>song99bottles go = new song99bottles();</code> <code>go</code>? What is? a countdown? I could call it <code>song</code> (example))</p></li>\n</ol>\n\n<hr>\n\n<p>About your code:</p>\n\n<ol>\n<li><p>You create two <code>song99bottles</code> objects, why? One inside <code>main</code> and one inside <code>question()</code>. You should move <code>question</code> code inside <code>main</code> because <code>song99bottles</code> class should just play the song, the main will take care if the user want or not to play the song. Then in your <code>main</code>, just call <code>go.lyrics();</code></p></li>\n<li><p>About <code>lyrics()</code> code, see Roger answer.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:54:41.547", "Id": "79062", "Score": "0", "body": "Java [Code Style Conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395) require that the opening brace for a compound statement goes at the *end* of the line, not on a new line. Your `should be` example code is wrong...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:57:41.207", "Id": "79064", "Score": "1", "body": "I will edit with that. But i should admit i always follow the \"new line\" style, i thought the code more clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:02:29.837", "Id": "79066", "Score": "0", "body": "I understand, and I have worked with both. Two comments though... if you are producing 'example code' it should follow conventions.... and, with the `{` on the next line it looks like C#. Also, by the way, empty-line before method declarations ;-). Your answer is good, it already has my +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:08:12.713", "Id": "79069", "Score": "0", "body": "About empty-line, yes.. i think i deleted the line by error... Fixed thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:08:32.827", "Id": "79070", "Score": "0", "body": "Might as well update my answer too..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T03:42:32.367", "Id": "79105", "Score": "0", "body": "Actually, it appears that this indentation is missing because tabs were used instead of spaces. I suppose that can still be fixed (I was about to), but I didn't want to invalidate your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T05:28:43.457", "Id": "79109", "Score": "0", "body": "When I writed the answer I had problems to let work code block with numeric list so I think I just do some errors here (spaces problems etc.) Today I will try to fix it by myself.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:25:08.373", "Id": "79155", "Score": "0", "body": "`Class names should be camel case` - I think you mean Pascal case. song99bottles *is* camel case" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:31:37.317", "Id": "45348", "ParentId": "45346", "Score": "15" } }, { "body": "<p>Taking Roger's answer as a starting point, you can also only use one string in the <code>lyrics()</code> function, because you always use <code>intro2</code> before <code>fall</code>. If you use one string, you save an allocation and concatenation.</p>\n\n<pre><code>String intro = \"There were \";\nString fall = \" in the bed and the little one said rollover\"\n + System.lineSeparator()\n + \"So they all rolled over and 1 fell out.\";\nString end = \"And the little said 'I'm lonely'.\";\n\nfor(int peeps = 10; peeps &gt; 0; peeps--){\n System.out.println(intro + peeps + fall);\n}\nSystem.out.println(end);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:55:20.303", "Id": "79063", "Score": "0", "body": "... I don't even know what to say... Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T01:56:16.640", "Id": "79098", "Score": "0", "body": "You might want to get the line break sequence from the System object instead of hard coding a newline in the middle of the 'fall' string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T02:46:19.913", "Id": "79101", "Score": "0", "body": "@atk Like this? It's kinda verbose, but it might save a cross platform headache or two." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:39:05.747", "Id": "45350", "ParentId": "45346", "Score": "10" } }, { "body": "<p>Suggestion to code</p>\n\n<ol>\n<li>Do not create Song99bottles twice, from question() you can call lyrics()</li>\n<li>Do not + strings, it creates an unbelievable overhead of strings in the stack (memory). Use a string formatter String.format(\"format %d\", integer)</li>\n<li>Do not use comments unless the really matter. Comments are a sign of bad names and too few funtions, see this <a href=\"http://ptgmedia.pearsoncmg.com/images/9780132350884/samplepages/0132350882_Sample.pdf\" rel=\"nofollow\">http://ptgmedia.pearsoncmg.com/images/9780132350884/samplepages/0132350882_Sample.pdf</a></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:08:35.537", "Id": "45378", "ParentId": "45346", "Score": "3" } }, { "body": "<p>In addition to the other good advice I see here, I would rename your lyrics method to imply exactly what it does. For example <code>printLyrics()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:19:24.910", "Id": "45404", "ParentId": "45346", "Score": "1" } }, { "body": "<p>The only thing I can think to add to others' is that the comments in the <code>main</code> method are superfluous.</p>\n\n<pre><code>// Declare a reference variable of type song99bottles - new object \nsong99bottles go = new song99bottles();\n</code></pre>\n\n<p>It's obvious you're declaring a reference here. You're not adding much by saying it.</p>\n\n<pre><code>// calls the method \"queston\" for object \"go\".\ngo.question();\n</code></pre>\n\n<p>This is worse. This is like saying <code>x = 10; // Sets x to 10</code>. If you're set on leaving some comments it'd be more beneficial to leave some in the other methods with more logic involved like the <code>lyrics</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-19T00:24:38.950", "Id": "91121", "ParentId": "45346", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:18:31.443", "Id": "45346", "Score": "8", "Tags": [ "java", "beginner" ], "Title": "And the little one said \"Roll over\"" }
45346
<p>I am a beginner in C++ and learning from textbook. I find it hard to jump into oops concepts as I have used C a lot. Here is an interview question I came across:</p> <blockquote> <p>Problem Statement </p> <p>Our marketing department has just negotiated a deal with several local merchants that will allow us to offer exclusive discounts on various products to our top customers every day. The catch is that we can only offer each product to one customer and we may only offer one product to each customer. </p> <p>Each day we will get the list of products that are eligible for these special discounts. We then have to decide which products to offer to which of our customers. Fortunately, our team of highly skilled statisticians has developed an amazing mathematical model for determining how likely a given customer is to buy an offered product by calculating what we call the "suitability score" (SS). The top-secret algorithm to calculate the SS between a customer and a product is this: </p> <ol> <li>If the number of letters in the product's name is even then the SS is the number of vowels (a, e, i, o, u, y) in the customer's name multiplied by 1.5. </li> <li>If the number of letters in the product's name is odd then the SS is the number of consonants in the customer's name. </li> <li>If the number of letters in the product's name shares any common factors (besides 1) with the number of letters in the customer's name then the SS is multiplied by 1.5. </li> </ol> <p>Your task is to implement a program that assigns each customer a product to be offered in a way that maximizes the combined total SS across all of the chosen offers. Note that there may be a different number of products and customers. You may include code from external libraries as long as you cite the source. INPUT SAMPLE:</p> <p>Your program should accept as its only argument a path to a file. Each line in this file is one test case. Each test case will be a comma delimited set of customer names followed by a semicolon and then a comma delimited set of product names. Assume the input file is ASCII encoded. For example (NOTE: The example below has 3 test cases): </p> <p>Jack Abraham,John Evans,Ted Dziuba;iPad 2 - 4-pack,Girl Scouts Thin Mints,Nerf Crossbow</p> <p>Jeffery Lebowski,Walter Sobchak,Theodore Donald Kerabatsos,Peter Gibbons,Michael Bolton,Samir Nagheenanajar;Half &amp; Half,Colt M1911A1,16lb bowling ball,Red Swingline Stapler,Printer paper,Vibe Magazine Subscriptions - 40 pack</p> <p>Jareau Wade,Rob Eroh,Mahmoud Abdelkader,Wenyi Cai,Justin Van Winkle,Gabriel Sinkin,Aaron Adelson;Batman No. 1,Football - Official Size,Bass Amplifying Headphones,Elephant food - 1024 lbs,Three Wolf One Moon T-shirt,Dom Perignon 2000 Vintage</p> </blockquote> <h2>Known Bug</h2> <ol> <li>I don't know how to handle the last input sample. It has 7 customer names and 6 products. I'm confused on how to handle that. What would be a good approach?</li> <li>I know this code can be easily done in Python or other languages, but I am trying to learn C++ here.</li> </ol> <h3>Questions</h3> <ol> <li>Is vector a good way to deal with this data? If not, what else works and why?</li> <li>I am using too many "for" loops which is a bad thing (I guess). Any other approach to eliminating them?</li> </ol> <p>General code review/ suggestions/ creative criticism would be cool.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cstdlib&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #define DEBUG false //================================= MAIN ROUTINE AT END //================================= int getGCD(int a, int b) { if(b == 0) return a; else return getGCD( b , a % b ); } double find_common(int a, int b) // basically a GCD finder { int gcd; gcd = getGCD ( a , b ); if (gcd &gt; 1) return 1.5; else return 1.0; } void find_let_vow_con(std::string s, int&amp; l, int&amp; v, int&amp; c) { char chars[] = "aAeEiIoOuUyY"; v = 0; //Y is a vowel and a consonant (looked up in the dicitionary :) l = s.size(); for(int i = 0; i&lt; sizeof(chars); i++) { for(int j = 0; j &lt; l; j++ ) { if(s[i]== chars[j]) v++; } } c = l - v; //consonants = num_letters in string - num_vowels std::cout &lt;&lt; "string = " &lt;&lt; s &lt;&lt; std::endl; std::cout &lt;&lt; "num_letters = " &lt;&lt; l &lt;&lt; std::endl; std::cout &lt;&lt; "num_vowels = " &lt;&lt; v &lt;&lt; std::endl; std::cout &lt;&lt; "num_consonants = " &lt;&lt; c &lt;&lt; std::endl; } void strip_string(std::string&amp; s) { char chars[] = "\n\r.-_1234567890 "; for (unsigned int i = 0; i &lt; sizeof(chars); ++i) { // you need include &lt;algorithm&gt; to use general algorithms like std::remove() s.erase (std::remove(s.begin(), s.end(), chars[i]), s.end()); } } void comma_seprate(std::string s, std::vector &lt; std::vector&lt;std::string&gt; &gt;&amp; a , int i) { std::istringstream ss(s); std::string token; //s.resize(i); std::vector&lt;std::string&gt; n; int j = 0; while(std::getline(ss, token, ',')) { //n.push_back(token); a.push_back(std::vector&lt;std::string&gt;()); a[i].push_back(token); std::cout &lt;&lt; token &lt;&lt; std::endl; j++; } } void split_string( std::string s, std::vector&lt;std::string&gt;&amp; v, std::vector&lt;std::string&gt;&amp; u ) { std::string delimiter = ";"; v.push_back (s.substr(0, s.find(delimiter))); u.push_back (s.substr(s.find(delimiter)+1,s.size())); } int main ( int argc, char** argv ) { //variable for file name std::string filename; //error handling for invalid argument size if ( argc &gt; 2 || argc &lt; 2 ) { std::cerr &lt;&lt;"filename missing! Usage: " &lt;&lt; argv[0] &lt;&lt; " &lt;input_filename&gt;"&lt;&lt; std::endl; return EXIT_FAILURE; } //========================================================================= //Using C style debugging : Any other way to do this in c++? #ifdef DEBUG std::cout &lt;&lt; "filename :"&lt;&lt;filename &lt;&lt; "\t num_arguments: " &lt;&lt; argc &lt;&lt; std::endl; #endif //========================================================================= //opening the file for reading std::ifstream in(argv[1]); std::vector&lt;std::string&gt; line_vec; std::string temp_line; int line_count = 0; while(std::getline(in,temp_line)) { line_count++; //Ignores any empty lines in the input file if(temp_line.empty()) continue; line_vec.push_back(temp_line); } //========================================================================= #ifdef DEBUG std::cout &lt;&lt;"\nPrinting out contents of the line_vec" &lt;&lt;std::endl; for (int i=0; i&lt;line_vec.size();i++){ std::cout &lt;&lt; line_vec[i] &lt;&lt; std::endl; } std::cout &lt;&lt; "The size of the line_vector is : " &lt;&lt; line_vec.size() &lt;&lt; std::endl; #endif //========================================================================= //Now splitting line by semicolon for customer names and product name seperation std::vector&lt;std::string&gt; customer_list; std::vector&lt;std::string&gt; product_list; for (int i=0; i&lt;line_vec.size();i++) { split_string(line_vec[i], customer_list, product_list); } #ifdef DEBUG std::cout &lt;&lt;"=======================================================================" &lt;&lt;std::endl; std::cout &lt;&lt;"\nPrinting out contents of the customer_list " &lt;&lt;std::endl; std::cout &lt;&lt;"=======================================================================" &lt;&lt;std::endl; for (int i=0; i&lt;customer_list.size();i++){ std::cout &lt;&lt; customer_list[i] &lt;&lt; "\n\n" &lt;&lt; std::endl; } std::cout &lt;&lt; "The size of the customer_list vector is : " &lt;&lt; customer_list.size() &lt;&lt; std::endl; std::cout &lt;&lt;"=======================================================================" &lt;&lt;std::endl; std::cout &lt;&lt;"\nPrinting out contents of the product_list " &lt;&lt;std::endl; std::cout &lt;&lt;"=======================================================================" &lt;&lt;std::endl; for (int i=0; i&lt;product_list.size();i++){ std::cout &lt;&lt; product_list[i] &lt;&lt; "\n\n" &lt;&lt; std::endl; } std::cout &lt;&lt; "The size of the line_vector vector is : " &lt;&lt; product_list.size() &lt;&lt; std::endl; #endif //comma seprating the string to get a list of customer names and product names std::vector &lt; std::vector &lt; std::string &gt; &gt; customer_name; std::vector &lt; std::vector &lt; std::string &gt; &gt; product_name; for(int i =0; i&lt; customer_list.size(); i++) { comma_seprate(customer_list[i],customer_name,i); comma_seprate(product_list[i],product_name,i); } // #ifdef DEBUG std::cout &lt;&lt; customer_name[0][0]&lt;&lt;std::endl; std::cout &lt;&lt; product_name[0][0]&lt;&lt;std::endl; #endif //strip strings with special characters so only letters remain std::string strip_this; for(int i =0; i&lt;customer_name.size();i++) { for(int j = 0;j&lt;customer_name[i].size();j++) { strip_this = customer_name[i][j]; strip_string(strip_this); customer_name[i][j] = strip_this; #ifdef DEBUG std::cout &lt;&lt; strip_this &lt;&lt; std::endl; #endif } } for(int i =0; i&lt;product_name.size();i++) { for(int j = 0;j&lt;product_name[i].size();j++) { strip_this = product_name[i][j]; strip_string(strip_this); product_name[i][j] = strip_this; #ifdef DEBUG std::cout &lt;&lt; strip_this &lt;&lt; std::endl; #endif } } double ss = 0,multiplier; //Odd or Even /* 1. If the number of letters in the product's name is even then the SS is the number of vowels (a, e, i, o, u, y) in the customer's name multiplied by 1.5. 2. If the number of letters in the product's name is odd then the SS is the number of consonants in the customer's name. 3. If the number of letters in the product's name shares any common factors (besides 1) with the number of letters in the customer's name then the SS is multiplied by 1.5. */ int cnum_letters,cnum_vowels,cnum_consonants; //number of letters in customer name, vowels and consonants int pnum_letters,pnum_vowels,pnum_consonants; //number of letters in product name, vowels and consonants for(int i =0; i&lt;customer_name.size();i++) { for(int j = 0;j&lt;customer_name[i].size();j++) { find_let_vow_con(customer_name[i][j],cnum_letters,cnum_vowels,cnum_consonants); find_let_vow_con(product_name[i][j],pnum_letters,pnum_vowels,pnum_consonants); multiplier = find_common( cnum_letters, product_name[i][j].size() ); if( pnum_letters % 2 == 1) //odd { ss += cnum_vowels * 1.5; } else //even { ss += cnum_consonants; } ss = ss * multiplier; } std::cout &lt;&lt; ss &lt;&lt; std::endl; ss = 0.0; } /* for(int i =0; i&lt;product_name.size();i++) { for(int j = 0;j&lt;product_name[i].size();j++) { find_let_vow_con(product_name[i][j],pnum_letters,pnum_vowels,pnum_consonants); } } */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:01:40.480", "Id": "79065", "Score": "1", "body": "Sadly, you asked near the end of the day when I am all out of votes... :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:30:57.937", "Id": "79073", "Score": "0", "body": "@syb0rg Ah! no problem mate :) ther's always another day :) @Jamal♦ Thank you for the edit once again :)" } ]
[ { "body": "<p>Reading a unit test:</p>\n\n<blockquote>\n <p>Jareau Wade,Rob Eroh,Mahmoud Abdelkader,Wenyi Cai,Justin Van Winkle,Gabriel Sinkin,Aaron Adelson;Batman No. 1,Football - Official Size,Bass Amplifying Headphones,Elephant food - 1024 lbs,Three Wolf One Moon T-shirt,Dom Perignon 2000 Vintage</p>\n</blockquote>\n\n<pre><code>// Utility class that reads ',' seprated words from a stream.\n// Also automatically converts to std::string when needed.\nstruct ItemInList\n{\n std::string itemValue;\n operator std::string {return itemValue;}\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; s, ItemInList&amp; value)\n {\n return std::getline(s, value.itemValue, ',');\n }\n};\n\n///// STUFF\n\nstd::ifstream file(&lt;fileName&gt;);\n\nstd::string allCustomers;\nstd::getline(file, allCustomers, ';'); // Reads upto ';' puts the content into `allCustomers`\nstd::stringstream allCustomersStr(allCustomers);// Convert the string into a stream\n\n// Iterate over the stream. Copy the values into the vector.\nstd::vector&lt;std::string&gt; customerVec(std::istream_iterator&lt;ItemInList&gt;(allCustomersStr),\n std::istream_iterator&lt;ItemInList&gt;());\n\n\n\nstd::string allProducts;\nstd::getline(file, allProducts);\nstd::stringstream allProductsStr(allProducts);\nstd::vector&lt;std::string&gt; productVec(std::istream_iterator&lt;ItemInList&gt;(allProductsStr),\n std::istream_iterator&lt;ItemInList&gt;());\n</code></pre>\n\n<h3>EDIT 1:</h3>\n\n<p>Same thing applies to stripping things</p>\n\n<pre><code>struct Strip\n{\n // Defining the method `operator()` means that objects of this type\n // Can be called like functions.\n //\n // Strip stripper;\n // std::cout &lt;&lt; stripper(\"String with 56686868 Bad char\") &lt;&lt; \"\\n\";\n //\n // This is called a functor (a function like object).\n std::string operator()(std::string value) const\n {\n // remove bad characters.\n // \n return value;\n }\n\n // So why do this over a function.\n // It turns out this is much easier for the compiler to optimize.\n //\n // But this technique is really a closure in disguise.\n // A closure is a function with captured state. Now this particular\n // one does not capture state but by adding some member variables\n // you can save information each time it is called and that \n // information can be used on subsequent calls.\n};\n\nstd::transform(std::begin(product_name), std::end(product_name), // Src\n std::begin(product_name), // Dst (same as src\n Strip()); // Action create strip object.\n</code></pre>\n\n<p>Of course this can be done in a single line with C++11 and lambdas.</p>\n\n<pre><code>std::transform(std::begin(product_name), std::end(product_name), // Src\n std::begin(product_name), // Dst (same as src\n [](std::string value){\n // remove bad characters. The lambda declaration\n // Basically creates an anonymous functor\n return value; // behind the scenes.\n\n});\n</code></pre>\n\n<p>Which technique to use is still a matter of debate. If the operation is common (by common I mean easy to understand and you can tell what it does by its name without looking it up) and you think it can be re-used then I would use a functor. If it is a on-off and short i would use a lambda. Everything else will depnd on how easy it is to read in the context.</p>\n\n<h3>Edit 2</h3>\n\n<p>Copying arrays/vectors to the output:</p>\n\n<pre><code> for (int i=0; i&lt;product_list.size();i++){\n std::cout &lt;&lt; product_list[i] &lt;&lt; \"\\n\\n\" &lt;&lt; std::endl;\n</code></pre>\n\n<p>Can be greatly simplified. using the above techniques.</p>\n\n<pre><code>std::copy(std::begin(product_list), std::end(product_list),\n std::ostream_iterator&lt;std::string&gt;(std::cout, \"\\n\\n\\n\"));\n // ^^^^^^^^^^^\n</code></pre>\n\n<p>Here simply printing the string. But by changing std::string here I can modify how the output is printed. Thus encapsulating and changing the printing behavior.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:53:25.837", "Id": "79077", "Score": "0", "body": "Very peculiar way to use a structure .. haven’t come across anything like this before, confuses me a bit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T14:58:25.467", "Id": "79173", "Score": "1", "body": "You should read my other answers then. This is very common technique in C++. You define some small piece of functionality in a class (same as a struct) then use that as the control over a generic function. Though in C++11 lambdas are becoming very popular (this allows the code to be defined inline (but this is a technique I am still learning))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:02:30.660", "Id": "79175", "Score": "1", "body": "Anyway. If you see a loop. See if you can eliminate it with an algorithm that uses an iterator. For streams this means using `istream_iterator` or `ostream_iterator` for other containers `std::begin()` and `std::end()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:49:50.167", "Id": "79240", "Score": "0", "body": "Wow! gr8 info Edit2 method is so much more readable and way cooler than a for loop :P . I am still unclear (one Edit 0 & 1)as to how operator overloading(that's what i assume that is , if i am wrong please correct me ) works and i need to read on that i guess to understand the structs you have created. Also how would you handle the last case where (number_of_customers) != (number_of_products) .. i.e. Aron Adelson has no product pair. Program generates a seg-fault if the pairs are not complete. ignore the last one customer ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:08:05.507", "Id": "79262", "Score": "1", "body": "Technically it would be operator overloading. But you will get better search results if you search for `functor`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:45:52.173", "Id": "45355", "ParentId": "45351", "Score": "3" } }, { "body": "<pre><code>#define DEBUG false\n</code></pre>\n\n<p>This strikes me as a poor idea. Your code depends only on whether <code>DEBUG</code> is defined or not. As it stands, it looks rather like you're trying to say: \"Don't include the debugging code\", but in fact the opposite is actually true. I'd either define DEBUG to <code>true</code> (or 1), or not define it at all.</p>\n\n<pre><code>//=================================\n MAIN ROUTINE AT END \n//=================================\n</code></pre>\n\n<p>I'm a bit uncertain how you managed to get this to compile at all. It shouldn't, since the <code>MAIN ROUTINE AT END</code> part isn't in a comment (or maybe it's something you edited in while posting--hard to be sure).</p>\n\n<pre><code>void find_let_vow_con(std::string s, int&amp; l, int&amp; v, int&amp; c)\n{\n char chars[] = \"aAeEiIoOuUyY\";\n v = 0; \n //Y is a vowel and a consonant (looked up in the dicitionary :)\n l = s.size();\n for(int i = 0; i&lt; sizeof(chars); i++)\n {\n for(int j = 0; j &lt; l; j++ )\n { \n if(s[i]== chars[j])\n v++;\n }\n }\n c = l - v; //consonants = num_letters in string - num_vowels\n std::cout &lt;&lt; \"string = \" &lt;&lt; s &lt;&lt; std::endl;\n std::cout &lt;&lt; \"num_letters = \" &lt;&lt; l &lt;&lt; std::endl;\n std::cout &lt;&lt; \"num_vowels = \" &lt;&lt; v &lt;&lt; std::endl;\n std::cout &lt;&lt; \"num_consonants = \" &lt;&lt; c &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>I think I'd count the vowels using something like <code>std::count_if</code>:</p>\n\n<pre><code>static const std::string vowels = \"aAeEiIoOuUyY\";\n\nint num_vowels = std::count_if(s.begin(), s.end(), \n [](char ch) { return vowels.find(ch) != std::string::npos; });\n</code></pre>\n\n<p>That may or may not be noticeably faster, but (IMO) it's a lot more convenient and readable.</p>\n\n<pre><code>void comma_seprate(std::string s, std::vector &lt; std::vector&lt;std::string&gt; &gt;&amp; a , int i)\n{\n std::istringstream ss(s);\n std::string token;\n //s.resize(i);\n std::vector&lt;std::string&gt; n;\n int j = 0;\n\n while(std::getline(ss, token, ','))\n {\n //n.push_back(token);\n a.push_back(std::vector&lt;std::string&gt;());\n a[i].push_back(token);\n std::cout &lt;&lt; token &lt;&lt; std::endl;\n j++;\n }\n</code></pre>\n\n<p>I'm not <em>sure</em>, but I suspect this isn't doing what you intended. You're adding strings to <code>a[i]</code>, but incrementing <code>j</code> (and never using it). At a guess, you may have intended to do something like <code>a[j].push_back(token);</code>?</p>\n\n<p>In any case, I think @Loki's suggestion is much better; instead of trying to fix the details here, I'd try to start with something simpler and cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:35:40.903", "Id": "79237", "Score": "0", "body": "I gathered the debug method was poorly written. Also i dont know why i put the \"false\" after the debug. Yes! i commented stuff while posting which might have broken things :( . count_if that is very COOL .. definitely something new to learn. Actually the j was for something else .. now i just use it to gather a count. The motive here was to push a empty vector first so i could created 2nd dimension members of the 2D vectr and assign strings. @Jerry what do you think was vector a good choice for this program, in terms of data structures that can be used for this problem?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T04:20:44.843", "Id": "45367", "ParentId": "45351", "Score": "3" } } ]
{ "AcceptedAnswerId": "45355", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T21:49:36.587", "Id": "45351", "Score": "5", "Tags": [ "c++", "beginner", "strings", "interview-questions", "vectors" ], "Title": "Calculate Suitability Score program" }
45351
<p>I found out that in Visual Studio 2012, it is possible to create project of SFML easily with a template. I am not an experienced C# programmer. Hence I wanted to implement a physics component just for practice purposes.</p> <p><code>PhysicsManager</code> Class contains all the physical objects:</p> <pre><code>public sealed class PhysicsManager { // Thread-Safe Singleton Pattern Definition private static volatile PhysicsManager instance = new PhysicsManager(); private static object syncRoot = new Object(); private PhysicsManager() { } public static PhysicsManager Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new PhysicsManager(); } } return instance; } } /////////////////////////////////////////////// private List&lt;RigidObject&gt; physicsObjects = new List&lt;RigidObject&gt;(); private double _environmentFriction = 0.6F; public double EnvironmentFriction { get { return this._environmentFriction; } set { this._environmentFriction = value; RigidObject.friction = value; } } public void AddRigidObject(RigidObject obj) { physicsObjects.Add(obj); } public void RemoveRigidObject(RigidObject obj) { physicsObjects.Remove(obj); } public void Update() { foreach(var rigit in physicsObjects) { rigit.UpdatePhysics(); } // TODO: Collision Detection and Response (Should be refactored into a separate class). for (int n = 0; n &lt; physicsObjects.Count; ++n) { RigidObject r = physicsObjects[n]; for (int m = n+1; m &lt; physicsObjects.Count; ++m) { RigidObject o = physicsObjects[m]; if (r.isCollisionWith(o)) { r.HandleCollision(); o.HandleCollision(); } } } } } </code></pre> <p><code>RigidObject</code> Abstract Class where the friction, force, and movement of physical objects are implemented:</p> <pre><code>abstract public class RigidObject { // Environmental Friction static internal double friction = 0.6F; private double forceX = 0; private double forceY = 0; private double accelerationX = 0; private double accelerationY = 0; protected double velocityX = 0; protected double velocityY = 0; protected Vector2f Position = new Vector2f(0,0); protected Vector2f prevPosition = new Vector2f(0, 0); private double _mass = 10F; public double Mass { get { return this._mass; } set { this._mass = value; } } public void AddForce(double X, double Y) { forceX = forceX + X; forceY = forceY + Y; } internal void UpdatePhysics() { double frictionX = 0; double frictionY = 0; // Adjust friction according to velocity if (velocityX &gt; 0) frictionX = friction; else if (velocityX &lt; 0) frictionX = -friction; else frictionX = 0; // velocityX == 0 if (velocityY &gt; 0) frictionY = friction; else if (velocityY &lt; 0) frictionY = -friction; else frictionY = 0; // velocityY == 0 // Environment Friction effects forces on rigid body forceX = forceX - frictionX; forceY = forceY - frictionY; accelerationX = forceX / _mass; accelerationY = forceY / _mass; velocityX = velocityX + accelerationX; velocityY = velocityY + accelerationY; // Saves the previous position prevPosition = Position; // Move the rigid body according to velocity Position = new Vector2f(Position.X + (float)velocityX, Position.Y + (float)velocityY); DelegatePosition(Position); // Reset Forces forceX = 0; forceY = 0; } protected void Move(float PosX, float PosY) { Position = new Vector2f(Position.X + PosX, Position.Y + PosY); DelegatePosition(Position); } protected void MoveTo(Vector2f pos) { Position = pos; DelegatePosition(Position); } abstract protected void DelegatePosition(Vector2f Pos); internal Boolean isCollisionWith(RigidObject Obj) { if (Obj.GetType() == typeof(RigidCircle)) return isCollisionWith(Obj as RigidCircle); return false; } abstract internal Boolean isCollisionWith(RigidCircle Obj); abstract internal void HandleCollision(); } </code></pre> <p><code>RigidCircle</code> Class inherits <code>RigidObject</code> and contains <code>CircleShape</code> (class of SFML):</p> <pre><code>public class RigidCircle : RigidObject { private CircleShape _baseShape; public Color FillColor { get { return _baseShape.FillColor; } set { _baseShape.FillColor = value; } } public RigidCircle(float PosX, float PosY, double mass, float radius) { _baseShape = new CircleShape(radius); Position = new Vector2f(PosX - radius, PosY - radius); _baseShape.Position = Position; } public CircleShape getShape() { return _baseShape; } public void SetPointCount(uint limit) { _baseShape.SetPointCount(limit); } protected override void DelegatePosition(Vector2f Pos) { _baseShape.Position = Pos; } internal override Boolean isCollisionWith(RigidCircle Obj) { // TODO: Needs restructuring (SFML Position means top-left corner, we needed center of circles) Vector2f distanceVec = Obj._baseShape.Position - _baseShape.Position; float radiusDiff = Obj._baseShape.Radius - _baseShape.Radius; distanceVec = distanceVec + new Vector2f(radiusDiff, radiusDiff); double distance = distanceVec.X * distanceVec.X + distanceVec.Y * distanceVec.Y; double totalRadius = _baseShape.Radius + Obj._baseShape.Radius; totalRadius = totalRadius * totalRadius; return (distance &lt; totalRadius)? true : false; } internal override void HandleCollision() { Position = prevPosition; _baseShape.Position = prevPosition; velocityX = -velocityX; velocityY = -velocityY; } } </code></pre> <p>Program where the main loop is implemented:</p> <pre><code>public static class Program { private static readonly Color CornflowerBlue = new Color(100, 149, 237); private static PhysicsManager Physics = PhysicsManager.Instance; public static void Main(string[] args) { ContextSettings settings = new ContextSettings(); settings.AntialiasingLevel = 4; RenderWindow window = new RenderWindow(new VideoMode(1280, 720), "SFML Window", Styles.Default, settings); window.Closed += (sender, eventArgs) =&gt; window.Close(); window.SetFramerateLimit(24); Physics.EnvironmentFriction = 0.4F; // Scene Setup float radiusM = 80.0F; Vector2f Pos = window.GetView().Size / 2; RigidCircle MainCircle = new RigidCircle(radiusM, radiusM, 2.5F, radiusM); MainCircle.FillColor = new Color(100, 250, 50); MainCircle.SetPointCount(30); float radiusS = 50.0F; RigidCircle StaticCircle = new RigidCircle(Pos.X, Pos.Y, 2.5F, radiusS); StaticCircle.FillColor = new Color(50, 50, 50); StaticCircle.SetPointCount(25); Physics.AddRigidObject(StaticCircle); Physics.AddRigidObject(MainCircle); while (window.IsOpen()) { window.DispatchEvents(); // TODO: Insert Update Code Here if (Keyboard.IsKeyPressed(Keyboard.Key.Down)) MainCircle.AddForce(0, 1.5F); if (Keyboard.IsKeyPressed(Keyboard.Key.Up)) MainCircle.AddForce(0, -1.5F); if (Keyboard.IsKeyPressed(Keyboard.Key.Right)) MainCircle.AddForce(1.5F, 0); if (Keyboard.IsKeyPressed(Keyboard.Key.Left)) MainCircle.AddForce(-1.5F, 0); Physics.Update(); window.Clear(CornflowerBlue); // TODO: Insert Draw Code Here window.Draw(StaticCircle.getShape()); window.Draw(MainCircle.getShape()); window.Display(); } } } </code></pre> <p>This runs correctly as one big green circle that can be controlled by arrow keys and a small gray circle that has static position.</p> <p>My questions are:</p> <ol> <li><p>In one of my classes I wanted to inherit from <code>CircleShape</code> but I couldn't since the class inherits another class (abstract), so I decided to contain a <code>CircleShape</code>. But it doesn't feel right in terms of software design. Is there a better way to design <code>RigidObject</code>, <code>RigidCircle</code> classes hence I don't need to write all methods and delegate them to <code>CircleShape</code> object inside <code>RigidCircle</code>?</p></li> <li><p>Is there a neater way to implement Collision Detection and Response so such that it will allow me to add more rigid classes derived from <code>RigidObject</code> and customize the collision response? (For example having a default response for each concrete class but it will allow to customize behavior for each object easily.)</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:46:30.557", "Id": "79074", "Score": "3", "body": "You should be able to simply return the instance on your singleton. Since you initialize it where you declare it, it should never be null. see http://www.yoda.arachsys.com/csharp/singleton.html and http://codereview.stackexchange.com/questions/79/implementing-a-singleton-pattern-in-c" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:03:16.770", "Id": "79113", "Score": "0", "body": "@hatchet, you are right. thank you for pointing out" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T03:20:28.787", "Id": "79515", "Score": "4", "body": "@hatchet if you fleshed that comment a bit, it would make a nice answer. CR answers can address any part, or aspect of the code. If you can make a comment and expand on it and relate it to the OP, then you can probably write an excellent CR answer ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T14:40:36.093", "Id": "81328", "Score": "0", "body": "I would love to see this in action, I would love to debug it as it runs. I am not familiar with SFML. I don't have my game code here otherwise I would compare my collision detection to what you have {it's been a while since I coded it}." } ]
[ { "body": "<p>for this little bit of code here</p>\n\n<pre><code>// TODO: Insert Update Code Here\nif (Keyboard.IsKeyPressed(Keyboard.Key.Down))\n MainCircle.AddForce(0, 1.5F);\nif (Keyboard.IsKeyPressed(Keyboard.Key.Up))\n MainCircle.AddForce(0, -1.5F);\nif (Keyboard.IsKeyPressed(Keyboard.Key.Right))\n MainCircle.AddForce(1.5F, 0);\nif (Keyboard.IsKeyPressed(Keyboard.Key.Left))\n MainCircle.AddForce(-1.5F, 0);\n</code></pre>\n\n<p>I was thinking that you might be able to use a case statement here instead of all these if statements.</p>\n\n<p>it has been a while since I have used the Keyboard Methods. but I think it would be better for maintenance if you used a <code>Switch</code> then you would be able to add other keys if you wanted to.</p>\n\n<p>this might take creating a method or function that will capture the KeyPressed Event for any Key on the keyboard and then return the key that was pressed. this would allow you to use it in a switch statement, which would make this bit of code much more maintainable.</p>\n\n<hr>\n\n<p>I assume that your <code>.AddForce(x,y)</code> is a really asking for a vector (at least that is what it would be in XNA I think)</p>\n\n<p>These look like you magic numbers, I would probably create some variables to hold these <code>up</code>, <code>down</code>, <code>left</code>, <code>right</code> numbers/Vectors/Force values, then you know which goes where and it would probably be easier to maintain.</p>\n\n<p>If you did it like this you would probably only need two variables: <code>up</code>, <code>right</code> then when you want the down value, you just add a negative, same with left value. At least I think it should work that way.</p>\n\n<hr>\n\n<p>I know that a lot of this review is telling you to <code>\"do more now to make it easier later\"</code>, but I think it is important, especially in a game like this, these variables could be at a higher scope so that you can use them (<code>up</code>,<code>down</code>,<code>right</code>,<code>left</code>) anywhere in your code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T20:53:49.940", "Id": "82343", "Score": "0", "body": "thank you for your answer. Do you think is it possible to use switch statement even if I want to catch multiple keys pressed simultaneously?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T21:05:50.560", "Id": "82344", "Score": "1", "body": "after I thought about it a bit and talked to some other Reviewers, I don't think it would be a good idea to try a switch statement out. it looked like something that would be a nice switch, but for a game loop where multiple buttons may be pressed at the same time, it could possibly decrease performance, depending on the implementation and the requirements of the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T14:37:32.050", "Id": "46557", "ParentId": "45353", "Score": "4" } }, { "body": "<ol>\n<li><p>Use auto-properties when you can like in <code>RigidObject</code> and set default values in the constructor.</p>\n\n<pre><code>public double Mass { get; set; }\n</code></pre></li>\n<li><p>I prefer to keep my private and protected members named with prefix underscore, and my method variables just lowercase. I saw you do some of this, and some not... it is good to keep this consistent.</p></li>\n<li><p>While I'm on naming and capitalization. Method names should be <code>PascalCase</code> not <code>camelCase</code> (start with a capital letter), this is especially true when the method is <code>public</code></p></li>\n<li><p>So in a method like this, I would reccommend lowering the case of those xy's and using <code>+=</code>.</p>\n\n<pre><code>public void AddForce(double x, double y)\n{\n forceX += x;\n forceY += y;\n}\n</code></pre>\n\n<p>Same goes for later in your <code>UpdatePhysics</code> use <code>-=</code>.</p></li>\n<li><p>Unless you plan on adding more logic to this method, you can tune this down to a single statement. As you can see, if the first condition is false, the statement will be immediately broken and return false, only if true will the next condition be checked as this is the nature of <code>&amp;&amp;</code> vs <code>&amp;</code>. Now the result of second condition will be anded with true, which will simply keep it the same, and the value will be returned.</p>\n\n<p><strong>Edit</strong>: Note that I also renamed this method to start with a verb, which is common practice, typically when something starts with <code>is</code>, it is a property or some state on an object.</p>\n\n<pre><code>internal Boolean CollidesWith(RigidObject obj)\n{\n return obj.GetType() == typeof(RigidCircle) &amp;&amp; isCollisionWith(obj as RigidCircle);\n}\n</code></pre>\n\n<p>If you do indeed want to add more rigid objects that this could collide with, you can always append this statement to include them.</p>\n\n<pre><code>internal Boolean CollidesWith(RigidObject obj)\n{\n return \n obj.GetType() == typeof(RigidCircle) &amp;&amp; isCollisionWith(obj as RigidCircle) ||\n obj.GetType() == typeof(RigidRectangle) &amp;&amp; isCollisionWith(obj as RigidRectangle);\n}\n</code></pre></li>\n<li><p>As <a href=\"https://codereview.stackexchange.com/users/18427/malachi\">Malachi</a> pointed out, you should indeed be using vectors for force direction. However, similarly to Malachi's point, you should be using a set value instead of a magic number. You should have some member something like this</p>\n\n<pre><code>double _keyboard_force = 1.5F;\n</code></pre>\n\n<p>Then in the case of your code when you apply the force.</p>\n\n<pre><code>if (Keyboard.IsKeyPressed(Keyboard.Key.Left))\n MainCircle.AddForce( -1F * _keyboard_force , 0);\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T16:16:04.893", "Id": "46568", "ParentId": "45353", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:16:31.757", "Id": "45353", "Score": "10", "Tags": [ "c#", "beginner", "game", "collision", "sfml" ], "Title": "Design of physics with Collision Detection using SFML" }
45353
<p>I have a bit of Python source code that I want to recreate in C#. The code is about reading and decrypting a binary file. I have tested the function on an existing file and it runs without errors; while the resulting string is not garbled or anything, it does not appear to be useful to me.</p> <p>But that is outside the scope of this question. I only want to know if I have translated the function correctly to C# so it does the same as in Python.</p> <p>The Python code:</p> <pre><code> filename = os.path.basename(path_and_filename) key = 0 for char in filename: key = key + ord(char) f = open(path_and_filename, 'rb') results = '' tick = 1 while True: byte = f.read(2) if byte: if tick: key = key + 2 else: key = key - 2 tick = not tick res = struct.unpack('h', byte)[0] ^ key results = results + chr(res) continue break f.close() return results </code></pre> <p><code>path_and_filename</code> is an absolute path to the encrypted file.</p> <p>Here is the C# code I wrote:</p> <pre><code> string path = _path; string fileName = _fileName; char[] chars = fileName.ToCharArray(); int key = 0; foreach (char c in chars) { key += c; } StringBuilder builder = new StringBuilder(); using (FileStream file = new FileStream(path, FileMode.Open)) { bool tick = true; while (true) { int i = file.ReadByte(); if (i == -1) break; if (tick) key += 2; else key -= 2; tick = !tick; //The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte) i &lt;&lt;= 8; i += file.ReadByte(); i ^= key; byte b = (byte)i; char c = (char)b; builder.Append(c); } } string result = builder.ToString(); </code></pre> <p>Never mind the dirtiness of the code. Will those 2 snippets give the same output to a certain input?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T23:17:03.017", "Id": "79085", "Score": "3", "body": "This is an interesting question, because unlike most translation questions (which are bad), you've actually tried to do it. This comment is designed to guard against thoughtless downvotes. I can in no way protect you from thoughtful ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T00:15:40.690", "Id": "79092", "Score": "0", "body": "Re. \"certain input\", we're supposed to assume but are you sure that `os.path.basename(path_and_filename)` is `\"c28556fb686c8d07066419601a2bdd83\"`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T00:48:18.437", "Id": "79093", "Score": "0", "body": "@ChrisW I go by the official documentation here: http://docs.python.org/2/library/os.path.html The specification says that the last folder name is the return value of that basename method. Besides, that folder name is the key for the decryption operation, so it does make sense that it would be the input for the key." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T00:54:14.333", "Id": "79094", "Score": "0", "body": "I fear that \"path\" includes the filename as well as the folder: see http://stackoverflow.com/q/1112545/49942 for example, and [this](http://pic.dhe.ibm.com/infocenter/idshelp/v117/index.jsp?topic=%2Fcom.ibm.gen_busug.doc%2Fc_fgl_ext_os_path_basename.htm) which says it returns the filename." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:21:46.767", "Id": "79116", "Score": "0", "body": "@ChrisW Thank you, that was indeed part of the problem. basename does return \"Game_Keywords.dat\". There were other msitakes as well." } ]
[ { "body": "<p>This section seems wrong:</p>\n\n<pre><code>//The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)\ni &lt;&lt;= 8;\ni += file.ReadByte();\n</code></pre>\n\n<p>you're shifting the value in <code>i</code> 8 bits left and then reading another byte. I'm guessing because the original code read it in 2 bytes at a time. If your file isn't the right length then this will break it here. what about:</p>\n\n<pre><code>i &lt;&lt;= 8;\nint secondByte = file.ReadByte()\nif(secondByte != -1)\n{\n i += secondByte ;\n}\n</code></pre>\n\n<p>Whats with this? It is casting an int to a byte to a char and it is truncating.</p>\n\n<pre><code>byte b = (byte)i;\nchar c = (char)b;\n</code></pre>\n\n<p>so you're better off ignoring the first byte and instead everything after <code>tick = !tick;</code>\ncould be:</p>\n\n<pre><code>i = file.ReadByte();\n\nchar c = (char)(i ^ (key &amp; 255));\nbuilder.Append(c);\n</code></pre>\n\n<p>In Python <code>chr()</code> will throw an exception if the value is greater than 255 anyway. </p>\n\n<p>And IMHO it is a bad idea to roll your own encryption/decryption like this. Use a trusted known <a href=\"https://superuser.com/questions/381849/cross-platform-file-encryption-tool?rq=1\">solution</a> instead.</p>\n\n<p><strong>Question:</strong> I only want to know if I have translated the function correctly to C# so it does the same as in Python</p>\n\n<p><strong>Answer</strong> Its more of a transliteration rather than a translation but they should give the same output. If I were to re-write the python into c# it would look different as it seems inefficient to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:46:43.513", "Id": "79118", "Score": "1", "body": "I know about the dangers of rolling my own encryption. The python is not mine, however, I'm just trying to translate/transliterate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T02:16:39.650", "Id": "45365", "ParentId": "45359", "Score": "4" } }, { "body": "<p>After a half-nighter, I finally found the solution. Running the code via <a href=\"http://ironpython.net/\" rel=\"nofollow\">Iron Python</a> told me that os.path.basename(path_and_filename) in my case does return the file name, as pointed out in the comments, not the name of the last folder. That was the first problem, so I've been working with the wrong key.</p>\n\n<p>The second issue was how I read the bytes to XOR with the key. Apparently, unpacking the two bytes read reverses their order in python, so in C# I have to read them in reverse order as well.</p>\n\n<p>So my code would actually look something like this:</p>\n\n<pre><code> string path = _path;\n string filename = _fileName;\n\n //python os.path.basename()\n char[] chars = filename.ToCharArray();\n int key = 0;\n foreach (char c in chars)\n {\n key += c;\n }\n\n StringBuilder builder = new StringBuilder();\n\n using (FileStream file = new FileStream(path + filename, FileMode.Open))\n {\n bool tick = true;\n\n while (true)\n {\n int i = file.ReadByte();\n //it's ok to break here because if the first byte is present, then the second byte will also be present, because the data files are well formed.\n if (i == -1)\n break;\n //we can skip the 2nd byte because the algorithm ignores it anyway\n file.ReadByte();\n\n if (tick)\n key += 2;\n else\n key -= 2;\n tick = !tick;\n\n i ^= key;\n\n char c = (char)(i &amp; 255);\n builder.Append(c);\n }\n }\n string result = builder.ToString();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:13:01.990", "Id": "79271", "Score": "0", "body": "I don't think `(char)` is doing the truncating `(byte)` was." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:34:59.617", "Id": "79277", "Score": "0", "body": "@JamesKhoury I don't see why you made that edit; it doesn't look good to me. Note the `@\"` at the start of the string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T01:48:30.147", "Id": "79280", "Score": "0", "body": "Sorry I should have mentioned it. The StackExchange syntax highlighter doesn't handle `@\"` properly. Atleast on my machine. By putting the extra space it shows the syntax for future viewers.The other alternative is use an extra \\ instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:39:31.010", "Id": "45384", "ParentId": "45359", "Score": "4" } } ]
{ "AcceptedAnswerId": "45384", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T23:12:27.077", "Id": "45359", "Score": "11", "Tags": [ "c#", "python" ], "Title": "Are these C# and Python code snippets functionally identical?" }
45359
<p>I have a method I created which is a custom <code>indexOf()</code>. This code seems ugly to me so I was wondering if anyone could recommend a cleaner and perhaps faster implementation of my method.</p> <pre><code>public static int myIndexOf(char[] str, char[] substr, int index) { if (str == null) { throw new NullPointerException(); } if (substr.length &gt; str.length) { return -1; } if (substr.length == 0 &amp;&amp; index &gt;= str.length) { return str.length; } if (substr.length == 0 &amp;&amp; index &gt;= 0) { return index; } if (substr.length == 0 &amp;&amp; index &lt; 0) { return 0; } if (substr.length == 0 &amp;&amp; str.length == 0 ) { return 0; } int[] found = boyerMoore(str, substr); for (int i : found) { if (i &gt;= index) { return i; } } // can not found substring after index return -1; } // Don't necessarily need any modification for this method. But for those who are interested Boyer Moore: public static int[] boyerMoore(char[] str, char[] substr) { // index array of indexes of found substrings // initialize int indexCounter = 0; int[] subStringIndex = new int[str.length]; for (int c = 0; c &lt; str.length; c++) { subStringIndex[c] = -1; } // character set ASCII int characterSet = 256; // initialize int[] charSet = new int[characterSet]; for (int a = 0; a &lt; characterSet; a++) { charSet[a] = -1; } for (int b = 0; b &lt; substr.length; b++) { charSet[substr[b]] = b; } int skip; for (int i = 0; i &lt;= (str.length - substr.length); i += skip) { //System.out.print(i); skip = 0; for (int j = substr.length - 1; j &gt;= 0; j--) { if (substr[j] != str[i + j]) { skip = Math.max(1, j - charSet[str[i + j]]); break; } } if (skip == 0) { // increment next value in String skip++; // add found substring (beginning index) subStringIndex[indexCounter] = i; indexCounter++; // this last bit is used if Boyer Moore stops searching after first instance is found // return i; } } return subStringIndex; // This bit is used when Boyer Moore is stops after the first instance in found // cannot be found // return str.length; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T01:27:16.560", "Id": "79095", "Score": "0", "body": "It seems the Boyer Moore part is missing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T01:43:53.057", "Id": "79097", "Score": "0", "body": "@konijn to boyer Moore part is on the bottom. I modded it to return an `in[]` if more than one instance of the substring is found" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T02:23:16.683", "Id": "79099", "Score": "0", "body": "I am a stupid user, I did not see the scroll bar, sorry" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:59:31.117", "Id": "79178", "Score": "0", "body": "@konijn dont be so hard on yourself =D" } ]
[ { "body": "<p><strong>Naming</strong></p>\n\n<ul>\n<li><p>Choose an existing idiom such as \"find a needle in a haystack\" and consider putting the parameters in that order.</p></li>\n<li><p>The name <code>index</code> implies some generic location within <code>haystack</code>. However, <code>start</code> makes it clear why that index is significant.</p></li>\n</ul>\n\n<p>The rest of my answer assumes these changes.</p>\n\n<p><strong>Validating Input</strong></p>\n\n<ul>\n<li><p>You don't need to manually throw <code>NullPointerException</code> for <code>null</code> values when accessing the length of each string will do it automatically. If not, make sure to check <em>both</em> strings for consistency.</p></li>\n<li><p>Consider how to handle negative values for <code>start</code>, typically by taking it from the end of the haystack. You'll need to decide whether to use modulo arithmetic or constrain overly-negative values to zero.</p>\n\n<pre><code>if start &lt; 0\n start = Math.max(0, haystack.length + start)\n</code></pre></li>\n</ul>\n\n<p><strong>Logic Yoga</strong></p>\n\n<ul>\n<li><p>Combine identical prefix expressions in an <code>if</code> chain.</p>\n\n<pre><code>if (A &amp;&amp; R) { X }\nif (A &amp;&amp; S) { Y }\nif (A &amp;&amp; T) { Z }\n</code></pre>\n\n<p>This can be <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\">simplified and optimized</a> to</p>\n\n<pre><code>if (A) {\n if (R) { X }\n if (S) { Y }\n if (T) { Z }\n}\n</code></pre>\n\n<p>It works for <code>||</code> as well, though I can't think of a recent sighting in the wild.</p>\n\n<pre><code>if (A || R) { X }\nif (A || S) { Y }\nif (A || T) { Z }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if (A)\n X Y Z\nelse\n // same as \"if (A)\" above\n</code></pre></li>\n<li><p>Clarify intent by using <code>else if</code> after blocks that should exit. Adding <code>else</code> lets the compiler <em>enforce</em> that intent when they're modified.</p>\n\n<pre><code>myIndexOf(needle, haystack, start)\n if needle is larger than haystack\n return ...\n else if needle is empty\n return ...\n else\n return ...\n</code></pre></li>\n</ul>\n\n<p><strong>Extract Methods</strong></p>\n\n<ul>\n<li><p>Move generic helper methods such as constraining an index to a library. Apache Commons probably has one. This way someone doesn't have to read the code three times to infer its intended purpose (versus what it actually does). Here <code>index</code> makes more sense without a context.</p>\n\n<pre><code>constrain(index, size)\n return Math.max(0, Math.min(index, size))\n</code></pre></li>\n<li><p>Separate parameter checking from the raw search algorithm when either is long enough.</p>\n\n<pre><code>findBoyerMore(needle, haystack, start)\n for index in boyerMoore(needle, haystack)\n if index &gt;= start\n return index\n return -1\n</code></pre></li>\n<li><p>Extract a method to test if <code>needle</code> can fit inside <code>haystack</code> at <code>start</code>.</p>\n\n<p>Also, you can <a href=\"https://en.wikipedia.org/wiki/Fail-fast\">fail fast</a> in the case of <code>myIndexOf(\"foo\", \"foobar\", 5)</code> without calling <code>boyerMoore</code> even though <code>foo</code> is shorter than <code>foobar</code>. Take <code>start</code> into consideration when comparing the length of the two strings.</p>\n\n<pre><code>canFitAt(needle, haystack, start)\n return start + needle.length &lt;= haystack.length\n</code></pre></li>\n</ul>\n\n<p><strong>Dead Code</strong></p>\n\n<ul>\n<li>Since <code>index &gt;= 0</code> and <code>index &lt; 0</code> cannot both fail, <code>if (substr.length == 0 &amp;&amp; str.length == 0)</code> cannot succeed and can be removed.</li>\n</ul>\n\n<p><strong>End Result</strong></p>\n\n<p>Combining all of the above gives us a much-simplified method.</p>\n\n<pre><code>myIndexOf(needle, haystack, start)\n if canFitAt(needle, haystack, start)\n return findBoyerMoore(needle, haystack, start)\n else\n return constrain(start, haystack.length)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T21:25:49.153", "Id": "436592", "Score": "0", "body": "I would say your `||` expansion is not an improvement as it is severely not DRY." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T15:52:40.887", "Id": "436826", "Score": "0", "body": "@NetMage Sometimes violating guidelines like DRY can improve readability. The key is recognizing when to break them. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-29T21:46:29.277", "Id": "437065", "Score": "0", "body": "In this case I would suggest it is asking for a future maintenance error, however, when Y is changed in one place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T04:27:36.050", "Id": "437232", "Score": "0", "body": "@NetMage And what about when `A` is changed in only one place? This is a seriously contrived example no one will encounter in the wild. There's no 100% correct answer to the trade-off of \"DRY vs. readablity\". That's what makes it a trade-off, and programming is full of them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T06:45:15.613", "Id": "45373", "ParentId": "45362", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T00:53:53.167", "Id": "45362", "Score": "6", "Tags": [ "java", "strings", "search" ], "Title": "indexOf() and Boyer Moore methods" }
45362
<p>For non-plugin code, I generally use the module pattern, but I'm working on a jQuery plugin and decided to try out the "<a href="http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns" rel="nofollow noreferrer">lightweight start</a>" pattern. The problem is, I find myself needing <code>$.proxy</code> when calling private methods to ensure the <em>this</em> context. </p> <p>Is there a better way to structure the code in order to avoid <code>$.proxy</code>, while ensuring the private methods have access to the <code>init()</code> method's <em><code>this</code></em> context? Where exactly should I define private properties?</p> <p><a href="http://jsfiddle.net/jbarreiros/tw5Pq/" rel="nofollow noreferrer">Jsfiddle example without $.proxy</a> ... also have a <a href="http://jsfiddle.net/jbarreiros/s64yn/" rel="nofollow noreferrer">jsfiddle example using $.proxy</a></p> <pre><code>(function($, window, document, undefined) { var pluginName = "myPlugin", defaults = { opt1: "#opt1", }; function Plugin(element, options) { this.element = $(element); this.options = $.extend( {}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype.init = function() { this.counter = 1; $("div").each(privateMethod1); $("body").on("click", this.options.opt1, event1); }; function privateMethod2(i, div) { // "this" context is Window, not Plugin $(div).append(i); this.element.append(this.counter); }; function privateMethod1(i, el) { // "this" context is Window, not Plugin this.counter += 1; // undefined, but defined in init() privateMethod2(i, el); }; function event1(ev, el) { this.counter += 1; // undefined, but defined in init() privateMethod1(this.counter, el); }; $.fn[pluginName] = function(options) { return this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin(this, options)); } }); }; }(jQuery)); </code></pre> <p><br> <strong>Edit:</strong></p> <p>What I learned. This pattern appears to actually make all methods private. This is because the <code>if (!$.data(this, "plugin_" + pluginName)) {</code> has no <code>else</code> block to handle elements that already have a reference to the plugin. To allow a method to be called, check out <a href="https://stackoverflow.com/a/14128485/536734">https://stackoverflow.com/a/14128485/536734</a>.</p>
[]
[ { "body": "<p>You could use a closure to create your own proxy.</p>\n\n<pre><code>Plugin.prototype.init = function() {\n var self = this;\n rows.each(function (groupIndex, group) {\n self.initGroup(groupIndex, group);\n });\n this.container.on(\"click\", this.options.addBtnId, function (ev) {\n self.addGroup(ev);\n });\n};\n</code></pre>\n\n<p><strike>Why are <code>initGroup</code> and <code>addGroup</code> using <code>$.proxy</code>? They are already being called with the correct <code>this</code> context, and rebinding to the same context changes nothing.</strike></p>\n\n<p><strong>Edit:</strong> Instead of using plain functions to implement \"private methods\", promote them to proper object methods and mark them private using JSDoc. This will save you those extra calls to <code>$.proxy</code>.</p>\n\n<pre><code>/** @private */\nPlugin.prototype.initGroup = function(groupIndex, group) {\n this.addFieldIds(groupIndex, group);\n};\n\n/** @private */\nPlugin.prototype.addGroup = function(ev) {\n this.initGroup(this.maxGroupIndex, newGroup);\n};\n</code></pre>\n\n<p>In my opinion, forcing developers to jump through hoops just to hide private methods is a net loss.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:59:38.807", "Id": "79179", "Score": "0", "body": "I found that without $.proxy, I lost access to any variables (this.counter) created within init(). -- Should private properties be defined outside of the init() method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:49:09.780", "Id": "79239", "Score": "1", "body": "@jbarreiros Ah, I didn't realize the private methods were plain functions and not object methods. If you want to use `this` inside them, you have to use something to bind the `this` context in the method call. `$.proxy` works for this, but you can instead make them proper object methods and mark them private in the documentation. See the updated [fiddle](http://jsfiddle.net/tw5Pq/2/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:28:35.897", "Id": "79424", "Score": "0", "body": "Got it. I was under the impression that adding the function to the prototype would make it \"public\", but looking closer at the syntax, I realize now that you can't actually call any of the methods from outside due to the `if (!$.data(this, \"plugin_\" + pluginName)) {` conditional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T17:41:19.173", "Id": "445055", "Score": "0", "body": "What is the difference between private function vs prototype function? why should not go with private functions?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T06:51:26.270", "Id": "45374", "ParentId": "45369", "Score": "4" } } ]
{ "AcceptedAnswerId": "45374", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T05:25:30.203", "Id": "45369", "Score": "8", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Private methods and properties in jQuery \"lightweight start\" pattern" }
45369
<blockquote> <p>Lets say there are 10 boys and 10 girls in speed date. 10 boys select 4 girls and rank them. 10 girls select 4 boys and rank them. In the end the winning pairs would be returned.</p> </blockquote> <p>Finer details such as tie-breakers, rules of input params etc, are well documented. Looking for code review, optimization and best practices.</p> <pre><code>final class Pair { private final String male; private final String female; public Pair(String male, String female) { this.male = male; this.female = female; } public String getMale() { return male; } public String getFemale() { return female; } @Override public String toString() { return male + " dates: " + female; } } /** * * Provides a thread safe solution Solves the speed date problem. * * Example: * -------- * - Lets say there are 10 boys and 10 girls in speed date * - 10 boys select 4 girls and rank them. * - 10 girls select 4 boys and rank them. * - in the end the winning pairs would be returned. * * Complexity: * Time complexity: O(nlogn) * Space complexity: O(n) * */ public class SpeedDateCompute { private final Map&lt;String, List&lt;String&gt;&gt; maleChoices; private final Map&lt;String, List&lt;String&gt;&gt; femaleChoices; /** * Does not make a deep copy of maps thus client is not expected to change maleChoice, femaleChoice. * Expects consistency in males and female maps, else results are unpredictable. * * By consistency it means: * - The number of boys and girls should be the same. * - Each boy and each girl should make same number of choices * - Choices should mention "only existing members of opposite sex" * * * @param maleChoices * @param femaleChoices */ public SpeedDateCompute(Map&lt;String, List&lt;String&gt;&gt; maleChoices, Map&lt;String, List&lt;String&gt;&gt; femaleChoices) { validate(maleChoices, femaleChoices); this.maleChoices = maleChoices; this.femaleChoices = femaleChoices; } private static class Edge { String male; String female; int malesPreference; // what does male ranks this female ? int femalePreference; // what does female ranks this male ? Edge (String male, String female, int malesPreference, int femalePreference) { this.male = male; this.female = female; this.malesPreference = malesPreference; this.femalePreference = femalePreference; } } private static class EdgeComparator implements Comparator&lt;Edge&gt; { @Override public int compare(Edge edge1, Edge edge2) { int val = rank (edge1.femalePreference - 1, edge1.malesPreference - 1) - rank (edge2.femalePreference - 1, edge2.malesPreference - 1); return val; } /* * Ranking algorithm. * * Let notation (1,2) mean - femalePrerence is 1 and malePreference is 2. * (1, 1) means both rank each other as their best so this pair triumps over (2, 2) * but there is a tie between (1, 2) and (2, 1) * As a tie breaker we give preference to feelings of women * thus (1,2) &gt; (2, 1) * * Thus the rule is expanded to * * (1, 1) &gt; (1, 2) &gt; (2, 1) &gt; (2, 2) * * This can be thought of as a matrix of the form * (lil lazy to retype the whole thing, plz check the link) * http://math.stackexchange.com/questions/720797/whats-the-name-of-this-sort-of-matrix * http://codereview.stackexchange.com/questions/44939/a-matrix-with-square-diagonals-and-transpose-being-increments-of-other * * @param row the female choice * @param col the male choice * @return */ private int rank(int row, int col) { if (row == col) { return row * row; } int rank = (col) * (col) + 1 + (2 * row) ; if (row &lt; col) { return rank; } else { return rank + 1; } } } private void validate (Map&lt;String, List&lt;String&gt;&gt; maleChoices, Map&lt;String, List&lt;String&gt;&gt; femaleChoices) { if (maleChoices == null || femaleChoices == null) { if (maleChoices != null) { throw new NullPointerException("female choice map should not be null"); } if (femaleChoices != null) { throw new NullPointerException("male choice map should not be null"); } throw new NullPointerException("no choice map should be null."); } if (maleChoices.size() == 0 || femaleChoices.size() == 0) { if (maleChoices.size() == 0) { throw new IllegalArgumentException("male choice map should not be empty."); } if (femaleChoices.size() == 0) { throw new IllegalArgumentException("female choice map should not be empty."); } throw new IllegalArgumentException("no choice map should be empty."); } } public List&lt;Pair&gt; getPairs() { final Collection&lt;Edge&gt; edges = parseChoiceMaps(); final List&lt;Edge&gt; sortedEdges = sort(edges); return createPairs(sortedEdges); } /** * Given a directed bipartite graph, it converts bipartite graph into * undirected map. * * @param choiceMap the bipartite graph of choices * @return */ private Collection&lt;Edge&gt; parseChoiceMaps() { final Map&lt;String, Edge&gt; combinedMaleChoice = new HashMap&lt;String, Edge&gt;(); synchronized (maleChoices) { // parsing male choices. for (Entry&lt;String, List&lt;String&gt;&gt; maleChoice : maleChoices.entrySet()) { String maleName = maleChoice.getKey(); List&lt;String&gt; females = maleChoice.getValue(); for (int i = 0; i &lt; females.size(); i++) { // mark female preference as "size" thus assigning the worst rank as default. combinedMaleChoice.put(maleName + females.get(i), new Edge(maleName, females.get(i), i + 1, maleChoices.size())); } } } synchronized (femaleChoices) { // parsing female choices for (Entry&lt;String, List&lt;String&gt;&gt; femaleChoice : femaleChoices.entrySet()) { List&lt;String&gt; males = femaleChoice.getValue(); for (int i = 0; i &lt; males.size(); i++) { String name = males.get(i) + femaleChoice.getKey(); // check if any male has chosen this female, else skip. if (combinedMaleChoice.containsKey(name)) { combinedMaleChoice.get(males.get(i) + femaleChoice.getKey()).femalePreference = i + 1; } } } } return combinedMaleChoice.values(); } private List&lt;Edge&gt; sort(Collection&lt;Edge&gt; edges) { final List&lt;Edge&gt; edgeList = new ArrayList&lt;Edge&gt;(edges); Collections.sort(edgeList, new EdgeComparator()); return edgeList; } private List&lt;Pair&gt; createPairs(List&lt;Edge&gt; edges) { final Set&lt;String&gt; hookedUpMales = new LinkedHashSet&lt;String&gt;(); final Set&lt;String&gt; hookedUpFemales = new LinkedHashSet&lt;String&gt;(); for (Edge edge : edges) { if (hookedUpMales.contains(edge.male) || hookedUpFemales.contains(edge.female)) { continue; } hookedUpMales.add(edge.male); hookedUpFemales.add(edge.female); } return mapSetsToPairs(hookedUpMales, hookedUpFemales); } private List&lt;Pair&gt; mapSetsToPairs(Set&lt;String&gt; hookedUpMales, Set&lt;String&gt; hookedUpFemales) { Iterator&lt;String&gt; maleItr = hookedUpMales.iterator(); Iterator&lt;String&gt; femaleItr = hookedUpFemales.iterator(); final List&lt;Pair&gt; pairs = new ArrayList&lt;Pair&gt;(); while (maleItr.hasNext() &amp;&amp; femaleItr.hasNext()) { pairs.add(new Pair(maleItr.next(), femaleItr.next())); maleItr.remove(); // just to optimize space femaleItr.remove(); // just to optimize space } return pairs; } public static void main(String[] args) { /* * Test case 1 */ Map&lt;String, List&lt;String&gt;&gt; maleChoice1 = new HashMap&lt;String, List&lt;String&gt;&gt;(); Map&lt;String, List&lt;String&gt;&gt; femaleChoice1 = new HashMap&lt;String, List&lt;String&gt;&gt;(); maleChoice1.put("male1", Arrays.asList("female1", "female2")); maleChoice1.put("male2", Arrays.asList("female2", "female1")); femaleChoice1.put("female1", Arrays.asList("male1", "male2")); femaleChoice1.put("female2", Arrays.asList("male2", "male1")); SpeedDateCompute speedDateCompute = new SpeedDateCompute(maleChoice1, femaleChoice1); List&lt;Pair&gt; actualValues = speedDateCompute.getPairs(); assertEquals("male1", actualValues.get(0).getMale()); assertEquals("female1", actualValues.get(0).getFemale()); assertEquals("male2", actualValues.get(1).getMale()); assertEquals("female2", actualValues.get(1).getFemale()); /* * Test case 2 */ Map&lt;String, List&lt;String&gt;&gt; maleChoice2 = new HashMap&lt;String, List&lt;String&gt;&gt;(); Map&lt;String, List&lt;String&gt;&gt; femaleChoice2 = new HashMap&lt;String, List&lt;String&gt;&gt;(); maleChoice2.put("male1", Arrays.asList("female2", "female1")); maleChoice2.put("male2", Arrays.asList("female1", "female2")); maleChoice2.put("male3", Arrays.asList("female1", "female2")); femaleChoice2.put("female1", Arrays.asList("male2", "male1")); femaleChoice2.put("female2", Arrays.asList("male1", "male2")); femaleChoice2.put("female3", Arrays.asList("male1", "male2")); speedDateCompute = new SpeedDateCompute(maleChoice2, femaleChoice2); actualValues = speedDateCompute.getPairs(); assertEquals("male1", actualValues.get(0).getMale()); assertEquals("female2", actualValues.get(0).getFemale()); assertEquals("male2", actualValues.get(1).getMale()); assertEquals("female1", actualValues.get(1).getFemale()); assertEquals(2, actualValues.size()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:08:27.047", "Id": "79114", "Score": "2", "body": "Where are 10 boys/girls and where are their 4 choices in your test cases?" } ]
[ { "body": "<p>Looks good, I didn't work through the logic of your algorithms, but generally looked if things could be done more efficiently and nothing grabbed my attention.</p>\n\n<p>The one comment I do have is on your validate() method, it checks for null and empty maps, but I believe you have an additional requirement that they are the same size? If so, this should be part of the validate() method as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:19:32.117", "Id": "45401", "ParentId": "45371", "Score": "5" } }, { "body": "<p>This code is really beautiful and well-documented. There are very few parts which could be criticized:</p>\n\n<ul>\n<li><p>Don't use objects where they are not applicable. Your <code>SpeedDateCompute</code> class is essentially only characterized by its <code>getPairs</code> method. We might as well make that static, and invoke it as <code>SpeedDateCompute.getPairs(maleChoices, femaleChoices)</code>.</p>\n\n<p>Such single-method classes encpasulating an algorithm should only be instantiable if we need to pass the algorithm around as an object.</p></li>\n<li><p>Your <code>validate</code> is a bit too complicated. This refactoring produces almost as good error messages, but is less confusing to read.</p>\n\n<pre><code>private void validate (Map&lt;String, List&lt;String&gt;&gt; maleChoices, Map&lt;String, List&lt;String&gt;&gt; femaleChoices) {\n if (femaleChoices == null) {\n throw new NullPointerException(\"female choice map should not be null\");\n }\n if (maleChoices == null) {\n throw new NullPointerException(\"male choice map should not be null\");\n }\n\n if (maleChoices.size() == 0) {\n throw new IllegalArgumentException(\"male choice map should not be empty.\");\n }\n if (femaleChoices.size() == 0) {\n throw new IllegalArgumentException(\"female choice map should not be empty.\");\n }\n}\n</code></pre></li>\n<li><p>Synchronizing on <code>maleChoices</code> and <code>femaleChoices</code> makes little sense. Your documentation already states that the “<em>client is not expected to change maleChoice, femaleChoice</em>”. I would have left it with that, and hope that any users of this class aren't insane enough to share this data between threads. Synchronizing is a fairly expensive operation, so I would wish to avoid it if unnecessary, and offload the responsibility to the client.</p></li>\n<li><p>The keys in <code>combinedMaleChoice</code> are a simple concatentation of the male and female names. While in practice very unlikely, this could lead to clashes (along the lines of <code>\"AA\" + \"B\"</code> vs. <code>\"A\" + \"AB\"</code>). You could use a <code>Map&lt;String, Map&lt;String, Edge&gt;&gt;</code> instead, or a separator that is guaranteed to not occur in the name: <code>maleName + \"\\0\" + femaleName</code>.</p>\n\n<p>This is part of a larger issue that names are not unique. For real-world code, you need some unique identifier. This is one reason why I would like to encapsulate the involved persons in a class of their own, e.g:</p>\n\n<pre><code>public static abstract class Person&lt;Likes extends Person&gt; {\n private final String name;\n private final List&lt;Likes&gt; likes = new ArrayList&lt;&gt;();\n\n public Person(String name) {\n this.name = name;\n }\n\n public String name() {\n return this.name;\n }\n\n public List&lt;Likes&gt; likes() {\n return this.likes;\n }\n\n public List&lt;Likes&gt; likes(List&lt;Likes&gt; others) {\n this.likes.addAll(others);\n return this.likes;\n }\n\n @Override\n public String toString() {\n return this.name();\n }\n\n // \"equals\" defaults to pointer equivalence, which is what we want\n}\n\npublic static class Male extends Person&lt;Female&gt; {\n public Male(String name) {\n super(name);\n }\n\n @Override\n public boolean equals(Object that) {\n return that instanceof Male &amp;&amp; super.equals(that);\n }\n}\n\npublic static class Female extends Person&lt;Male&gt; {\n public Female(String name) {\n super(name);\n }\n\n @Override\n public boolean equals(Object that) {\n return that instanceof Female &amp;&amp; super.equals(that);\n }\n}\n</code></pre>\n\n<p>This also allows us to better leverage the type system than only relying on <code>String</code>s – the downside is that the client will need more initialization code to prepare the <code>Person</code>s.</p></li>\n<li><p>There is no substantial difference between <code>Pair</code> and <code>Edge</code>. I'd combine both into one class.</p></li>\n<li><p>You made your code far more complicated than necessary by splitting logic into <code>createPairs</code> and <code>mapSetsToPairs</code>. You create two <code>LinkedHashSet</code>s and then iterate over both in parallel. We can do all of that in one loop:</p>\n\n<pre><code>private List&lt;Pair&gt; createPairs(List&lt;Edge&gt; edges) {\n final Set&lt;String&gt; hookedUpMales = new HashSet&lt;&gt;();\n final Set&lt;String&gt; hookedUpFemales = new HashSet&lt;&gt;();\n final List&lt;Pair&gt; hookedUpPairs = new ArrayList&lt;&gt;();\n\n for (Edge edge : edges) {\n if (hookedUpMales.contains(edge.male) || hookedUpFemales.contains(edge.female)) {\n continue;\n }\n hookedUpPairs.add(new Pair(edge.male, edge.female));\n hookedUpMales.add(edge.male);\n hookedUpFemales.add(edge.female);\n }\n\n return hookedUpPairs;\n}\n</code></pre></li>\n<li><p>If you are targeting Java 7, you don't have to spell out all generics, and can use the diamond operator instead:</p>\n\n<pre><code>// final List&lt;Edge&gt; edgeList = new ArrayList&lt;Edge&gt;(edges);\nfinal List&lt;Edge&gt; edgeList = new ArrayList&lt;&gt;(edges);\n</code></pre></li>\n<li><p>Your tests are buggy. While you guarantee that you return the optimal pairs, you do not guarantee any order when two pairs have the same preferences. Therefore in your first test, <code>actualValues.get(0).getMale()</code> may be <code>male2</code> rather than <code>male1</code>. Instead:</p>\n\n<ol>\n<li>Test that the number of returned pairs is correct</li>\n<li>Test that the collection of pairs <code>contains</code> an expected pair. This implies that you should override <code>equals</code> and <code>hashCode</code> for the <code>Pair</code> class.</li>\n</ol></li>\n<li><p>In <code>parseChoiceMaps</code>, you assign <code>i + 1</code> as a preference, then decrement that value again when calculating your rank. This index shuffling servers no purpose, and can be removed by using zero-based preferences</p></li>\n</ul>\n\n<p>I did a bit of refactoring incl. introducing a <code>Person</code> class and unifying <code>Edge</code> and <code>Pair</code>, and the result is in fact quite nice: <a href=\"http://ideone.com/RSTcUu\">http://ideone.com/RSTcUu</a></p>\n\n<p>Further observations:</p>\n\n<ul>\n<li><p>Your JavaDoc contains Markdown-like lists. IIRC, you can use a restricted subset of HTML for formatting instead.</p></li>\n<li><p>Your ranking algorithm seems terribly flawed. I understand that you need some absolute ordering, but a modified Manhattan Distance or Euclidean Distance would probably do a better job. For example with <code>f = 10, m = 0</code> (where <em>f</em> is the female preference, <em>m</em> the male preference) we get a rank of <code>22</code>. Now we might have another edge with <code>f = 0, m = 9</code>. I would expect this second edge to be sorted before the first one. But it has a rank of <code>101</code>, which is far worse! In other words, the choice of males is weighted more heavily.</p>\n\n<p>A related problem is that you assign a preference for females even when they have shown no interest in that specific male. For example, consider this:</p>\n\n<pre><code>male1 likes female1\nmale2 likes female2\nfemale1 likes male1\nfemale2 likes male1\n</code></pre>\n\n<p>The pairing <code>male1 – female1</code> is expected, as both like each other. However, <code>male2 – female2</code> is dubious. Due to your implementation, the reverse is not true:</p>\n\n<pre><code>male1 likes female1\nmale2 likes female1\nfemale1 likes male1\nfemale2 likes male2\n</code></pre>\n\n<p>will only return the <code>male1 – female1</code> pairing.</p>\n\n<p>Better rankings that use the female rankings to break ties could be a modified Manhattan Distance:</p>\n\n<pre><code>rank = (m + f) * max + f\n</code></pre>\n\n<p>or Euclidean Distance:</p>\n\n<pre><code>rank = (int) (Math.sqrt(m*m + f*f) * max + f)\n</code></pre>\n\n<p>where <code>max</code> is the maximum rating involved in this comparison.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:27:08.307", "Id": "45409", "ParentId": "45371", "Score": "10" } }, { "body": "<p>Computationally speaking, I don't have anything to add what has already been said. @amon did a really comprehensive review of your code. However, there are some serious sociological and/or ethical flaws in your code. I would say that, genderly speaking, it could be made more generic:</p>\n\n<ul>\n<li><strong>Sexual orientation:</strong> first of all, you are assuming that boys love girls and girls love boys. This is incorrect. You would have to take into account homosexual and bisexual people too. That would mean that your <code>Person</code> instances should also have a variable specifying what is the sexual orientation of the instance. You could use a percentage to roughly represent whether the subjects are more interested in males or in females; that percentage could be taken into account in the rating algorithm.</li>\n<li><strong>Sex:</strong> if we only restrict ourselves to biology and biological values, you totally overlook intersexual people. That may be very offensive since many of them have a hard time finding a place in society and try to conform to one gender while there is no \"dedicated\" gender for intersexual people. That could feel like an insult. Also, some try to assume an intersexual identity instead of trying to conform to \"male\" and \"female\".</li>\n<li><strong>Gender:</strong> we can safely assume that reducing people to what they have between their legs is a bad idea overall. Therefore, you could consider their gender instead. However, you will have trouble: there are as many genders as we can think of (for example, Facebook recently added <a href=\"http://theweek.com/article/index/256474/facebook-offers-users-56-new-gender-options-heres-what-they-mean\">56 gender options</a> instead to complete \"male\" and \"female\"). With the current design, your code would become overly complicated if you tried to represent even the most well-known ones.</li>\n</ul>\n\n<p>To conclude, one solution would be to make two lists of <code>Individual</code>s. Not only would it be more respectful towards many many people in the world, but you could also get rid of your <code>Male</code> and <code>Female</code> classes: that would make your code more generic while probably shorter and simpler too. Everywhere you have variable names containing <code>male</code> or <code>female</code>, you can replace them by <code>person1</code> and <code>person2</code> or <code>individual1</code> and <code>individual2</code>. Moreover, that kind of genericity would allow your code to be adapted to more complex problems (for example, a problem of <a href=\"http://en.wikipedia.org/wiki/M%C3%A9nage_%C3%A0_trois\">Ménage à trois</a> speed dating).</p>\n\n<p><em>Never forget that you should treat people as people, and consider how they define themselves before considering how you would like them to be.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:15:46.887", "Id": "79185", "Score": "3", "body": "I considered doing a `s/Male/HeterosexualMale/g` etc. in my refactoring, and the implementation can be easily adapted to handle arbitrary sexual orientations. There is no need for the input sets to be divided into male/female, except that the preferences of the latter group is used during the sorting to break ties between two pairings. This deal-braking mechanism has to be consistent, which is difficult to realize otherwise (comparing the names is not possible, as there could be ties here as well, and I don't want to untangle those love triangles)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:19:36.083", "Id": "79186", "Score": "0", "body": "@amon Deal-breaking will always be the problem anyway :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:56:32.320", "Id": "79199", "Score": "3", "body": "So your argument is that the problem itself has to be changed. Why? Are you the one who assigned this task? Maybe the intended audience is exactly how the problem states it. Next time I write a program to sort football fans and you will object that people who hate football and like basketball instead should be also included? Nothing in your answer actually answers the question, you just argue that the question should be changed to look for a solution for a completely different problem. This is codreview, not political sciences." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:09:00.263", "Id": "79202", "Score": "3", "body": "This algo was supposed to be bipartite graph - i could not think of any example but male/female pair to better convey my ideas. However noted your point and apologies for everyone" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:25:06.443", "Id": "79314", "Score": "0", "body": "@vsz My argument was that I was just trying to do something different. For fun actually (those are social sciences by the way, not political sciences). I expected that I would get that kind of answers and was actually waiting for them. That's pretty entertaining :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:36:38.873", "Id": "79318", "Score": "0", "body": "@JavaDeveloper At least, your problem was simple and clean to demonstrate the use of a bipartite graph, that's good. Generally speaking, you won't have to think about what I said whatsoever, unless you have to work on the design of a social platform (and even so, I doubt that anybody cares about how it is implemented). Nothing to worry about :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:54:16.600", "Id": "79373", "Score": "0", "body": "@Morwenn : I wouldn't even have commented if you wouldn't have included words like \"insult\" and \"offensive\", which indicate a tone I think is off-topic on this site. Maybe I'm just a bit too allergic to people trying to bring political topics or ideological propaganda (indifferent from which side) to this site :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:19:29.693", "Id": "79379", "Score": "0", "body": "@vsz I actually hesitated to include the aforementioned words, but tried to put myself in the shoes of the said people. It's rather impossible to content everybody, so I at least put words \"may\" and \"could\" wherever I could. You know, that's trying to write some kind of objective subjectivity, that's oxymoronic. But reading my answer again, I do sound a bit harsh." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:01:25.913", "Id": "45415", "ParentId": "45371", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T06:07:37.843", "Id": "45371", "Score": "12", "Tags": [ "java", "algorithm" ], "Title": "Speed dating algorithm to select the pair of dates" }
45371
<p>I have the following code which I feel that I must refactor, but not sure how to do it.</p> <pre><code>List&lt;AlgoTuningData&gt; feedbackScoreDatas; List&lt;AlgoTuningData&gt; topRatedDatas; int score1 = 0; int score2 = 0; boolean matched1 = false; boolean matched2 = false; for (AlgoTuningData topRatedData : topRatedDatas) { if (!matched1 &amp;&amp; isMatchesTopRatedTuning(p1, topRatedData)) { score1 += topRatedData.getRank(); matched1 = true; } if (!matched2 &amp;&amp; isMatchesTopRatedTuning(p2, topRatedData)) { score2 += topRatedData.getRank(); matched2 = true; } if (matched1 &amp;&amp; matched2) break; } matched1 = false; matched2 = false; for (AlgoTuningData feedbackScoreData : feedbackScoreDatas) { if (!matched1 &amp;&amp; isMatchesFeedbackScoreTuning(p1, feedbackScoreData)) { score1 += feedbackScoreData.getRank(); matched1 = true; } if (!matched2 &amp;&amp; isMatchesFeedbackScoreTuning(p2, feedbackScoreData)) { score2 += feedbackScoreData.getRank(); matched2 = true; } if (matched1 &amp;&amp; matched2) break; } private boolean isMatchesTopRatedTuning(Product product, AlgoTuningData topRatedData) { return product.getIsTopRated().equals(topRatedData.getValue()); } private boolean isMatchesFeedbackScoreTuning(Product product, AlgoTuningData feedbackScoreData) { return product.getPrice() &lt;= feedbackScoreData.getMaxProductPrice(); } </code></pre> <p>As you can see, I have 2 lists. each list has a different type of boolean function that verifies its objects. Each call to the function increases the <code>score1</code> and <code>score2</code>.</p> <p>I thought to use Callable, but wasn't sure how to do it for a list of items.</p> <p>I would like my code to have one-line call for each <code>List&lt;AlgoTuningData&gt;</code>, something like this:</p> <pre><code>increaseScore(List&lt;Integer&gt; scores, List&lt;AlgoTuningData&gt;, myFunc) </code></pre>
[]
[ { "body": "<p>I would <em>not</em> refactor this substantially, except maybe to avoid the reuse of the <code>matched1</code> and <code>matched2</code> variables:</p>\n\n<pre><code>{\n boolean matched1 = false;\n boolean matched2 = false;\n for (...) {\n ...\n }\n}\n\n// and here again\n</code></pre>\n\n<p>Your intuition is correct that this could be done much cleaner using functional programming, but FP is a pain with Java 1–7. So we have the following options:</p>\n\n<ul>\n<li>use Java 8</li>\n<li>use functional language like Scala</li>\n<li>ignore the pain, and do it anyway</li>\n</ul>\n\n<p>The last solution does not involve <code>java.util.concurrent.Callable</code>, but an interface of our own:</p>\n\n<pre><code>interface TuningDataTest {\n boolean test(Product product, AlgoTuningData datum);\n}\n</code></pre>\n\n<p>We can then write a function <code>scoreTuningData</code>:</p>\n\n<pre><code>private static class Score {\n final public int score1;\n final public int score2;\n\n public Score(int s1, int s2) {\n score1 = s1;\n score2 = s2;\n } \n\n public Score add(Score that) {\n return new Score(this.score1 + that.score1, this.score2 + that.score2);\n }\n}\n\nprivate Score scoreTuningData(Product p1, Product p2, Iterable&lt;AlgoTuningData&gt; data, TuningDataTest test) {\n boolean matched1 = false;\n boolean matched2 = false;\n int score1 = 0;\n int score2 = 0;\n\n for (AlgoTuningData datum : data) {\n if (!matched1 &amp;&amp; test.test(p1, datum)) {\n matched1 = true;\n score1 += datum.getRank();\n }\n if (!matched2 &amp;&amp; test.test(p2, datum)) {\n matched2 = true;\n score2 += datum.getRank();\n }\n if (matched1 &amp;&amp; matched2) {\n break;\n }\n }\n\n return new Score(score1, score2);\n}\n</code></pre>\n\n<p>Note that “data” is the plural form of “datum”, the word “datas” does not exist. One “datum” is a “record”, “data” are a set of records.</p>\n\n<p>And your main code would then look like:</p>\n\n<pre><code>List&lt;AlgoTuningData&gt; topRatedData = ...;\nList&lt;AlgoTuningData&gt; feedbackScoreData = ...;\nScore score = scoreTuningData(p1, p2, topRatedData, new TuningDataTest() {\n @Override\n public boolean test(Product product, AlgoTuningData datum) {\n return product.getIsTopRated().equals(datum.getValue());\n }\n}).add(scoreTuningData(p1, p2, feedbackScoreData, new TuningDataTest() {\n @Override\n public boolean test(Product product, AlgoTuningData datum) {\n return product.getPrice() &lt;= datum.getMaxProductPrice();\n }\n}));\n\nint score1 = score.score1;\nint score2 = score.score2;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:58:10.790", "Id": "79120", "Score": "0", "body": "The above code will work in Java 7?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:01:06.767", "Id": "79121", "Score": "0", "body": "@Odelya yes, although I didn't test it. It may even work with Java 5!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:08:56.283", "Id": "79134", "Score": "0", "body": "Hi I don't understand how you do you cal lthe first test method for the first collection item and the second test method for the second collection type of item" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:36:59.660", "Id": "79139", "Score": "0", "body": "@Odelya Well, I have the `scoreTuningData` method to which I pass an object with a `test` method. This object is an instance of an anonymous class that implements `TuningDataTest`. In the first class, the `test` method is equivalent to `isMatchesTopRatedTuning`, in the second class, it's equivalent to `isMatchesFeedbackScoreTuning`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:36:04.843", "Id": "45383", "ParentId": "45376", "Score": "4" } } ]
{ "AcceptedAnswerId": "45383", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T07:43:20.357", "Id": "45376", "Score": "1", "Tags": [ "java" ], "Title": "Refactoring scoring algorithm" }
45376
<p>I have written code in C++ 11 and check output with Project Euler site, and it is correct. I am not showing output, just to keep it secret, at least from my end.</p> <p>Please review my C++ 11 code.</p> <pre><code>#include &lt;fstream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;sstream&gt; using namespace std; int main(int argc, char* argv[]) { ifstream file("E:\\names.txt"); if (!file.is_open()) { cout &lt;&lt; "Unable to open file"; return -1; } /* Get all file data with ',' delimiter*/ vector&lt;string&gt; words; string token; while (getline(file, token, ',')) { words.push_back(token); } //sort all the words sort(words.begin(), words.end()); int counter = 0; unsigned int grand_total = 0; //get total of each word and multiply with it's position for (auto it = words.begin(); it != words.end(); it++) { counter++; //copy word from token excluding " " string word((*it).begin() + 1, (*it).end() - 1); int sub_total = 0; for (string::iterator it = word.begin(); it != word.end(); it++) { //ascii value of A is 65 //A is 1, B is 2, so *it - 64 sub_total += *it - 64; } //grand total will be final answer grand_total += sub_total*counter; } return 0; } </code></pre>
[]
[ { "body": "<p>The code is generally pretty clean, however, the major sticking point is that everything here is just shoved into <code>main</code>. Just breaking this up with a few functions that do one thing would be a good start:</p>\n\n<pre><code>std::vector&lt;std::string&gt; read_file(const std::string&amp; path)\n{\n std::ifstream file(path);\n\n if (!file.is_open())\n {\n std::cerr &lt;&lt; \"Unable to open file\" &lt;&lt; \"\\n\";\n std::exit(-1);\n }\n\n std::vector&lt;string&gt; words;\n std::string token;\n\n while (std::getline(file, token, ','))\n {\n words.push_back(token);\n }\n\n return words;\n}\n</code></pre>\n\n<p>I've also put back all the <code>std::</code> namespace qualifier. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Using namespace std</a> is something that is ok for very short programs like this, but is something you shouldn't get into the habit of doing.</p>\n\n<p>How about a function to sum the values in a word?</p>\n\n<pre><code>int sum_word(const std::string&amp; word)\n{\n constexpr static int ascii_to_integer = 64;\n int total = 0;\n for(auto c : word) {\n total += (c - ascii_to_integer);\n }\n return total;\n}\n</code></pre>\n\n<p>In fact, if you want to be fancy, this can be even shorter:</p>\n\n<pre><code>int sum_word(const std::string&amp; word)\n{\n constexpr static int ascii_to_integer = 64;\n return std::accumulate(word.begin(), word.end(), 0, [](int i) { return i - ascii_to_integer; });\n}\n</code></pre>\n\n<p>Finally, we can have a function to encompass the outer loop (processing each word in the vector):</p>\n\n<pre><code>int total_word_position(const std::vector&lt;std::string&gt;&amp; v)\n{\n int counter = 1;\n int total = 0;\n\n for(const std::string&amp; s : v) {\n // Exclude \" \"\n std::string word(s.begin() + 1, s.end() - 1);\n total += (sum_word(word) * counter);\n ++counter;\n }\n return total;\n}\n</code></pre>\n\n<p>Your <code>main</code> method would then become:</p>\n\n<pre><code>int main()\n{\n std::vector&lt;std::string&gt; all_words = read_file(\"E:\\\\names.txt\");\n std::sort(all_words.begin(), all_words.end());\n int grand_total = total_word_position(all_words);\n}\n</code></pre>\n\n<p>This has a number of benefits:</p>\n\n<ul>\n<li><p>Variable scope is minimized to a single smaller function, instead of a large main function.</p></li>\n<li><p>It's generally easier to read and debug, as there is less to keep in your head.</p></li>\n<li><p>It separates parts of the program that do very different things (reading a file vs sorting vs summing numbers).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T11:37:49.600", "Id": "79147", "Score": "1", "body": "You forgot to use the `path` argument in `read_file`. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T11:48:59.167", "Id": "79149", "Score": "0", "body": "@JoãoPortela Whoops, good catch. Fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:12:34.510", "Id": "45380", "ParentId": "45377", "Score": "10" } }, { "body": "<p>Yuushi's advice is pretty good. Here's what I have to add:</p>\n\n<pre><code>ifstream file(\"E:\\\\names.txt\");\n</code></pre>\n\n<p>Would be nice if the path wasn't hardcoded. You could pass in the input through stdin or open a file name passed in argv[1].</p>\n\n<pre><code>if (!file.is_open())\n</code></pre>\n\n<p>I believe <code>if (!file)</code> is a better way to do this since it checks if error bits are set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:17:14.543", "Id": "45382", "ParentId": "45377", "Score": "6" } } ]
{ "AcceptedAnswerId": "45380", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T07:43:59.750", "Id": "45377", "Score": "7", "Tags": [ "c++", "algorithm", "c++11", "file", "programming-challenge" ], "Title": "Project Euler #22 - Name scores" }
45377
<p>I'm just started learning TDD with Rails and RSpec. This is my first test for controller. Just plain RESTful UserController that responds with JSON, so it has no <em>new</em> and <em>edit</em> methods. Please review it</p> <pre><code>require 'spec_helper' describe UsersController do let(:users) { 4.times.map { create(:user) } } describe '#index' do before(:each) { get :index } it 'assigns all users to @users' do expect(assigns(:users)).to match_array users end it 'success' do expect(response).to be_success end end describe '#show' do context 'when requested user exists' do let(:user) { users[rand 4] } before(:each) { get :show, id: user.id } it 'success' do expect(response).to be_success end it 'assigns it to @user' do expect(assigns(:user)).to eq user end end context 'when requested user does not exists' do it 'throws ActiveRecord::RecordNotFound' do expect { get :show, id: -1 }.to raise_exception ActiveRecord::RecordNotFound end end end describe '#create' do before(:each) { post :create, ** user_attrs } context 'when valid' do let(:user_attrs) { attributes_for(:user) } it 'success' do expect(response).to be_success end it 'saves and assigns new user to @user' do user = assigns(:user) expect(user).to be_kind_of ActiveRecord::Base expect(user).to be_persisted expect(users).not_to include user end end context 'when invalid' do let(:user_attrs) { attributes_for(:invalid_user) } it 'fails' do expect(response).not_to be_success end it 'assigns user to @user' do expect(assigns(:user)).to be_kind_of ActiveRecord::Base end end end describe '#update' do let(:user) { create(:user) } before(:each) { patch :update, ** new_values, id: user.id } context 'when valid' do let(:new_values) { attributes_for(:user) } it 'success' do expect(response).to be_success end it 'saves and assigns user to @user' do expect(assigns(:user)).to eq user end it 'saves updates' do expect { user.reload }.to change { user.nick }.to(new_values[:nick]) end end context 'when invalid' do let(:new_values) { attributes_for(:invalid_user) } it 'fails' do expect(response).not_to be_success end it 'assigns user to @user' do expect(assigns(:user)).to eq user end end end describe '#destroy' do context 'when requested user exists' do let(:user) { users[rand 4] } before(:each) { delete :destroy, id: user.id } it 'success' do expect(response).to be_success end it 'removes user form DB' do expect(User.all).not_to include user expect { user.reload }.to raise_exception ActiveRecord::RecordNotFound end end context 'when requested user does not exists' do it 'throws ActiveRecord::RecordNotFound' do expect { delete :destroy, id: -1 }.to raise_exception ActiveRecord::RecordNotFound end end end end </code></pre> <p>Here is <a href="http://pastebin.com/6f1UeX2h">controller</a>, <a href="http://pastebin.com/5X7h0Zye">model</a> and <a href="http://pastebin.com/8GFBiV0C">factory</a> if you need them</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:45:27.233", "Id": "79129", "Score": "0", "body": "looks pretty to good to me, but you could start by indenting with 2 spaces :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:50:39.017", "Id": "79131", "Score": "0", "body": "@tokland Actually I use tabs (one tab for each level) I don't know why tabs ware converted to spaces" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:57:41.503", "Id": "79142", "Score": "1", "body": "@atomAltera They have to be spaces (and not tabs). But only 2 as tokland says" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:32:22.647", "Id": "79298", "Score": "0", "body": "OK, you're right, code updated" } ]
[ { "body": "<p>It looks really good to me. All I have a very minor quibbles/suggestions.</p>\n\n<p>Since you're using FactoryGirl, you should be able to use <code>create_list :user, 4</code> instead of the <code>4.times.map { ... }</code> block</p>\n\n<p>You might as well check that a new record <code>be_kind_of User</code>. Just checking if it's an ActiveRecord is a little loose.</p>\n\n<p>You don't need to create many users for some of these tests (like <code>#show</code> and <code>#destroy</code>). It's fine to do so of course, but the more tests you accumulate the faster you'll want your tests to be. And fully creating several records may be a bottleneck, especially for something like user models that likely have a uniqueness validation. That'll cause Rails to perform extra queries (one to check if the record is unique, and another to insert it in the DB).</p>\n\n<p>Lastly, try running rspec with the <code>--format documentation</code> option, if you're not already. It'll format the output like so</p>\n\n<pre><code>UsersController\n #index\n assigns all users to @users\n success\n #show\n ...\n</code></pre>\n\n<p>which I personally prefer because it reads well (and, as the name implies, documents stuff). But for that same reason, you may want to change <code>success</code> to <code>succeeds</code> and <code>when valid</code> to something like <code>with valid params</code> just so you get nicer sentences.</p>\n\n<p>Again, this is all really minor stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T10:17:00.883", "Id": "79952", "Score": "0", "body": "Thank you very much! Can I ask you to help me with authorization/permissions testing? I can't find anything about it. Can you supply me some useful articles, or code samples?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T13:47:15.477", "Id": "79965", "Score": "1", "body": "@atomAltera It really depends on how you've got it set up. If you're using Devise, [there are some ready-made helpers](https://github.com/plataformatec/devise/wiki/How-To:-Controllers-tests-with-Rails-3-(and-rspec)). You can also use rspec stub/mock classes or methods to always return an admin user, or a `nil` user, or whatever, and see how stuff behaves. You'll also want to handle some of this in your higher-level feature specs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T16:27:10.793", "Id": "84336", "Score": "0", "body": "how you look at such [controller's testing fashion](http://pastebin.com/7s9JKw6S), this is just a draft, and it seems a little ugly, but I think you get an idea. I'm just trying DRYful style" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:18:01.013", "Id": "45501", "ParentId": "45379", "Score": "4" } } ]
{ "AcceptedAnswerId": "45501", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:10:07.967", "Id": "45379", "Score": "8", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "My first controller rspec test" }
45379
<p>I have written the following code as the level rendering part of a game engine I am writing. I am very happy how it works but as it is the background / level graphics made up of individual blocks it needs to be quick.</p> <p>What it does it look take the graphics from a resource loaded elsewhere and scales it onto the block if it is in the viewing window.</p> <p><code>Blocksize</code> is the size of the blocks and can be increased of decreased and is used to scale the blocks to give the Zoom in and out effect.</p> <p>How can I improve this code both in terms of speed and shorten it to improve readability?</p> <pre><code>public void render(Graphics g){ //Ensure player co-ords updated camerax=playerx-(gamewidth/2); cameray=playery-(gameheight/2); int blockwidth=blocksize-2; //Draw coloured blocks int screenx=-(int)camerax-blocksize; for (int x=0;x&lt;sizex;x++){ screenx+=blocksize; if (screenx&gt;-blocksize &amp;&amp; screenx&lt;gamewidth){ int screeny=-(int)cameray-blocksize; for (int y=0;y&lt;sizey;y++){ screeny+=blocksize; if (screeny&gt;-blocksize &amp;&amp; screeny&lt;gameheight){ if (tiles[x][y][0]&gt;0){ g.drawImage(levelgraphics, screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null); } else { g.setColor(new Color( tiles[x][y][1])); g.fillRect(screenx,screeny,blockwidth,blockwidth); g.setColor(Color.WHITE); g.drawString(String.valueOf(x+y*sizex), screenx+5,screeny+20); } } } } } //world - camera = screen, algebra that world = screen + camera //Add camerax to mouse screen co-ords to convert to world co-ords. int cursorx_world=(int)camerax+(int)GameInput.mousex; int cursorx_grid=(int)cursorx_world/blocksize; // World Co-ords / gridsize give grid co-ords int cursorx_screen=-(int)camerax+(cursorx_grid*blocksize); //Add cameray to mouse screen co-ords to convert to world co-ords. int cursory_world=(int)cameray+(int)GameInput.mousey; int cursory_grid=(int)cursory_world/blocksize; int cursory_screen=-(int)cameray+(cursory_grid*blocksize); //Draw on screen cursor if (cursorx_grid&gt;=0 &amp;&amp; cursory_grid&gt;=0 &amp;&amp; cursorx_grid&lt;sizex &amp;&amp; cursory_grid&lt;sizey){ //if (detect(cursorx_grid,cursory_grid)){ //if (tiles[cursorx_grid][cursory_grid][0]&gt;1){ g.setColor(Color.yellow); g.drawRect(cursorx_screen,cursory_screen,blockwidth,blockwidth); //} } //Draw on screen map for (int x=0;x&lt;sizex;x++){ for (int y=0;y&lt;sizey;y++){ g.setColor(new Color((int) tiles[x][y][1])); g.fillRect(mapx+x*mapsize, mapy+y*mapsize, mapsize, mapsize); } } //Outline g.drawRect(mapx,mapy,mapsize*sizex ,mapsize*sizey ); //Map location box g.setColor(Color.RED); g.drawRect(mapx+mapsize*((int)camerax/blocksize),mapy+mapsize*((int)cameray/blocksize),(gamewidth/blocksize)*mapsize ,(gameheight/blocksize)*mapsize ); } </code></pre> <p>The last bit of the code adds a map onto the screen and pops a scaled box on it so players can see what part of the map they are looking at.</p>
[]
[ { "body": "<p>Three things I noticed: </p>\n\n<ol>\n<li><p>Generally speaking, when you have a for with a gigantic if composing the contents of the for, it is because you're checking for a condition in order to do something. If this condition is related to what you're iterating on, then you can modify the for loop to guarantee that the condition is true.</p>\n\n<p>Without knowing precisely how your code works, I don't feel comfortable trying to fix it myself, however if done properly, you shouldn't need to contain that gigantic inner if. </p></li>\n<li><p>You're cycling the entire matrix twice. This is inefficient and shouldn't be done unless you require information that can only be obtained by having passed all data at least once (for example matrix value sum). If you're worried this will clutter your code further, then see the point below.</p></li>\n<li><p>Separate each drawing task into its own method. This separation of tasks makes it easier to maintain and read, as you don't need to be looking at code for drawing the map location box if you're trying to fix a problem related to drawing the coloured blocks.</p>\n\n<p>In the case of a nested loop such as when you cycle through all matrix items, you should place the entire loop inside its own method, and for each draw operation to be performed for each block, call its own method passing whatever information you'd need.</p></li>\n</ol>\n\n<p>I hope that helps. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:49:36.530", "Id": "45387", "ParentId": "45381", "Score": "6" } }, { "body": "<h2>White spaces are free, use them</h2>\n\n<p>Your code is hard to read as all operators are cramped together.</p>\n\n<h2>Avoid branches</h2>\n\n<p>A missed branch prediction can force your CPU to discard all speculative execution it has done. Although modern CPU's are pretty good at branch prediction, it's a good practice to avoid branches when possible. And in your case it will reduce iterations in the loop.</p>\n\n<pre><code>int screenx = -(int)camerax - blocksize;\nfor (int x = 0; x &lt; sizex; x++){\n screenx += blocksize;\n if (screenx &gt; -blocksize &amp;&amp; screenx &lt; gamewidth){\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>int screenx = -(int)camerax - blocksize;\nint xstart = Math.max(0, -(blocksize + screenx) / blocksize);\nint xend = Math.min(sizex, (gamewidth - screenx) / blocksize);\nscreenx += blocksize * xstart; // Edit: We need to keep this value updated too.\nfor (int x = xstart; x &lt; xend; ++x){\n screenx += blocksize;\n</code></pre>\n\n<p>and similarly for the inner loop. Depending on the ratio camera size to level size (if I'm interpreting your code correctly) this can give a big speedup.</p>\n\n<p><strong>Hint:</strong> The y direction iteration start and end values are independent of the current iteration in x direction so calculate the yend and ystart before entering the first loop.</p>\n\n<p><strong>Caution:</strong> The above <code>xstart</code> and <code>xend</code> may be off-by-one as I don't know what all the variables are, adjust to taste.</p>\n\n<p><strong>Edit:</strong> Oops just realized this is what Neil mentioned in the first point on his answer. But I'll leave this here as it's an example of what he said.</p>\n\n<p><strong>Edit2:</strong> Missed the incrementation of <code>screenx</code> prior to entering the loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:39:15.607", "Id": "45426", "ParentId": "45381", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T08:15:30.847", "Id": "45381", "Score": "8", "Tags": [ "java", "game" ], "Title": "Blocktastic optimisation" }
45381
<p>I have two lists of the same type and I want to be able view a list of both lists:</p> <pre><code> public List&lt;Page&gt; HeaderPages; public List&lt;Page&gt; SurveyPages; public IReadOnlyList&lt;Page&gt; AllPages { get { List&lt;Page&gt; allPages = new List&lt;Page&gt;(); allPages.AddRange(this.HeaderPages); allPages.AddRange(this.SurveyPages); return allPages; } } </code></pre> <p>I think it is very inefficient to keep creating a new list object each time I want to get <code>AllPages</code>, so I thought I could store a private <code>allPages</code> list. But then I thought if I am in the class, I would have to remember to use the public <code>AllPages</code> rather than the private <code>allPages</code> - which may not be up-to-date.</p> <p>Any elegant solutions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:06:00.923", "Id": "79132", "Score": "0", "body": "Can you post an example of some code which demonstrates the problem? You're asking us to review a hypothetical class which contains a private allPages list, and a hypothetical method which finds it difficult to remember whether to reference allPages or AllPages ... but it's difficult to understand hypothetical (non-existent) code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:14:25.433", "Id": "79231", "Score": "0", "body": "I don't know C# enough to write an answer, but what if everytime the get was called you saved the result in an instance variable and set something like \"changed = false\" alse as an instance variable. Whenever get is called, if changed is false just return your cached list. Then anything in the class that changed the other two lists sets changed to true." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:45:57.547", "Id": "79342", "Score": "0", "body": "Do you actually need to optimise this? How often do you call the getter?" } ]
[ { "body": "<p>As you said, keep another List which will contains all the elements and when you add an element inside one of the two update the internal List ... you could make List private and make helper method which update the main list and the internal List.</p>\n\n<p>With your code anyway you will create a List every item it's called and I think it could lead to bugs if you keep the reference sonewhere and you except it's updated (it's isn't, will keep values of when is created) with the latest pages.</p>\n\n<p>Another way is to keep your approch but create the List only once and return it. Then you should find a way to let know to the class if one of the List changed, if changed update the list (clear and readd to avoid a new instance)</p>\n\n<p>I could add code example if you need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:14:35.753", "Id": "45389", "ParentId": "45386", "Score": "5" } }, { "body": "<p>If you have control over the design of the Page class, I would add a \"bool IsHeader\" property to it and keep one public list of all Page objects and add every Page object to that list. Instead of keeping several other lists that sort your Page objects, you can then perform searches on that master list instead for Page objects with certain properties, preferably with LINQ statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:12:42.910", "Id": "79152", "Score": "0", "body": "I think this is a really nice advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:11:46.630", "Id": "79164", "Score": "0", "body": "Even if he has control over `Page` class, how do you know both `HeaderPages` and `SurveyPages` are not non-empty?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:24:45.567", "Id": "79165", "Score": "2", "body": "I would do it completely without HeaderPages and SurveyPages, that's the whole point of my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T14:09:50.697", "Id": "79168", "Score": "1", "body": "I agree with this because it's a far more elegant solution, *however* if the OP is worried about the overhead of instantiating a single list, then doing O(n) operations on all data accesses might not be their favourite. They'd be wrong, of course, as n is almost certainly trivial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:07:32.973", "Id": "79356", "Score": "0", "body": "I do have control of the `Page` class. In the end I decided this method was best suited to my project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:43:08.643", "Id": "79408", "Score": "1", "body": "Why not use an `enum` instead of `bool`? This will allow easier modification in the future if more page types pop up?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:32:00.570", "Id": "45391", "ParentId": "45386", "Score": "13" } }, { "body": "<p>You can use lazy initialization to achieve the same:</p>\n\n<pre><code>private Lazy&lt;List&lt;Page&gt;&gt; _lazyPageList = new Lazy&lt;List&lt;Page&gt;&gt;(GetPageList);\n\npublic IReadOnlyList&lt;Page&gt; AllPages\n{\n get\n {\n return lazyPageList.Value;\n }\n}\n\nprivate List&lt;Page &gt;GetPageList(){\n List&lt;Page&gt; allPages = new List&lt;Page&gt;();\n allPages.AddRange(this.HeaderPages);\n allPages.AddRange(this.SurveyPages);\n return allPages;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:11:10.343", "Id": "79151", "Score": "0", "body": "And what good will it do? You will still have to update `AllPages` somehow when other collections change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:50:28.213", "Id": "79161", "Score": "0", "body": "What I understand from the original question the lists do not change. The idea is to avoid creating a new list everytime **AllPages** property is accessed. @chazjn doesn't want to create a member variable to store the result. Lazy class is best suited for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:57:16.637", "Id": "79162", "Score": "0", "body": "from question: \"I could store a private 'allPages' list, but then I thought if I am in the class I would have to remember to use the public 'AllPages' rather than the private 'allPages' - *which may not be up-to-date*.\" Introducing `Lazy` property does not solve this issue, it only adds extra complexity to the code. (you still create an extra field `_lazyPageList`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T06:38:55.790", "Id": "79306", "Score": "0", "body": "I agree with you that new changes will not be updated with lazy approach. However whether you use the linq extension or the code in the original post a new list will be created every time the property is accessed. A better approach would be to store the result temporarilty to a variable and update it only if the either of the list has changed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T07:19:39.353", "Id": "79310", "Score": "1", "body": "linq does not create new list. It creates new enumeration logic over existing collection(-s). To create a new list you'd have to call `ToList()` method." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:44:22.913", "Id": "45393", "ParentId": "45386", "Score": "3" } }, { "body": "<p>Two alternatives to <a href=\"https://codereview.stackexchange.com/a/45391/34757\">Hackworth's answer</a> if you don't have control of the Page class:</p>\n\n<ul>\n<li>Either, create two subclasses HeaderPage and SurveyPage, bother/either of which you can store in the <code>List&lt;Page&gt; AllPages</code></li>\n<li>Or, add a <code>Dictionary&lt;Page,bool&gt;</code> in which to remember the type of page (the 'type of page' is shown here as a <code>bool</code>, but could be an <code>enum</code>) for each page in your single <code>List&lt;Page&gt; AllPages</code></li>\n</ul>\n\n<p>Access to that dictionary could be defined as an extention method:</p>\n\n<pre><code>static class PageExtensions\n{\n // Or this could be a non-static member of your container class and passed\n // as a parameter into the GetPageType and SetPageType extension methods.\n static Dictionary&lt;Page, bool&gt; dictionary = new Dictionary&lt;Page, bool&gt;();\n\n public static bool? GetPageType(this Page page)\n {\n bool rc;\n return (dictionary.TryGetValue(page, out rc)) ? rc : null;\n }\n public static void SetPageType(this Page page, bool type)\n {\n dictionary[page] = type;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:41:49.297", "Id": "79407", "Score": "1", "body": "Bool means nothing in this context. I would change it to an `enum` that names the page type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:58:22.800", "Id": "79413", "Score": "0", "body": "I did say, \"could be an enum\" in the answer. Alternatively rename the associated extensions methods, e.g. to SetIsHeader instead of SetPageType." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T11:42:07.833", "Id": "45398", "ParentId": "45386", "Score": "1" } }, { "body": "<p>If you want to keep the two lists (otherwise check <strong>Hackworth</strong>'s answer), the best solution would be to use LINQ extensions</p>\n\n<pre><code>public IEnumerable&lt;Page&gt; AllPages \n{ \n get \n {\n return HeaderPages.Concat(SurveyPages);\n } \n}\n</code></pre>\n\n<p>This way you do not create any unnecessary collections. It forces you to use <code>IEnumerable&lt;Page&gt;</code> though, but in my opinion it is a good thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:45:52.843", "Id": "79216", "Score": "0", "body": "+1 The difference between IReadOnlyList and IEnumerable is (only) that IReadOnlyList also supports Count and Index properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:05:32.033", "Id": "79354", "Score": "0", "body": "Thanks, I really like this very clean solution and and will definitely try it out on other projects." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T12:06:01.677", "Id": "45400", "ParentId": "45386", "Score": "16" } }, { "body": "<p>What are people going to want to do with <code>AllPages</code>, and are they going to have any expectations about how it should behave if the underlying data changes?</p>\n\n<p>If the intention is that code which reads <code>AllPages</code> isn't going to use it after the next time anything changes, you could have each instance of your self create (or lazily create) an instance of <code>AllPageWrapper</code>, which holds a reference to its creator along with a \"change count\" and possibly the number of items in <code>HeaderPages</code>. Methods and properties of <code>AllPageWrapper</code> would ensure the wrapped object had not been modified, and would then use that wrapped object as a source of data. The indexed getter might look something like:</p>\n\n<pre><code>public Page this(int index)\n{ get\n {\n if (changeCount != parent.changeCount)\n throw InvalidOPerationException(...);\n if (index &gt; headerCount)\n return parent.SurveyPages(index-headerCount);\n else\n return parent.HeaderPages(index);\n }\n}\n</code></pre>\n\n<p>Such an approach would allow the <code>AllPages</code> property to simply return a wrapper object, without having to do any real \"work\". Code which needs a detached copy of the list could use use <code>thing.AllPages.ToList()</code>, but code which will need it only briefly need not bother.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:37:02.013", "Id": "45432", "ParentId": "45386", "Score": "0" } }, { "body": "<p>Have you profiled your code and determined that this call is problem? If not, do that before optimising anything.</p>\n\n<p>There is a general solution to problems like this, which is to use a <code>dirty</code> flag to track whether the return value is valid. To do this you will want to wrap all the cases when the header and survey pages can be modified in a manner that breaks the allpages list and have these calls set the <code>dirty</code> flag. Then replace your getter with something like this:</p>\n\n<pre><code>private List&lt;page&gt; allPages;\nprivate boolean dirty;\n\npublic IReadOnlyList&lt;Page&gt; AllPages \n{ \n get \n {\n if (dirty)\n {\n allPages = new List&lt;Page&gt;();\n allPages.AddRange(this.HeaderPages);\n allPages.AddRange(this.SurveyPages);\n }\n return allPages;\n } \n}\n</code></pre>\n\n<p>Unfortunately <code>dirty</code> flags can be error prone so tread with care.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:15:20.007", "Id": "79346", "Score": "1", "body": "There's a bug in the sample code: allPages names a local variable and a member. Also, if dirty would you prefer `allPages = new List<Page>();` or `allPages.Clear();`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:50:47.793", "Id": "79352", "Score": "0", "body": "@ChrisW I would say just create a new list and let the old one get collected. If you try to do the Clear, you need to check to see if the allPages is initialized first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:02:05.347", "Id": "79377", "Score": "0", "body": "@ChrisW: Thanks, I've fixed that bug. I don't know which is more efficient in C#, you'd have to time it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:51:52.443", "Id": "45485", "ParentId": "45386", "Score": "3" } } ]
{ "AcceptedAnswerId": "45391", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T09:27:24.230", "Id": "45386", "Score": "10", "Tags": [ "c#", "properties" ], "Title": "Inefficient code inside of getter?" }
45386
<p>I have a piece of code which grabs data from an SQL database and displays it in a DataGridView. This code works perfectly fine for me.</p> <p>It has been pointed out to me that the below code is bad programming:</p> <pre><code>Imports System.Data.SqlClient Public Class Form1 Dim dbConnection As SqlConnection Dim dbCommand As SqlCommand Dim dbAdapter As SqlDataAdapter Dim DataSet As New DataSet Dim strSQL As String Dim dbCount As String Public Sub SQLConnect() dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True") dbConnection.Open() End Sub Public Sub SQLCommand() dbCommand = New SqlCommand(strSQL, dbConnection) End Sub Public Sub SQLAdapter() dbAdapter = New SqlDataAdapter(strSQL, dbConnection) End Sub Public Sub SQLDisconnect() dbConnection.Close() End Sub Public Sub DGVLoad() Try SQLConnect() strSQL = "SELECT * FROM [Products]" SQLAdapter() DataSet.Clear() dbAdapter.Fill(DataSet) SQLDisconnect() DataGridView1.DataSource = DataSet.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load DGVLoad() End Sub </code></pre> <p>Could someone explain to me why what I am doing is bad practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:27:18.777", "Id": "79136", "Score": "0", "body": "It's hard to believe that `\"SELECT [item] FROM [table] WHERE ([item] = 'value')\"` is real code from a real project. How/where is the value of `'value'` specified in the real code? Could you post real code instead of example code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:33:21.787", "Id": "79137", "Score": "0", "body": "Of course the SQL statement it's not real code it was an example, I didn't think a simple SELECT statement would be the problem. I have no problems with the SQL statements to which I am grabbing the information. All this code works perfectly for me, but it was also pointed out to me that the code above portrays bad programming patterns and unmaintainable code. I just wanted someone to show me and explain to me how that is the case. I will edit the select statement to make it understandable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:41:38.660", "Id": "79140", "Score": "1", "body": "The FAQ about on- and off-topic questions asks, [Is it actual code from a project rather than pseudo-code or example code?](http://codereview.stackexchange.com/help/on-topic) -- Asking for a review of 'example code' code instead of 'actual code' is like asking a medical doctor to examine an 'example person' instead of an 'actual person'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:49:35.167", "Id": "79141", "Score": "0", "body": "I understand what you are saying, I do. But lets assume that this code works perfectly, to which it actually does. And I have edited the code above to reflect 'actual code' in the SQL statement, which is now does. Now like I said before, this code is working perfectly, nothing wrong with it for me what so ever. But can you see why or explain why how I have coded it with bad programming practice? I cant see why it is bad practice but the guys at StackOverflow seem to think it is and I was advised to post HERE to get an answer to why it is bad programming to get an answer." } ]
[ { "body": "<p>Three possible problems that I see.</p>\n\n<hr>\n\n<pre><code>dbConnection = New SqlConnection(\"Data Source=connectionhere\\sqlexpress;Initial Catalog=line_log;Integrated Security=True\")\n</code></pre>\n\n<p>You have a hard-coded connection string. If you want a different database location then you need to edit the code. Perhaps it's better to have the connection string in an editable config file.</p>\n\n<hr>\n\n<p>The <a href=\"https://stackoverflow.com/a/22636697/49942\">original version which prompted this review</a> ...</p>\n\n<pre><code>strSQL = \"SELECT [item] FROM [table] WHERE ([item] = 'value')\"\n</code></pre>\n\n<p>... seems to build the select statement by string manipulation of the <code>value</code> and therefore may be vulnerable to <a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">SQL injection</a>.</p>\n\n<hr>\n\n<p>You have SQL code and Form code in the same source file. It may be better to separate these into <a href=\"https://codereview.stackexchange.com/a/44643/34757\">different classes so that they can be tested and re-used independently</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T11:35:45.843", "Id": "79146", "Score": "0", "body": "Thank you very much I appreciate your answer, the hard coded string I have already changed, and as for the select statement I will look into parameterized queries instead. Thank you for your constructive feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T11:32:21.893", "Id": "45396", "ParentId": "45390", "Score": "2" } }, { "body": "<p>I'll try not to rehash what others have said already.</p>\n<ul>\n<li>Indentation matters. The harder it is to read the code, the harder it is to maintain. Everything inside of <code>Sub...End Sub</code> should be indented one level. (Whether that's one tab or four spaces, I don't care. Just one level.) The same goes for <code>Try...End Try</code>, <code>If...End If</code>, etc.</li>\n<li>All of your data access code is bound to a <em>Form</em>. Even if this is the only form in your entire project (which I doubt), the code to connect to your database doesn't belong here. It belongs in it's own class. Your form should only be concerned with interacting with the user. It shouldn't care or know how to connect to or query a database.</li>\n<li>Don't catch exceptions if you don't know what to do with them.</li>\n</ul>\n<blockquote>\n<pre><code>Catch ex As Exception\n</code></pre>\n</blockquote>\n<pre><code> MsgBox(ex.ToString)\n</code></pre>\n<p>Seriously, stop doing this. You should be as specific as possible about what exceptions you catch. As it is, you're catching potentially <em><strong>fatal</strong></em> exceptions that you probably can't do anything about.</p>\n<blockquote>\n<p>Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them. They almost always happen because the process is deeply diseased and is about to be put out of its misery. Out of memory, thread aborted, and so on. There is absolutely no point in catching these because nothing your puny user code can do will fix the problem. Just let your &quot;finally&quot; blocks run and hope for the best.</p>\n</blockquote>\n<p><a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/vexing-exceptions\" rel=\"nofollow noreferrer\"><em>Eric Lippert</em></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-09-23T03:03:33.587", "Id": "63641", "ParentId": "45390", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:19:08.707", "Id": "45390", "Score": "1", "Tags": [ "sql", "vb.net" ], "Title": "Selecting from a database into a DataGridView" }
45390
<p>Could you give any suggestion on the following unit tests? How to make it more readable, maintainable and trustworthy. If it is not a problem - post some code with the suggestions.</p> <pre><code>[TestClass] public class PropertyBagCompositeTests { private readonly IFixture fixture; private readonly Mock&lt;IPropertyBag&gt; secondPropertyBagMock; private readonly Mock&lt;IPropertyBag&gt; firstPropertyBagMock; private readonly string propertyName; private readonly int propertyValue; private readonly PropertyBagComposite cut; public PropertyBagCompositeTests() { fixture = new Fixture(); firstPropertyBagMock = new Mock&lt;IPropertyBag&gt;(); secondPropertyBagMock = new Mock&lt;IPropertyBag&gt;(); propertyName = Any&lt;string&gt;(); propertyValue = Any&lt;int&gt;(); cut = new PropertyBagComposite(new [] { firstPropertyBagMock.Object, secondPropertyBagMock.Object}); } [TestMethod] public void GetProperty_DelegatedToBags() { cut.PropertyGet(propertyName); firstPropertyBagMock.Verify(x =&gt; x.PropertyGet(propertyName), Times.Once()); secondPropertyBagMock.Verify(x =&gt; x.PropertyGet(propertyName), Times.Once()); } [TestMethod] public void GetProperty_NoBagHasProperty_ReturnsNull() { object result = cut.PropertyGet(propertyName); result.Should().BeNull(); } [TestMethod] public void GetProperty_OneBagHasPropety_ResturnsItsResult() { firstPropertyBagMock.Setup(x =&gt; x.PropertyGet(propertyName)).Returns(propertyValue); object result = cut.PropertyGet(propertyName); result.Should().Be(propertyValue); } [TestMethod] public void GetProperty_BothBagHasPropetyWithSameValue_ResturnsItsResult() { firstPropertyBagMock.Setup(x =&gt; x.PropertyGet(propertyName)).Returns(propertyValue); secondPropertyBagMock.Setup(x =&gt; x.PropertyGet(propertyName)).Returns(propertyValue); object result = cut.PropertyGet(propertyName); result.Should().Be(propertyValue); } [TestMethod] public void GetProperty_BothBagHasPropetyWithDifferentValue_ThrowsAmbiguousResultException() { firstPropertyBagMock.Setup(x =&gt; x.PropertyGet(propertyName)).Returns(propertyValue); var otherPropertyValue = Any&lt;double&gt;(); secondPropertyBagMock.Setup(x =&gt; x.PropertyGet(propertyName)).Returns(otherPropertyValue); Action action = () =&gt; cut.PropertyGet(propertyName); action.ShouldThrow&lt;AmbiguousResultException&gt;(); } [TestMethod] public void SetProperty_DelegatedToBags() { cut.PropertySet(propertyName, propertyValue); firstPropertyBagMock.Verify(x =&gt; x.PropertySet(propertyName, propertyValue), Times.Once()); secondPropertyBagMock.Verify(x =&gt; x.PropertySet(propertyName, propertyValue), Times.Once()); } [TestMethod] public void ListProperties_ReturnsAllProperties() { var duplicatedPropertyName = Any&lt;string&gt;(); var somePropertyName = Any&lt;string&gt;(); var anotherPropertyName = Any&lt;string&gt;(); firstPropertyBagMock.Setup(x =&gt; x.ListProperties()).Returns(new[] { duplicatedPropertyName, somePropertyName }); secondPropertyBagMock.Setup(x =&gt; x.ListProperties()).Returns(new[] { anotherPropertyName, duplicatedPropertyName }); string[] result = cut.ListProperties(); result.Should().Contain(new[] { duplicatedPropertyName, somePropertyName, anotherPropertyName }); } [TestMethod] public void ListProperties_ReturnsDistinct() { var duplicated = Any&lt;string&gt;(); firstPropertyBagMock.Setup(x =&gt; x.ListProperties()).Returns(new[] { duplicated, Any&lt;string&gt;() }); secondPropertyBagMock.Setup(x =&gt; x.ListProperties()).Returns(new[] { Any&lt;string&gt;(), duplicated }); string[] result = cut.ListProperties(); result.Count(x =&gt; x == duplicated).Should().Be(1); } private T Any&lt;T&gt;() { return fixture.Create&lt;T&gt;(); } } </code></pre> <p>Code Under Test:</p> <pre><code>internal class PropertyBagComposite : IPropertyBag { private readonly IEnumerable&lt;IPropertyBag&gt; propertyBags; public PropertyBagComposite(IEnumerable&lt;IPropertyBag&gt; propertyBags) { Require.NotNull(propertyBags, "propertyBags"); this.propertyBags = propertyBags; } public object PropertyGet(string propertyName) { object result = null; foreach (object newItem in propertyBags.Select(x =&gt; x.PropertyGet(propertyName))) { if (result == null) { result = newItem; } else if (newItem != null &amp;&amp; !result.Equals(newItem)) { throw new AmbiguousResultException(); } } return result; } public void PropertySet(string propertyName, object propertyValue) { propertyBags .ForEach(x =&gt; x.PropertySet(propertyName, propertyValue)); } public string[] ListProperties() { string[] result = propertyBags .SelectMany(x =&gt; x.ListProperties()) .Distinct() .ToArray(); return result; } } </code></pre>
[]
[ { "body": "<p>It's pretty clean. In my oppinion, test parameters should be setup in each test, and not during setup. Setup is for setting up infrastructure bits. You should be able to take advantage of AutoFixture AutoMocking customization to make your tests more resiliant to change (let autofixture create your sut, so adding future dependencies won't break your valid tests).</p>\n\n<pre><code> firstPropertyBagMock.Verify(x =&gt; x.PropertySet(propertyName, propertyValue), Times.Once());\n</code></pre>\n\n<p>The times.once() is kind of redundant, as this is the default.</p>\n\n<p>Assertion like this:</p>\n\n<pre><code>result.Count(x =&gt; x == duplicated).Should().Be(1);\n</code></pre>\n\n<p>Can be rewritten a bit cleaner (Will have a better message on fail:</p>\n\n<pre><code>result.Where(x =&gt; x == duplicated).Should().HaveCount(c =&gt; c == 1)\n</code></pre>\n\n<p>Otherwise, you can achieve a bit more readability by creating a common base class to help with your tests, one I use (Uses rhino mocks, but gives you the idea):</p>\n\n<p>public abstract class AutoFixtureBaseTest : AutoFixtureBaseTest where TSut : class {}</p>\n\n<pre><code>[TestFixture]\npublic abstract class AutoFixtureBaseTest&lt;TSut, TContract&gt;\n where TSut : class, TContract\n where TContract : class\n{\n protected IFixture Fixture { get; private set; }\n\n [SetUp]\n protected virtual void Initialize()\n {\n Fixture = new Fixture().Customize(new AutoRhinoMockCustomization());\n Fixture.Behaviors.Add(new OmitOnRecursionBehavior());\n Fixture.Customize&lt;TSut&gt;(x =&gt; x.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));\n } \n\n public T Dep&lt;T&gt;()\n {\n return Fixture.Freeze&lt;T&gt;();\n }\n\n public T Fake&lt;T&gt;(Func&lt;ICustomizationComposer&lt;T&gt;, IPostprocessComposer&lt;T&gt;&gt; builder)\n {\n return builder(Fixture.Build&lt;T&gt;()).Create();\n }\n\n public T Fake&lt;T&gt;()\n {\n return Fixture.Create&lt;T&gt;();\n }\n\n public void Chain&lt;TParent, TChild&gt;(Function&lt;TParent, TChild&gt; expression) where TParent : class where TChild : class\n {\n Dep&lt;TParent&gt;().Stub(expression).Return(Dep&lt;TChild&gt;());\n }\n\n public IEnumerable&lt;T&gt; FakeMany&lt;T&gt;(Func&lt;ICustomizationComposer&lt;T&gt;, IPostprocessComposer&lt;T&gt;&gt; builder)\n {\n return builder(Fixture.Build&lt;T&gt;()).CreateMany();\n }\n\n public IEnumerable&lt;T&gt; FakeMany&lt;T&gt;()\n {\n return Fixture.CreateMany&lt;T&gt;();\n }\n\n public TContract Sut\n {\n get\n {\n return Fixture.Freeze&lt;TSut&gt;();\n }\n }\n}\n</code></pre>\n\n<p>With this setup and configuration, most times you only need to setup the specific cases for each test.</p>\n\n<p>EDIT: Quick example of how to convert your code to use automocking:</p>\n\n<p>Take this section of code from your example:</p>\n\n<pre><code>public PropertyBagCompositeTests()\n {\n fixture = new Fixture();\n firstPropertyBagMock = new Mock&lt;IPropertyBag&gt;();\n secondPropertyBagMock = new Mock&lt;IPropertyBag&gt;();\n propertyName = Any&lt;string&gt;();\n propertyValue = Any&lt;int&gt;();\n cut = new PropertyBagComposite(new [] { firstPropertyBagMock.Object, secondPropertyBagMock.Object});\n }\n</code></pre>\n\n<p>You're particular example, is somewhat complicated by the fact you are injecting an IEnumerable, for that you have to explicitly register:</p>\n\n<pre><code>public PropertyBagCompositeTests()\n {\n fixture = new Fixture().Customize(new AutoMoqCustomization());\n propertyBags = fixture.CreateMany&lt;Mock&lt;IPropertyBag&gt;&gt;();\n fixture.Register&lt;IEnumerable&lt;IPropertyBag&gt;&gt;(() =&gt; propertyBags.Select(x =&gt; x.Object));\n\n propertyName = Any&lt;string&gt;();\n propertyValue = Any&lt;int&gt;();\n cut = fixture.Freeze&lt;PropertyBagComposite&gt;();\n }\n</code></pre>\n\n<p>A more common example, and a good reference point:\n<a href=\"http://blog.ploeh.dk/2010/08/19/AutoFixtureasanauto-mockingcontainer/\">http://blog.ploeh.dk/2010/08/19/AutoFixtureasanauto-mockingcontainer/</a></p>\n\n<p>Using the base class similar to what I mentioned, you can do things like:</p>\n\n<pre><code>public class MyObjectSpecification : AutoFixtureBaseTest&lt;MyClass, IMyClass&gt; {\n [TestMethod]\n public void Should_do_something_with_dependency(){\n var expected = Fake&lt;Something&gt;();\n Dep&lt;IDependency&gt;(x =&gt; x.Setup(dep =&gt; dep.DoSomething()).Returns(expected).Verifiable());\n var result = Sut.DoSomethingWithDependency();\n result.Should().Be(expected);\n Verify&lt;IDependency&gt;();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:27:59.710", "Id": "79349", "Score": "0", "body": "Could you post me some code how to take advantage of AutoFixture AutoMocking customization? I am just starting using this library" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:22:31.390", "Id": "45407", "ParentId": "45392", "Score": "9" } } ]
{ "AcceptedAnswerId": "45407", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:33:30.267", "Id": "45392", "Score": "7", "Tags": [ "c#", "unit-testing", "moq", "fluent-assertions" ], "Title": "Unit tests using C#, Moq, AutoFixture, FluentAssertions" }
45392
<p>I have this code which runs when an Async HTTP call is made on a <code>HorizontalScrollView</code></p> <pre><code> //These 3 defined outside of the method ObjectAnimator animatorR = null; ObjectAnimator animatorL = null; boolean loop = true; Inside the method if (animatorL != null) animatorL.cancel(); animatorL = null; if (animatorR != null) animatorR.cancel(); animatorR = null; HorizontalScrollView sv = (HorizontalScrollView) findViewById(R.id.scroll_view); loop = true; sv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { animatorL.cancel(); animatorR.cancel(); loop = false; sv.setOnTouchListener(null); return false; } }); animatorR = ObjectAnimator.ofInt(sv, "scrollX", sv.getMaxScrollAmount()).setDuration(4000); animatorL = ObjectAnimator.ofInt(sv, "scrollX", 0).setDuration(4000); animatorR.removeAllListeners(); animatorR.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { Log.d("AnimR", "Ended"); if (loop &amp;&amp; animatorL != null) animatorL.start(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); animatorR.start(); animatorL.removeAllListeners(); animatorL.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { Log.d("AnimL", "Ended"); if (loop &amp;&amp; animatorR != null) animatorR.start(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } </code></pre> <p>This is my first time using Animators and the code seems very clunky. Where could I make improvements to this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:58:22.790", "Id": "79167", "Score": "1", "body": "Hi, welcome to CodeReview.SE. Can you please provide the whole class or whatever this snippet was supposed to be in ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:01:40.023", "Id": "79180", "Score": "0", "body": "will you please look at the code and make sure that your indentation is correct? it looks like you have an `if` statement that is out of alignment" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:05:08.447", "Id": "79261", "Score": "0", "body": "@Josay the code this from is about 1000 lines long, I just cut out the part I wanted looking at at the moment, should I post all of it? @ Malachi yeah ones out of line when I copied it here, it's inline in the actual file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:53:10.900", "Id": "79442", "Score": "0", "body": "You don't need to post the whole file. I see a couple of potential improvements. I will write up an answer either later today or tomorrow!" } ]
[ { "body": "<p>The biggest change I can see here would be to extract a class out of the two anonymous inner classes. The two variations are exactly the same except for which <code>ObjectAnimator</code> they should call next, and which logging tag to use. So let's extract a class and pass those values to its constructor: (Place the code below inside the same class as you are using right now)</p>\n\n<pre><code>private class MyAnimListener implements Animator.AnimatorListener {\n private ObjectAnimator other;\n private final String logMessage;\n\n public MyAnimListener(String logMessage, ObjectAnimator startOther) {\n this.logMessage = logMessage;\n this.other = startOther;\n }\n\n @Override\n public void onAnimationStart(Animator animation) {\n }\n\n @Override\n public void onAnimationEnd(Animator animation) {\n Log.d(logMessage, \"Ended\");\n if (loop &amp;&amp; other != null) \n other.start();\n }\n\n @Override\n public void onAnimationCancel(Animator animation) {\n }\n\n @Override\n public void onAnimationRepeat(Animator animation) {\n }\n} \n</code></pre>\n\n<p>You could then use this code to add the listeners:</p>\n\n<pre><code>animatorR.addListener(new MyAnimListener(\"AnimR\", animatorL));\nanimatorL.addListener(new MyAnimListener(\"AnimL\", animatorR));\n</code></pre>\n\n<p>However, if your two <code>animator</code> instances often switch to/from null, I would think about what it actually is that you are trying to achieve. (Honestly I'm not sure what you are trying to do, which can make this a bit of an <a href=\"https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem\">X-Y problem</a>). </p>\n\n<p>If you really really want the two animator instances to switch to/from null, then you will have to use two variables for the <code>MyAnimListener</code> and modify its <code>ObjectAnimator other</code> field, something like this:</p>\n\n<pre><code> // Variable declarations\nanimRListener = new MyAnimListener(\"AnimR\", animatorL);\nanimatorR.addListener(animRListener);\nanimLListener = new MyAnimListener(\"AnimL\", animatorR);\nanimatorL.addListener(animLListener);\n\n// Later on\nanimatorR = null;\nanimLListener.other = null;\n</code></pre>\n\n<p>Besides this, I actually think your code might be cleaner than it looks, if that makes any sense...</p>\n\n<hr>\n\n<p>I would recommend using the same <code>tag</code> parameter for all <code>Log</code> calls throughout your entire map. The Logcat utility can filter on a specific tag, by using it like this:</p>\n\n<pre><code>adb -d logcat YourTag:D YourOtherTag:D System.err:W *:S\n</code></pre>\n\n<p>I usually use something like this to be informed about both my own tags, stack traces from applications gone mad, and some other more or less useful Android messages:</p>\n\n<pre><code>adb -d logcat MyTag:D MyOtherTag:D MyThirdTag:D dalvikvm:I AndroidRuntime:E ResourceType:W PackageManager:I System.err:W *:S\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T08:27:48.090", "Id": "79945", "Score": "0", "body": "Thanks for the reply :). The reason they're going to null at the moment is because I had a problem with looping, when that block of code ran for the second time (And third etc...) the animation would happen twice, I tried using `.cancel()` but it didn't seem to fix it, but setting it to null did." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T16:18:19.183", "Id": "45632", "ParentId": "45402", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:05:30.457", "Id": "45402", "Score": "6", "Tags": [ "java", "android" ], "Title": "Animated ScrollView" }
45402
<p>I have a RoR 4 app, and its model have these associations:</p> <pre><code>has_many :accreditations has_one :legal, -&gt; { where(kind_cd: Accreditation.legal) }, class_name: 'Accreditation' has_many :departments, -&gt; { where(kind_cd: Accreditation.department) }, class_name: 'Accreditation' </code></pre> <p>So, you see that these associations similar, but <code>legal</code> &amp; <code>departments</code> have more conditions than <code>accreditations</code>. Can I replace <code>class_name: 'Accreditation'</code> with something like <code>using :accreditations</code>?</p>
[]
[ { "body": "<p>I don't see what you will gain with your hypothetical <code>using</code> syntax, let's say there is one... your code will look like this:</p>\n\n<pre><code>has_many :accreditations\nhas_one :legal, -&gt; { where(kind_cd: Accreditation.legal) }, using: :accreditations\nhas_many :departments, -&gt; { where(kind_cd: Accreditation.department) }, using: :accreditations\n</code></pre>\n\n<p>How is it better than your current code? It is not more expressive, nor is it more succinct, nor DRY.</p>\n\n<p>Also, these associations are similar to some extent, but they look as DRY as you can make them - one is <code>has_one</code>, while the others are <code>has_many</code>, one uses the default idiom, while the others have names different than the associated class, conditions are different (and though one might argue you can predict the filter by the association name, one is singular, and the other is plural...)</p>\n\n<p>In short, I think your current code is good enough - any change will only harm readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T05:31:09.650", "Id": "79302", "Score": "0", "body": "Uri, but if I make two queries like\n`@accreditations = @contractor.accreditations;@legal = @contractor.accreditations`\nI'll get second query faster because it will use cache from first query, isn't it?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:46:57.593", "Id": "45428", "ParentId": "45405", "Score": "3" } }, { "body": "<p>There are two ways to tackle this situation. One of them is what you did: follow the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">Law of Demeter</a>; I don't have any advice to improve your code. The second way is move the logic to the other model. In that case you'd write:</p>\n\n<pre><code>class Company\n has_many :accreditations\nend\n\nclass Accreditation\n scope :departments, where(kind_cd: department)\n\n def self.legal\n where(kind_cd: legal).first\n end\nend\n</code></pre>\n\n<p>Both are ok even though I prefer the second because the logic of departments/legal is within the accreditation model.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T19:53:33.047", "Id": "45437", "ParentId": "45405", "Score": "4" } } ]
{ "AcceptedAnswerId": "45428", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:20:12.803", "Id": "45405", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails refactoring has_many" }
45405
<p>I want users to enter their code into my blog and keep original styling tags intact. So I had to develop a function that extracts user's code (between two tags) and convert special characters to HTML entities, then remove unwanted tags using <code>purifyHTML</code>.</p> <p>I want to know if it is safe to use it like that, and if there are any bad issues with this function.</p> <pre><code>public function extracter($string, $start, $end){ function get_string_between($string, $start, $end){ $delimiters = array(); $ini = strpos($string,$start); if ($ini == 0) return FALSE; $delimiters['start'] = substr($string, 0, $ini); $ini += strlen($start); $last = strpos($string,$end,$ini); $len = $last - $ini; $delimiters['inside'] = substr($string,$ini,$len); $delimiters['end'] = substr($string, $last+strlen($end)); return $delimiters; } function reconstruct($strings = array(), $filter){ if( count($strings) == 0 || !$strings ) return false; $count = count($strings); $i = 0; $str = ''; $code = array(); $uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using foreach ($strings as $key =&gt; $val) { $i++; foreach ($val as $k =&gt; $v) { if( $k == 'start' ) $str .= $v; if( $k == 'inside' ){ $str .= '['.$uniq.$i.']'; //creat a token in the string $code[$i] = htmlspecialchars($v); } if( $i == $count ) if( $k == 'end' ) $str .= $v; } } $purify = $filter-&gt;purifyHtml($str);//i'm using purifyhtml to remove undesirable tags and leave TinyMce tags for ($j=1; $j &lt;= $i; $j++) { $purify = str_replace('['.$uniq.$j.']', $code[$j], $purify); //replace the token with the escaped code } return $purify; } /* main */ $string = " ".$string; $components = array(); $exists = TRUE; while ( $exists ) { $st = get_string_between($string, $start, $end);//decompose if token found if( !$st ) return $string;// return the original string if nothing found $string = $st['end']; $components[] = $st; $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string } return reconstruct($components, $this-&gt;InputFilter); } </code></pre>
[]
[ { "body": "<p>\"Extracter\" <a href=\"https://books.google.com/ngrams/graph?content=extracter%2C+extractor\" rel=\"nofollow\">should be spelled \"extractor\"</a>.</p>\n\n<p>It's nice that you broke up the functionality into smaller functions.</p>\n\n<hr>\n\n<p>In <code>get_string_between()</code>, you don't appear to be properly handling the <code>$start</code> and <code>$end</code> strings not being found. Consider:</p>\n\n<pre><code>$ini = strpos($string,$start);\nif ($ini == 0) return FALSE;\n</code></pre>\n\n<p>Did you mean to write</p>\n\n<pre><code>if ($ini === FALSE) return FALSE;\n</code></pre>\n\n<p>instead? <a href=\"http://php.net/strpos\" rel=\"nofollow\"><code>strpos()</code></a> is tricky, in that you have to carefully distinguish between 0 and <code>FALSE</code> return values.</p>\n\n<p>For <code>$last = strpos($string,$end,$ini)</code>, you don't check the return value at all, and just use it.</p>\n\n<hr>\n\n<p>Flag variables are an ineffective way to control execution flow. If possible, restructure the code to avoid them. For example,</p>\n\n<pre><code>$components = array();\n$exists = TRUE;\nwhile ( $exists ) {\n $st = get_string_between($string, $start, $end);//decompose if token found\n if( !$st )\n return $string;// return the original string if nothing found\n $string = $st['end'];\n $components[] = $st; $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string\n}\n</code></pre>\n\n<p>… should be written as an equivalent do-while loop:</p>\n\n<pre><code>$components = array();\ndo {\n $st = get_string_between($string, $start, $end);//decompose if token found\n if( !$st )\n return $string;// return the original string if nothing found\n $string = $st['end'];\n $components[] = $st;\n} while (strpos($st['end'], $start) !== FALSE); //check if another code exists in the string\n</code></pre>\n\n<p>However, even that is dissatisfying, since the <code>strpos()</code> test is redundant with the <code>strpos()</code> operation within <code>get_string_between()</code>.</p>\n\n<pre><code>$components = array();\nwhile (($st = get_string_between($string, $start, $end))) {\n $components[] = $st;\n $string = $st['end'];\n}\nreturn empty($components) ? $string // return the original string if nothing found\n : reconstruct($components, $this-&gt;InputFilter);\n</code></pre>\n\n<hr>\n\n<p>In <code>reconstruct()</code>, your loops are too complex. The original code…</p>\n\n<pre><code>$count = count($strings);\n$i = 0;\n$str = '';\n$code = array();\n$uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using\nforeach ($strings as $key =&gt; $val) {\n $i++;\n foreach ($val as $k =&gt; $v) {\n if( $k == 'start' )\n $str .= $v;\n if( $k == 'inside' ){\n $str .= '['.$uniq.$i.']'; //creat a token in the string\n $code[$i] = htmlspecialchars($v);\n }\n if( $i == $count )\n if( $k == 'end' )\n $str .= $v;\n }\n}\n</code></pre>\n\n<p>… could be simplified to</p>\n\n<pre><code>$str = '';\n$code = array();\n$uniq = uniqid();\nforeach ($strings as $i =&gt; $component) {\n $str .= $component['start'];\n $str .= \"[$uniq\" . ($i + 1) . \"]\"; // Create a token in the string\n $code[$i + 1] = htmlspecialchars($component['inside']);\n}\n$str .= $component[count($component) - 1]['end'];\n</code></pre>\n\n<p>It's unconventional that <code>$code</code> is a 1-based array, and there doesn't seem to be any advantage to starting from 1 rather than 0, so just use <code>$i</code> instead of <code>$i + 1</code> everywhere. Just adjust <code>$j</code> accordingly.</p>\n\n<hr>\n\n<p>Nobody likes to read low-level string manipulation code, especially when it's not clear what the code is supposed to do. Now that I've understood it, I would write a comment on the function like this:</p>\n\n<pre><code>/**\n * Runs HTML purifier on $string. Sections of the string between $start\n * and $end delimiters are taken literally: instead of being filtered through\n * the HTML purifier, they are escaped using htmlspecialchars() instead.\n * The $start and $end delimiters themselves are discarded.\n */\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T04:41:55.727", "Id": "47044", "ParentId": "45406", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T13:42:01.797", "Id": "45406", "Score": "5", "Tags": [ "php", "algorithm", "strings", "security" ], "Title": "Extract code and convert special characters to HTML entities" }
45406
<p>I am working on my first HTML5/CSS web site and, like all of my first-time projects, they end up cumbersome, crude, and hard to work with when changes need to be made later in the life cycle. I am attaching some code with a small amount of HTML and CSS. I have read up on CSS and HTML and, after quite alot of effort, have ended up with this. Please look at the code and fill me in on any inefficiencies that I may have introduced due to lack of experience. I do feel like I am doing a little bit too much manually right now and this is just a basic web site. Any opinion will be appreciated. FYI: I have left the colors a bit funny in order to easily see changes to the web site.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Created on : Mar 24, 2014, 9:05:35 AM Author : meggleston */ #listheader { position:absolute; top:90px; width:100%; background:cadetblue; height: 80px; text-align: center; } #header { top: 0; position: absolute; height: 90px; width: 100%; background: #007400; margin: 0px; padding: 0px; } #logo { position:absolute; background-image:url(../assets/pics/logomain.png); background-repeat: no-repeat; background-re:no-repeat; background-position: left top; background-size:100px 90px; height: 100; width: 100; } body { margin: 0px; padding: 0px; } #site1Container { position:absolute; background-color: #cd0a0a; top:170px; width: 100%; height: 180px; } #site2Container { position:absolute; background-color: bisque; top:350px; width: 100%; height: 180px; } #site3Container { position:absolute; background-color: darkgoldenrod; top:530px; width: 100%; height: 180px; } #site1logo { position:absolute; top:20%; background-image:url(../assets/pics/logo1.png); background-repeat: no-repeat; background-re:no-repeat; background-position: left top; background-size:100px 100px; height: 100%; width: 100; } #site2logo { position:absolute; top:20%; background-image:url(../assets/pics/logo2.png); background-repeat: no-repeat; background-re:no-repeat; background-position: left top; background-size:100px 100px; height: 100; width: 100; } #site3logo { position:absolute; top:20%; background-image:url(../assets/pics/logo3.png); background-repeat: no-repeat; background-re:no-repeat; background-position: left top; background-size:100px 100px; height: 100; width: 100; } #site1desc { position: absolute; left:150px; top: 20%; } #site2desc { position: absolute; left:150px; top: 20%; } #site3desc { position: absolute; left:150px; top: 20%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Site Title&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" href="css/basecss.css"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; &lt;div id="logo"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="listheader"&gt; &lt;h1&gt;&lt;u&gt;List of Web Sites Header&lt;/u&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div id="site1Container"&gt; &lt;div id="site1logo"&gt;&lt;/div&gt; &lt;div id="site1desc"&gt;Site description goes here.&lt;/div&gt; &lt;/div&gt; &lt;div id="site2Container"&gt; &lt;div id="site2logo"&gt;&lt;/div&gt; &lt;div id="site1desc"&gt;Site description goes here.&lt;/div&gt; &lt;/div&gt; &lt;div id="site3Container"&gt; &lt;div id="site3logo"&gt;&lt;/div&gt; &lt;div id="site1desc"&gt;Site description goes here.&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:53:26.287", "Id": "79197", "Score": "3", "body": "One quick note, you can save yourself a lot of layout headache, if you leverage a CSS framework like Twitter.Bootstrap (http://getbootstrap.com/2.3.2/) it is drastically easier to create responsive layouts with a lot less \"Cross-browser\" issues, as they've already done a lot of the heavy lifting for you. Also, as stated, don't use absolute positioning, it's almost never necessary/a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:35:07.223", "Id": "79324", "Score": "2", "body": "@MitchellLee Bootstrap isn't part of Twitter anymore, also there is Bootstrap 3 now: http://getbootstrap.com/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:48:16.200", "Id": "79360", "Score": "2", "body": "Using Bootstrap is also a really good way to bloat your markup. I wouldn't recommend its use to anyone." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:23:57.697", "Id": "79416", "Score": "0", "body": "That's why it offers the different css components as separate .less files. You can pick and choose the elements you need (e.g. just the grid system) and ignore the rest. Combine + minify your css and there is negligible increases in bloat." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T20:15:23.627", "Id": "79691", "Score": "0", "body": "If you are wanting to _learn_ then it is arguably better to start off without using a framework." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-19T01:25:30.833", "Id": "379034", "Score": "0", "body": "In CSS, it's common practice to include the first curly bracket on the first line with the selector: `#example {`." } ]
[ { "body": "<p>One example of where you should use other HTML Elements</p>\n\n<pre><code> &lt;div id=\"site1Container\"&gt;\n &lt;div id=\"site1logo\"&gt;&lt;/div&gt;\n &lt;div id=\"site1desc\"&gt;Site description goes here.&lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>This should look like this</p>\n\n<pre><code> &lt;div id=\"site1Container\"&gt;\n &lt;img id=\"site1logo\" src=\"http://www.google.com/yourpic.jpg\" alt=\"funny picture\"/&gt;\n &lt;p class=\"site1desc\"&gt;Site description goes here.&lt;/p&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>You were also using the same ID attribute multiple times, which is a <strong>no-no</strong>, use classes for something where you are going to use a similar Style for multiple tags.</p>\n\n<p>you might want to lose the ID on the <code>img</code> tag as well, if you are going to display a picture then display a picture not a background.</p>\n\n<p>I only pointed out one instance, there are others in your code</p>\n\n<hr>\n\n<p>Don't use old outdated tags like this one</p>\n\n<pre><code>&lt;h1&gt;&lt;u&gt;List of Web Sites Header&lt;/u&gt;&lt;/h1&gt;\n</code></pre>\n\n<p>if you want to underline something, use a style</p>\n\n<pre><code>&lt;h1 style=\"text-decoration:underline\"&gt; List of Web Sites Header &lt;/h1&gt;\n</code></pre>\n\n<p>if you are going to use the same style in more than one place use a class, only write inline style rules where absolutely necessary, they can clutter your HTML</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:40:23.047", "Id": "79350", "Score": "3", "body": "You probable wanted to use `src` attribute for `img` tag, not `href`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:49:32.690", "Id": "79583", "Score": "0", "body": "Additionally dropping the class on child elements will promote css's natural cascade. E.g. specificity vs implied. And my personal preference is to use classes for styling and id's for functionality as id's take precedence over classes, Pseudo elements, and selectors so avoiding using ID's for styling will make it more scalable as a whole." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:53:07.960", "Id": "45413", "ParentId": "45408", "Score": "23" } }, { "body": "<h2>Semantically, I would suggest using HTML5 elements more.</h2>\n\n<p>For example, instead of...</p>\n\n<pre><code>&lt;div id=\"header\"&gt;\n &lt;div id=\"logo\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Use instead: (the ID can stay if you want it to)</p>\n\n<pre><code>&lt;header&gt;\n &lt;div id=\"logo\"&gt;&lt;/div&gt;\n&lt;/header&gt;\n</code></pre>\n\n<p>This would change your CSS from <code>#header {}</code> to just <code>header {}</code></p>\n\n<p>It is common to see multiple tags in complicated templates. So something like this might be appropriate if that is the case...</p>\n\n<pre><code>&lt;header class=\"site-header\"&gt;\n &lt;div id=\"logo\"&gt;&lt;/div&gt;\n&lt;/header&gt;\n</code></pre>\n\n<p>CSS would be:</p>\n\n<pre><code>header.site-header {}\n</code></pre>\n\n<hr>\n\n<h2>Consistency, consistency, consistency.</h2>\n\n<p>Most of your class and ID names are completely lowercase. However a few classes use camelCase like: <code>#site3Container</code></p>\n\n<p>Make your naming conventions consistent. Either use all camelCase or use all lowercase or all UPPERCASE etc.</p>\n\n<p>Typically, I use lowercase for HTML and CSS (faster to write). I use camelCase for PHP. This is no rule however.</p>\n\n<hr>\n\n<h2>Positioning</h2>\n\n<p>Absolute positioning has its uses. It's almost never used for basic layout however.</p>\n\n<p>Your exact layout can be achieved without the use of ANY <code>position: absolute;</code>. It is my general recommendation to avoid <code>position: absolute;</code> at almost all times. If you are finding you need to use it for something, chances are you don't actually need to, you just don't know how else to do it yet. Consult someone.</p>\n\n<p>Here is a JSFiddle of your <a href=\"http://jsfiddle.net/8zy98/\">current html and css</a></p>\n\n<p>Here is a JSFiddle demonstrating the <a href=\"http://jsfiddle.net/8zy98/1/\">same layout, without positioning.</a></p>\n\n<p><em><strong></em>*Note</strong> that the description text now has a maximum width of 960px (common site width, though 1140 is becoming more common). The description divs are also center so there will always be equal space on left and right sides.</p>\n\n<p>My modifications above also feature one particular additional CSS selector:</p>\n\n<pre><code>* { margin: 0; padding: 0; }\n</code></pre>\n\n<p>The asterisk * is a wildcard, it essentially means ANY element. The selector above resets the margin and padding of every element to 0. This is usually done via something called a \"reset stylesheet\". Which leads me to my next subject...</p>\n\n<hr>\n\n<h2>Reset Stylesheets</h2>\n\n<p>Reset stylesheets contain CSS code which standardizes what your website will look like across all browsers. It sets all padding and margins to 0 for instance, so that no default styling is added to your site that you potentially, or even probably, don't want.</p>\n\n<p>A quick Google search lands us at this website: <a href=\"http://www.cssreset.com/\">http://www.cssreset.com/</a></p>\n\n<p>There, you can see many popular reset stylesheets, all with their own different sort of caveats and specialities. I personally recommend Normalize.css It keeps and standardizes some typical styles you may not necessarily want to reset to 0. It also contains some standard typography styling, so your text looks great without you having to do any work. Reset stylesheets should always be the very first .css file you link. So you would include yours like this for instance:</p>\n\n<pre><code>&lt;head&gt;\n &lt;title&gt;Site Title&lt;/title&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n &lt;link rel=\"stylesheet\" href=\"css/reset.css\"/&gt;\n &lt;link rel=\"stylesheet\" href=\"css/basecss.css\"/&gt;\n&lt;/head&gt;\n</code></pre>\n\n<hr>\n\n<h2>Classes over ID's</h2>\n\n<p>An ID is specific, they can be used once. It IS this \"thing\" and it is only ever this \"thing\". A class can be just as specific, or as broad as you would like. A class can be applied to multiple elements on the same page. An example, expanding from the JS Fiddles above, would be to combine the styles for the description divs.</p>\n\n<p>We start with this CSS:</p>\n\n<pre><code>#site1desc\n{\n width: 100%;\n max-width: 960px;\n margin: 0 auto;\n}\n\n#site2desc\n{\n width: 100%;\n max-width: 960px;\n margin: 0 auto;\n}\n\n#site3desc\n{\n width: 100%;\n max-width: 960px;\n margin: 0 auto;\n}\n</code></pre>\n\n<p>By modifying the HTML so that every <code>&lt;div id=\"site1desc\"&gt;</code> is now this: <code>&lt;div class=\"contentdesc\"&gt;</code> We can drastically cut down on our total CSS code. Our full HTML now looks like the below...</p>\n\n<pre><code>&lt;div id=\"site1Container\"&gt;\n &lt;div id=\"site1logo\"&gt;&lt;/div&gt;\n &lt;div class=\"contentdesc\"&gt;Site description goes here.&lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"site2Container\"&gt;\n &lt;div id=\"site2logo\"&gt;&lt;/div&gt;\n &lt;div class=\"contentdesc\"&gt;Site description goes here.&lt;/div&gt;\n&lt;/div&gt;\n&lt;div id=\"site3Container\"&gt;\n &lt;div id=\"site3logo\"&gt;&lt;/div&gt;\n &lt;div class=\"contentdesc\"&gt;Site description goes here\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The only CSS we need changes from the 3 selectors above to just this:</p>\n\n<pre><code>.contentdesc\n{\n width: 100%;\n max-width: 960px;\n margin: 0 auto;\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/8zy98/2/\">JSFiddle Demo of the above</a></p>\n\n<p>***Note: CSS classes are referenced with a period <code>.className</code> is different from <code>#idName</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:50:29.723", "Id": "79361", "Score": "1", "body": "CSS resets are nothing but snake oil. Setting all of your margins to 0 just so you can set them to something sane elsewhere is stupid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:56:27.430", "Id": "79363", "Score": "4", "body": "Are you kidding me? There are plenty of good reasons to utilize a css reset. Good ones like Normalize do a hell of a lot more than just reset padding and margin spaces. Normalize in particular doesn't set to 0 anyways, but sets to pretty common spaces used by a number of modern sites." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:12:53.177", "Id": "79432", "Score": "0", "body": "This is a shining example of what kind of answers SO is looking for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:16:11.573", "Id": "79434", "Score": "0", "body": "TYVM @JoshWillik" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:00:30.187", "Id": "79588", "Score": "0", "body": "Id offer up an answer but it seems you already have a decent one in this answer. +1, but there's too much more to add and I'm lazy at the moment, so I'll just suggest that pseudo elements are your friend, you dont need to be ultra specific in classing everything & use CSS's natural cascade." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-21T14:15:20.810", "Id": "364738", "Score": "0", "body": "I personally prefer to leave stuff at the browser's default settings." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:03:06.247", "Id": "45417", "ParentId": "45408", "Score": "41" } }, { "body": "<p>The CSS rulesets for your <code>#site1desc</code> and <code>#site2desc</code> etc. are all the same (copy-and-pasted). Instead there could be just one class <code>class=\"sitedesc\"</code> and CSS selector <code>.sitedesc</code>; or several ID selectors for the same ruleset</p>\n\n<pre><code>#site1desc, #site2desc, #site3desc\n{\n position: absolute;\n left:150px;\n top: 20%;\n}\n</code></pre>\n\n<p>Your <code>#site1logo</code> and <code>#site2logo</code> etc. definitions are all the same, except for the URL of the logo. You could make these all the same class with one ruleset; and differentate just the logo with a rule like:</p>\n\n<pre><code>#site1Container &gt; .sitelogo\n{\n background-image:url(../assets/pics/logo1.png);\n}\n</code></pre>\n\n<p>Similarly our <code>#site1Container</code> and <code>#site2Container</code> etc. rulesets are all the same, except for the background-color.</p>\n\n<p>So I'd suggest HTML like:</p>\n\n<pre><code> &lt;div id=\"site1\" class=\"siteContainer\"&gt;\n &lt;div class=\"siteLogo\"&gt;&lt;/div&gt;\n &lt;div class=\"siteDesc\"&gt;Site description goes here.&lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:09:21.010", "Id": "45420", "ParentId": "45408", "Score": "11" } }, { "body": "<p>One quick remark: Never leave out the DOCTYPE (<code>&lt;!doctype html&gt;</code> for HTML 5), unless you want to work around the bugs that the browsers will emulate.</p>\n\n<p>EDIT: I forgot the \"5\" in HTML 5.</p>\n\n<p>Also: It doesn't really matter which DOCTYPE you use, as long it triggers <a href=\"https://developer.mozilla.org/en-US/docs/Quirks_Mode_and_Standards_Mode\" rel=\"noreferrer\">Standards Mode</a> the browser. Browsers don't differentiate between HTML versions. You could use an \"old\" HTML 4 DOCTYPE but write HTML 5 code or use the HTML 5 DOCTYPE and just write \"plain\" HTML 4. As long as the browser is in Standards Mode it will be fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:28:57.077", "Id": "79187", "Score": "0", "body": "for HTML5 or for any HTML?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:50:57.937", "Id": "79195", "Score": "5", "body": "For any HTML, although if your not using HTML5 you should add the correct doctype (XHTML Transitional, strict, etc)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:53:16.117", "Id": "79196", "Score": "0", "body": "@MitchellLee thanks. most of the time I let my IDE create the DocTypes and don't pay any attention, shame on me...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:55:09.250", "Id": "79198", "Score": "0", "body": "@Malachi if your IDE is adding the doctype to the page, then it is part of your outputted HTML, and that's an acceptable solution. The main thing is the browser has to see the doctype, as it will make a lot of weird issues (especially with IE6-8) go away." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:09:08.670", "Id": "79203", "Score": "0", "body": "@MitchellLee, I am just saying I make sure it is there, but don't know much about it, I mean I know enough that it needs to be correct for the code you want to use on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:15:28.300", "Id": "79207", "Score": "2", "body": "@Malachi these days, I'd say you should just stick to <!doctype html>. HTML5 is the most advanced, and well supported by almost every browser these days, and due to the nature of older browsers being (almost TOO forgiving) malformed HTML, it generally doesn't cause any problems there. Combine it with a CSS Framework like Boostrap, and Modernzr javascript library, and other polyfils, it's the path to least resistence." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:24:54.773", "Id": "45422", "ParentId": "45408", "Score": "18" } }, { "body": "\n\n<p>You should add the DOCTYPE at the top (before the <code>html</code> element): </p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n</code></pre>\n\n<hr>\n\n<p>The <code>meta</code>-<code>charset</code> should come <em>before</em> the <code>title</code> (so the encoding is known before parsers reach it):</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;meta charset=\"UTF-8\"&gt;\n&lt;title&gt;Site Title&lt;/title&gt;\n</code></pre>\n\n<hr>\n\n<p>If this is a page from a whole website, and not just a stand-alone page:</p>\n\n<p>Your site title (which seems to be represented as logo in your case, so the textual title would be the <code>alt</code> value of that logo) should be a <code>h1</code>. </p>\n\n<p>The main content (which currently has an <code>h1</code>), should be in scope of the site title, i.e., <code>h2</code>. Or even better, use a sectioning content element (<code>section</code> resp. <code>article</code>) for your main content. So the structure would look like:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;body&gt;\n &lt;h1&gt;&lt;img src=\"logo.png\" alt=\"Site title\"&gt;&lt;/h1&gt; &lt;!-- don’t append \"logo\" to the alt value --&gt;\n &lt;section&gt; &lt;!-- depending on your content, this could also be 'article' --&gt;\n &lt;h1&gt;Main content title&lt;/h1&gt;\n &lt;!-- here comes your whole main content of that page --&gt;\n &lt;/section&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>You can read more about this in my other answers:</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/40262/16414\">https://codereview.stackexchange.com/a/40262/16414</a></li>\n<li><a href=\"https://codereview.stackexchange.com/a/28295/16414\">https://codereview.stackexchange.com/a/28295/16414</a></li>\n<li><a href=\"https://stackoverflow.com/a/11915502/1591669\">https://stackoverflow.com/a/11915502/1591669</a></li>\n<li><a href=\"https://stackoverflow.com/a/14920215/1591669\">https://stackoverflow.com/a/14920215/1591669</a></li>\n</ul>\n\n<hr>\n\n<p>The <a href=\"http://www.w3.org/TR/2014/CR-html5-20140204/text-level-semantics.html#the-u-element\" rel=\"nofollow noreferrer\"><code>u</code> element</a> doesn’t seem to be used correctly here (\"unarticulated, though explicitly rendered, non-textual annotation\"). If you want to display this text as underlined, use CSS instead:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>#listheader h1 {text-decoration: underline;}\n</code></pre>\n\n<p>But note that in the Web underlines are typically associated with hyperlinks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:56:29.250", "Id": "79394", "Score": "1", "body": "I disagree with your use of the H1 tag to surround the IMG tag. you will create padding and newlines and margins by doing this. an H1 is meant for text Headings not to encapsulate a Graphic, the graphic could be encapsulated by fancy HTML5 tags like `<header>` that would make more sense. and as far as everything else, it's all been said except for the Meta Tag stuff, which is a good point" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:04:54.650", "Id": "79399", "Score": "0", "body": "@Malachi: The point is that the *site* needs (\\*) a heading (for pages that are part of a website, that is; for example those with a global navigation). Whatever the site title may be should be enclosed in `h1`. It may be text, a logo or even an audio file, this doesn’t matter. -- And using a heading is about the semantics/accessibility, not about the default CSS styling it may have in browsers. -- (\\* It can also be omitted, but then the main content must be inside a sectioning content element, and the `body` sectioning root must not have other direct headings.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:08:07.243", "Id": "79400", "Score": "0", "body": "I see the Title inside the Title Tag nested in the header tag, where it belongs. like I said HTML5 has a tag for header sections of websites `<header>` and `</header>` that should surround the Logo and any H1 text that goes with it (separately)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:11:13.340", "Id": "79401", "Score": "0", "body": "`<joke>`you should work for Microsoft's Internet Explorer team...`</joke>` with all the this must be that lingo floating around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:11:48.573", "Id": "79402", "Score": "0", "body": "@Malachi: Yes, if the site has a logo *and* a textual heading, then this can be done. But according to OP’s example, I assumed that the site has only a logo. So in such a case, the logo (resp the logo’s `alt` value) is the relevant `h1`. --- The `header` element can be used, yes, but note that it doesn’t play a role in the outline, so for this point it doesn’t influence the decision if headings should be used or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:31:37.187", "Id": "79417", "Score": "1", "body": "you are over complicating things I think.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:26:12.843", "Id": "79575", "Score": "1", "body": "Where the img tag is now valid in an h1 in html5, it isn't considered semantically sound. Either an image with an alt OR a h1 if your site name is the heading of that particular page. No text in an h1 makes little sense, just because you can do something doesn't mean you should. Additionally, the title tag and h1 on the page should compliment the page contents and each other, not replicate each other. A logo is site wide branding whereas title/h1 is page specific." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T16:54:38.067", "Id": "79655", "Score": "0", "body": "@darcher: This is not correct, the HTML5 spec even contains such an example: [Logos, insignia, flags, or emblems](http://www.w3.org/TR/2014/CR-html5-20140204/embedded-content-0.html#logos,-insignia,-flags,-or-emblems) (second example). -- Exactly *because* the logo (or the site name) is site-wide \"branding\", it is important that it becomes the top-level heading. Otherwise site-wide things like navigation, header, footer, sidebars etc. would be in scope of the main content heading, which would clearly lead to a wrong outline." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T18:01:14.717", "Id": "79672", "Score": "0", "body": "@unor As with anything, it greatly depend on the context in which it's being used. However, GENERALLY SPEAKING a logo is not a heading, it's a logo, it doesn't relate to the content displayed on the page and thus shouldn't be associated with the pages outline (in most cases). http://csswizardry.com/2010/10/your-logo-is-an-image-not-a-h1/ touches on the topic and there is a plethora of related debates as it's a highly debated topic, so I'll just correct my previous comment and say \"Generally speaking.\"" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:40:04.833", "Id": "45517", "ParentId": "45408", "Score": "8" } } ]
{ "AcceptedAnswerId": "45417", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:25:33.890", "Id": "45408", "Score": "38", "Tags": [ "html", "css", "html5", "web-services" ], "Title": "First Time HTML5/CSS Site" }
45408
<p>I want to group the two very similar jQuery functions into just one. Any idea?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;input id="progress" type="text" class="spinner-input form-control" maxlength="3" readonly value="&lt;?php echo $progreso['progress'] ?&gt;"&gt; &lt;div class="spinner-buttons input-group-btn btn-group-vertical"&gt; &lt;button id="plus" type="button" class="btn spinner-up btn-xs btn-info"&gt; &lt;i class="icon-angle-up"&gt;&lt;/i&gt; &lt;/button&gt; &lt;button id="minus" type="button" class="btn spinner-down btn-xs btn-info"&gt; &lt;i class="icon-angle-down"&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$(document).on('click', '#plus', function(e){ var progress = parseInt( $('#progress').val() ) + 5; if ( progress &lt;= 100 ) { $('#progress').val( progress ); } else{ $('#progress').val( 100 ); }; }); $(document).on('click', '#minus', function(e){ var progress = parseInt( $('#progress').val() ) - 5; if ( progress &gt;= 0 ) { $('#progress').val( progress ); } else{ $('#progress').val( 0 ); }; }); </code></pre>
[]
[ { "body": "<p>You could define one function:</p>\n\n<pre><code>function plus_or_minus(event)\n{\n var isPlus = $(this).id === '#plus';\n\n var progress = parseInt($('#progress').val(), 10); \n\n if(isPlus)\n progress += 5;\n else\n progress -= 5;\n\n if(progress &gt; 100)\n progress = 100;\n else if(progress &lt; 0)\n progress = 0;\n\n $('#progress').val(progress);\n}\n\n\n// And then bind\n$(document).on('click', '#plus', plus_or_minus);\n$(document).on('click', '#minus', plus_or_minus);\n</code></pre>\n\n<p>When condensing your code, try to abstract the common parts out to one function - with a simple check against the target element's ID, we can figure out whether to add or subtract. Next, we check <code>progress</code>'s value against 100 and 0 to keep it in bounds either way. Finally, apply the value to the <code>#progress</code> element.</p>\n\n<p>Keep in mind that it's a good idea to always pass a base parameter to <code>parseInt</code> - usually the default will be base 10, but there are no promises made when it comes to dealing with as many browsers as there are out there. </p>\n\n<p>PS I haven't tested this, the only part I'm iffy on is the <code>var isPlus = ...</code> as I haven't done jQuery in a while. If that fails to work, maybe try <code>var isPlus = $(this) == $('#plus')</code></p>\n\n<p>PPS As a bonus, I think jQuery can accept multiple targets for a single <code>on</code> command - research the docs and see if you can bind the function to both elements at the same time</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:06:14.207", "Id": "79182", "Score": "1", "body": "Checking the id would be `id.this === \"plus\"` (without jQuery) or `$(this).attr(\"id\") === \"plus\"` (with jQuery). `$(this) == $('#plus')` just tries to compare two jQuery objects that may both point to the same element, but they still be two different objects and thus never equal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:14:29.917", "Id": "79206", "Score": "0", "body": "@RoToRa thanks - I thought maybe the two would be \"loosely equal\" with the `==`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:00:34.767", "Id": "45414", "ParentId": "45412", "Score": "1" } }, { "body": "<p>First step would be to extract a function that updates the input:</p>\n\n<pre><code>function modifyProgress(delta) {\n var element = $('#progress');\n var progress = +element.val() + delta;\n element.val( isNaN(progress) ? 0 : progress &lt; 0 ? 0 : progress &gt; 100 ? 100 : progress;\n);\n}\n</code></pre>\n\n<p>BTW, never ever use <code>parseInt</code> with out its second parameter (radix). Some browsers interpret numbers starting with a leading <code>0</code> (zero) as octal, so that an input of <code>\"09\"</code> throws an error and <code>\"010\"</code> to returns <code>8</code>. Better is to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#-_.28Unary_Plus.29\" rel=\"nofollow\">unary plus operator</a>.</p>\n\n<p>This simplifies the event handler:</p>\n\n<pre><code>$(document).on('click', '#plus, #minus', function(e){\n modifyProgress(5 * (this.id === \"plus\" ? 1 : -1));\n})\n</code></pre>\n\n<p>EDIT: You should consider storing your progress value somewhere other inside the <code>input</code> such as a data model (see <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a>). Keeping data/logic separate from the GUI is always a good thing. It also avoids needing to re-parse the number every time. And you can \"hide\" the checking of overflow or underflow inside the model.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:02:21.253", "Id": "45416", "ParentId": "45412", "Score": "4" } }, { "body": "<p>Introduce a third function that both of the first two call.</p>\n\n<pre><code>function adjustSpinner(value, amount) {\n var progress = parseInt(value,10) + amount;\n if (progress &gt; 100) return 100;\n if (progress &lt; 0) return 0;\n return progress;\n}\n\n$(document).on('click', '#plus', function(e){\n $('#progress').val(adjustSpinner($('#progress').val(), 5));\n});\n\n$(document).on('click', '#minus', function(e){\n $('#progress').val(adjustSpinner($('#progress').val(), -5));\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:08:32.947", "Id": "79183", "Score": "0", "body": "You forgot converting `$('#progress').val()` to a number. This will just lead to string concatenation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:14:08.563", "Id": "79184", "Score": "0", "body": "Good point. Got ahead of myself. Fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:03:40.467", "Id": "45418", "ParentId": "45412", "Score": "2" } } ]
{ "AcceptedAnswerId": "45416", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T15:42:26.930", "Id": "45412", "Score": "3", "Tags": [ "javascript", "jquery", "html" ], "Title": "Grouping similar jQuery functions" }
45412
<p>For the over eager people: check out this <a href="http://plnkr.co/edit/YXtVx48q01rrfKu3DEIX" rel="nofollow">plunker</a></p> <p>I create a directive which has to add buttons on top of input fields, to select the language you want to input.</p> <p>This is used on forms, such as a product form. A product has translations (i.e. has a description that is language dependant).</p> <p>Things I am not really happy with:</p> <ul> <li>I use <code>$scope.$parent</code> to get the required translation for the given field</li> <li>The use of the timeout to handle model info that arrives with a delay (from a web service)</li> </ul> <p>for the people that took the time to read this: check out the example on <a href="http://plnkr.co/edit/YXtVx48q01rrfKu3DEIX" rel="nofollow">plunker</a></p> <p>Let me know if you need any more information / explanation.</p> <p>The directive in question:</p> <pre><code>app.directive('translationMenu', function($compile, $timeout) { return { restrict: 'E', scope: { languages: '=', defaultLanguage: '=' }, templateUrl: 'translation-menu.html', controller: function($scope, $element, $attrs) { // check if the current field is available in the given dictionary var checkFieldAvailability = function(l) { return $scope.$parent[$attrs.dictionary] &amp;&amp; $scope.$parent[$attrs.dictionary][l] &amp;&amp; $scope.$parent[$attrs.dictionary][ l][$attrs.field]; } // check if the language is available in the dictionary, and if so, if the field is already translated. // is used to color the button text red var dictionaries = {}; $scope.languages.forEach(function(l) { dictionaries[l] = checkFieldAvailability(l); }); // the muscles of this operation // it will replace the input field with a clone of the original (and with ng-model filled out) var inputElementTemplate = $element.next().clone(); var setInputField = function(lang) { var inputElement = inputElementTemplate.clone(); inputElement.attr('ng-model', $attrs.dictionary + '.' + lang + '.' + $attrs.field); $element.next().replaceWith(inputElement); $compile(inputElement)($scope.$parent); }; // function used in the ng-click. // when navigating away, it will also check again if it needs transalation. var selectLanguage = function(lang) { var oldLang = $scope.selectedLanguage; dictionaries[oldLang] = checkFieldAvailability(oldLang); $scope.selectedLanguage = lang; setInputField(lang); }; // Dirty fix, this "ensures" that the dictionary is returned from the ajax request. $timeout(function() { console.dir(dictionaries); for (var lang in dictionaries) { dictionaries[lang] = checkFieldAvailability(lang); } }, 300); $scope.selectedLanguage = $scope.defaultLanguage; $scope.selectLanguage = selectLanguage; $scope.dictionaries = dictionaries; selectLanguage('en'); } } }); </code></pre> <p>The View:</p> <pre><code>&lt;div class="col-sm-5"&gt; &lt;translation-menu languages="allLanguages" default-language="currentUser.DefaultLanguage" field="name" dictionary="desc" &gt;&lt;/translation-menu&gt; &lt;input class="form-control" type="text" /&gt; &lt;/div&gt; </code></pre> <p>the controller:</p> <pre><code>function MyController($rootScope, $scope,$timeout) { $rootScope.allLanguages = ['en', 'nl', 'fr']; $rootScope.currentUser = { DefaultLanguage: 'en' }; // Simulate slow-ish web service $scope.desc = {}; $timeout(function(){ $scope.desc = { 'en': { 'name': 'Joseph', 'code': 'EN123' }, 'nl': { 'name': 'Jos', 'code': 'NL123' } }; }, 200); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T07:30:58.183", "Id": "83499", "Score": "1", "body": "You are basically reading your attributes, then why not simply using `$attrs` provided instead of the fragile `$scope.$parent`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:19:17.210", "Id": "45421", "Score": "1", "Tags": [ "javascript", "angular.js" ], "Title": "Angular directive with use of scope.$parent and $timeout" }
45421
<p>The problem is to input, divide 2 <code>int</code>s and display the result.<br> Please, review my program. It worth noting, I've intentionally used <code>goto</code>, not <code>while</code>. </p> <pre><code>int main(){ int a, b; ab_input: cout &lt;&lt; "Enter 2 numbers: "; cin &gt;&gt; a &gt;&gt; b; try { if (!cin) throw std::runtime_error("Bad input"); if (b == 0) throw std::runtime_error("Dividing by zero"); } catch (std::runtime_error er) { cin.sync(); cin.clear(); std::cerr &lt;&lt; er.what() &lt;&lt; endl; cout &lt;&lt; "Try again? y/n: "; char c; cin &gt;&gt; c; if (cin &amp;&amp; c == 'y') goto ab_input; else return -1; } cout &lt;&lt; "a/b = " &lt;&lt; a / b &lt;&lt; endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:31:53.117", "Id": "79188", "Score": "12", "body": "Could you explain why you've intentionally used `goto`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:33:10.333", "Id": "79189", "Score": "10", "body": "[Hope the raptors get you](http://xkcd.com/292/) ... ;-) ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:38:37.793", "Id": "79190", "Score": "1", "body": "(LET THE HOLYWAR BEGINS!!!11) I believe it's more apropriate and more readable here, than `while`. Or `goto`_is_bad is a dogma? Anyway, may be there are some another notes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:41:33.577", "Id": "79191", "Score": "0", "body": "My C++ is a bit rusty, what if the user writes a number larger than 2^31-1? Doesn't that result in an overflow and a wrong result? OR does the !cin catch that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:47:42.707", "Id": "79192", "Score": "0", "body": "You should also be catching the `std::runtime_error` by `const&`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:50:50.333", "Id": "79194", "Score": "0", "body": "like `catch (const std::runtime_error &er)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:57:38.563", "Id": "79200", "Score": "2", "body": "\"Or goto_is_bad is a dogma?\" -- It's popularly [Considered harmful](http://en.wikipedia.org/wiki/Considered_harmful)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T17:04:01.903", "Id": "79201", "Score": "0", "body": "@user2198121: Yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:14:37.940", "Id": "79213", "Score": "3", "body": "@user2198121: Its not a holy war. That implies there are two large factions that disagree. I think you will find there is only one large faction (that war was won by our side decades ago). But yes there are legitimate uses of goto (they do exist and I have used goto once). But here it is not legitimate and does make the code harder to read." } ]
[ { "body": "<p>Some alternatives to <code>goto</code>:</p>\n\n<pre><code>int main(){\n int a, b;\n\n for (;;) { // until success\n cout &lt;&lt; \"Enter 2 numbers: \";\n cin &gt;&gt; a &gt;&gt; b;\n try {\n if (!cin) throw std::runtime_error(\"Bad input\");\n if (b == 0) throw std::runtime_error(\"Dividing by zero\");\n break; // success!\n } \n catch (const std::runtime_error&amp; ex) {\n cin.sync();\n cin.clear();\n std::cerr &lt;&lt; ex.what() &lt;&lt; endl;\n cout &lt;&lt; \"Try again? y/n: \";\n char c; \n cin &gt;&gt; c;\n if (cin &amp;&amp; c == 'y') continue; // try again!\n else return -1;\n }\n }\n cout &lt;&lt; \"a/b = \" &lt;&lt; a / b &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>static bool tryAgain(const char* errorMessage){\n cin.sync();\n cin.clear();\n std::cerr &lt;&lt; errorMessage &lt;&lt; endl;\n cout &lt;&lt; \"Try again? y/n: \";\n char c; \n cin &gt;&gt; c;\n return (cin &amp;&amp; c == 'y'); // try again!\n}\n\nint main(){\n int a, b;\n\n const char* errorMessage;\n do {\n cout &lt;&lt; \"Enter 2 numbers: \";\n cin &gt;&gt; a &gt;&gt; b;\n // set errorMessage.\n if (!cin) errorMessage = \"Bad input\";\n else if ((b == 0)) errorMessage = \"Dividing by zero\";\n else errorMessage = 0;\n if (errorMessage &amp;&amp; !tryAgain(errorMessage)) return -1; // fail!\n } while (errorMessage);\n cout &lt;&lt; \"a/b = \" &lt;&lt; a / b &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>int main(){\n int a, b;\n\n for (;;) { // Until explicit break on success.\n cout &lt;&lt; \"Enter 2 numbers: \";\n cin &gt;&gt; a &gt;&gt; b;\n // set errorMessage.\n const char* errorMessage;\n if (!cin) errorMessage = \"Bad input\";\n else if ((b == 0)) errorMessage = \"Dividing by zero\";\n else break; // success!\n if (!tryAgain(errorMessage)) return -1; // fail!\n }\n\n cout &lt;&lt; \"a/b = \" &lt;&lt; a / b &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Also you might like to change the last statement to:</p>\n\n<pre><code>cout &lt;&lt; \"a/b = \" &lt;&lt; (double)a / b &lt;&lt; endl;\n</code></pre>\n\n<blockquote>\n <p>I would also mention that returning -1 is normally a bad idea. The shell interprets negative numbers in weird ways</p>\n</blockquote>\n\n<p>All of the <a href=\"http://en.wikipedia.org/wiki/Exit_status#References\">Exit status - References</a> suggest <code>0</code> for success and non-zero (but positive) for failure:</p>\n\n<ul>\n<li>Some (Unix and DOS) references suggest that the range of valid codes is <code>0..255</code></li>\n<li>Another (HP OpenVMS) says that bits 29..31 are reserved and must be zero</li>\n<li>The Windows <a href=\"http://msdn.microsoft.com/en-us/library/ms681381.aspx\">System Error Codes</a> range up to 15999 (I guess you might want to return something like <code>ERROR_INVALID_PARAMETER</code>).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:50:57.510", "Id": "79217", "Score": "4", "body": "I would also mention that returning -1 is normally a bad idea. The shell interprets negative numbers in weird ways" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:52:44.080", "Id": "45424", "ParentId": "45423", "Score": "12" } } ]
{ "AcceptedAnswerId": "45424", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T16:28:17.213", "Id": "45423", "Score": "7", "Tags": [ "c++", "exception-handling" ], "Title": "Dividing 2 numbers" }
45423
<p>I had to look up some other solutions online because I could not figure it out on my own. I really wish I could have come up with it completely on my own, but that didn't happen. Nevertheless, please review my prime number program and let me know if there are any improvements I should make or advice your would like to give me about it.</p> <pre><code> var primes = []; // will become a list of prime numbers primes_loop: for (var n = 2; n &lt; 10; n++) { if (n === 2) { primes.push(n); // first prime number is stored continue primes_loop; // continue iteration of the loop } divisors_loop: for (var i = 2; i &lt; n; i++) { if (n % i === 0) { break divisors_loop; // n is not prime if condition is true } else { primes.push(n); // update prime list with the prime number } } } for (var index = 0; index &lt; primes.length; index++) { console.log(primes[index]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T03:59:15.743", "Id": "79289", "Score": "1", "body": "[Trial division](https://en.wikipedia.org/wiki/Trial_division), nice first step! Now try the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). Too intuitive? Try the [Sieve of Atkin](https://en.wikipedia.org/wiki/Sieve_of_Atkin)! Upgrade that algorithm for better time & space performance!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:03:23.033", "Id": "79290", "Score": "0", "body": "`for (var i = 2; i < n; i++)` I am kind of against using this kind of a loop, the number of iterations can be reduced by half just by changing it to, `for (var i = 2; i < n/2; i++)` Furthermore, if we are testing a very large number to be prime or not, using `i=2 ; i< sqrt(n) ; i++` reduces the number of iterations exponentially. (the last code snippet was a C code, not sure about the sqrt() function in javascript)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:10:22.303", "Id": "79292", "Score": "0", "body": "`n` is the number that is being tested for being prime or not, while the loop condition that is mentioned is for testing if a number is prime or not. Lets consider n=11, then the loop runs from i=2; i<5, no divisors found and hence prime. for a number n, the number of factors from [1,n/2] is equal top the number of factors from [n/2,n] hence the second part of the iteration is a repeat of the first part. I will try and fetch the algo that proves it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:16:35.097", "Id": "79294", "Score": "0", "body": "If I am reading the code right then i see two major loops, `for (var n = 2; n < 10; n++)` for generating the range of numbers from which he will print the ones that are prime, and `for (var i = 2; i < n; i++)` that tests if the generated number is prime or not. The value of `n` that is being generated in the first loop is being used as the upper limit for the second loop that tests if the number is primie or not. This is the loop that I am referring to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:20:30.377", "Id": "79295", "Score": "1", "body": "I you right, I though he was using the partial array of primes to check for primality of the larger number. He only needs to check `[2, floor(sqrt(n))]` to determine primality of `n`." } ]
[ { "body": "<p>First, let's correct your algorithm (<a href=\"http://www.programmingsimplified.com/c/source-code/c-program-for-prime-number\">using this very similar code</a>) and reformat just a little bit your code (with Fiddle's TidyUp):</p>\n\n<p><a href=\"http://jsfiddle.net/xCX9W/\">JSFIDDLE</a></p>\n\n<pre><code> var primes = []; // will become a list of prime numbers\n\n primes_loop: for (var n = 2; n &lt; 10; n++) {\n\n if (n === 2) {\n primes.push(n); // first prime number is stored\n continue primes_loop; // continue iteration of the loop\n }\n\n divisors_loop: for (var i = 2; i &lt; n; i++) {\n\n if (n % i === 0) {\n break divisors_loop; // n is not prime if condition is true\n }\n\n }\n\n if (n === i) {\n primes.push(n); // update prime list with the prime number\n }\n\n }\n\n for (var index = 0; index &lt; primes.length; index++) {\n console.log(primes[index]);\n }\n</code></pre>\n\n<p>It printed repeatedly numbers because of the condition for <code>primes.push</code>, and it needed another condition, outside of the loop, to be correct (as it was, it only found odd numbers).</p>\n\n<p>Next up, we don't really need tags for the inner loop. It's clear and very reasonable to remove it, and we even save the condition we just added:</p>\n\n<pre><code> var primes = []; // will become a list of prime numbers\n\n primes_loop: for (var n = 2; n &lt; 10; n++) {\n\n if (n === 2) {\n primes.push(n); // first prime number is stored\n continue; // continue iteration of the loop\n }\n\n for (var i = 2; i &lt; n; i++) {\n\n if (n % i === 0) {\n break primes_loop; // n is not prime if condition is true\n }\n\n }\n\n primes.push(n); // update prime list with the prime number\n\n }\n\n for (var index = 0; index &lt; primes.length; index++) {\n console.log(primes[index]);\n }\n</code></pre>\n\n<p>But, we might be able to wrap it up in a function and make it work faster, by skipping all multiples of 2:</p>\n\n<p><a href=\"http://jsfiddle.net/xCX9W/4/\">JSFIDDLE</a></p>\n\n<pre><code>function findPrimes(lowerLimit, upperLimit) {\n\n var primes = []; // will become a list of prime numbers\n\n if (lowerLimit === 2) {\n primes.push(2);\n }\n\n if (lowerLimit % 2 === 0) {\n lowerLimit++;\n }\n\n primes_loop: for (var n = lowerLimit; n &lt; upperLimit; n = n + 2) {\n\n for (var i = 2; i &lt; n; i++) {\n\n if (n % i === 0) {\n break primes_loop; // n is not prime if condtion is ture\n }\n\n }\n\n primes.push(n); // update prime list with the prime number\n\n }\n\n for (var index = 0; index &lt; primes.length; index++) {\n alert(primes[index]);\n }\n\n}\n\nfindPrimes(2, 10);\n</code></pre>\n\n<p>This may get you started, but if primes is what you want, there are better methods (indeed, even this method may be optimized further).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T19:14:31.840", "Id": "45434", "ParentId": "45431", "Score": "5" } }, { "body": "<p>First of all, there's a slight problem with your code. I get this output:</p>\n\n<pre><code>2, 3, 5, 5, 5, 7, 7, 7, 7, 7, 9\n</code></pre>\n\n<p>So it repeats quite a bit, and -- wait, 9 is not a prime number. Oops.</p>\n\n<p>For, say, numbers up to 25, you'd get 21 instances of <code>23</code> in your array. And we'd get a <code>24</code> too, although that's not prime. We'll deal with that in a second. </p>\n\n<p>The way your code runs, you don't need the labels (<code>primes_loop</code> and <code>divisors_loop</code>); when you <code>continue</code> or <code>break</code> you do so for the \"closest\" loop you're in. So simply writing <code>continue</code> with no label will skip to the next iteration of the outer (prime) loop, and <code>break</code> will break the inner (divisor) loop.</p>\n\n<p>However, a label might be handy for a revised version that actually does find primes and only primes (of course, there are <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">other, smarter approaches</a> to all of this, but I'm just sticking to the code that was posted):</p>\n\n<pre><code>var primes = [],\n limit = 10,\n n, divisor;\n\nouterLoop: for( n = 2 ; n &lt;= limit ; n++ ) {\n for( divisor = 2 ; divisor &lt; n ; divisor++ ) {\n if( n % divisor === 0 ) { \n continue outerLoop; // not a prime, try the next n\n }\n }\n primes.push(n); // if we made it all the way here, then n is prime\n}\n</code></pre>\n\n<p>After that, you'll be left with a <code>primes</code> array that looks like this:</p>\n\n<pre><code>[ 2, 3, 5, 7 ]\n</code></pre>\n\n<p>No repetition, and no false positives.</p>\n\n<p>Of course, it'd be nicer to wrap as a function:</p>\n\n<pre><code>function findPrimes(limit) {\n var primes = [], n, divisor;\n\n outerLoop: for( n = 2 ; n &lt;= limit ; n++ ) {\n for( divisor = 2 ; divisor &lt; n ; divisor++ ) {\n if( n % divisor === 0 ) {\n continue outerLoop;\n }\n }\n primes.push(n);\n }\n\n return primes;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T19:24:34.420", "Id": "45435", "ParentId": "45431", "Score": "6" } } ]
{ "AcceptedAnswerId": "45435", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T18:23:59.570", "Id": "45431", "Score": "12", "Tags": [ "javascript", "beginner", "primes" ], "Title": "First attempt at generating prime numbers" }
45431
<p>I'm trying to write a regular expression to check names for invalid entries. Basically I'm trying to eliminate people entering random junk as their name. I know I can't completely eliminate it but I'm trying to make it a little harder at the very least. Here is what I have so far. It works fine I'm wondering if there's a way to improve this.</p> <pre><code>[b-df-hj-np-tv-z]{5,}|[aeiou]{4,}|([a-z])(?=([a-z]*\1){3,})|([ ])(?=([a-z]*\3){2,})|[0-9]+ </code></pre>
[]
[ { "body": "<p>First off, there is an error: You have the part <code>[b-</code> duplicated at the beginning.</p>\n\n<p>The first section matches five successive consonants, which is possbile. Examples for German words (although not names) with up to eight successive consonants: <a href=\"http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-konsonanten\" rel=\"nofollow\">http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-konsonanten</a></p>\n\n<p>The same goes for four successive vowels. Again examples in German with up to five: <a href=\"http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-vokalen\" rel=\"nofollow\">http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-vokalen</a></p>\n\n<p>Then the next one basically matches when a specific letter is repeated three times anywhere in the name and that can't be terribly rare.</p>\n\n<p>And finally one that only allows two spaces, thus names consisting of three words. And I've come across plenty of names in my live with more than three words.</p>\n\n<p>Finally a technical note: If you really want to do this, you need to do it server side. JavaScript validation is trivially easy to circumvent. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:00:24.057", "Id": "79375", "Score": "0", "body": "I will only be matching this against names and first name and last name are in two separate fields so they will be checked individually." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:02:36.250", "Id": "45480", "ParentId": "45443", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T21:46:29.627", "Id": "45443", "Score": "2", "Tags": [ "javascript", "regex" ], "Title": "Check for invalid name" }
45443
<p>I have written the following C code for calculating the Shannon Entropy of a distribution of 8-bit ints. But obviously this is very inefficient for small arrays and won't work with say 32-bit integers, because that would require literally gigabytes of memory. I am not very experienced in C and don't know what would be the best approach here. If it would simplify things, I could use C++ or Objective-C...</p> <p>Also, please tell me about any other issues with the code you may find :-)</p> <pre><code>double entropyOfDistribution(uint8_t *x, size_t length) { double entropy = 0.0; //Counting number of occurrences of a number (using "buckets") double *probabilityOfX = calloc(sizeof(double), 256); for (int i = 0; i &lt; length; i++) probabilityOfX[x[i]] += 1.0; //Calculating the probabilities for (int i = 0; i &lt; 256; i++) probabilityOfX[x[i]] /= length; //Calculating the sum of p(x)*lg(p(x)) for all X double sum = 0.0; for (int i = 0; i &lt; 256; i++) if (probabilityOfX[i] &gt; 0.0) sum += probabilityOfX[i] * log2(probabilityOfX[i]); entropy = -1.0 * sum; free(probabilityOfX); return entropy; } </code></pre> <p>btw, this is the formula I implemented: $$ H(x) = -\sum_{x} p(x) \log(p(x))$$</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T06:56:21.760", "Id": "79308", "Score": "0", "body": "I believe your code currently contains a bug. Consider what happens in: `for (int i = 0; i < 256; i++) probabilityOfX[x[i]] /= length;`, if `x` has a length of 10 (or anything else less than 256). I believe here you want `probabilityOfX[i] /= length;`" } ]
[ { "body": "<p>Firstly, you know the size of the number of buckets you want to use here, so there is no reason to use dynamic allocation (specifically, <code>double *probabilityOfX = calloc(sizeof(double), 256);</code>). This could simply be:</p>\n\n<pre><code>double probabilityOfX[256];\nmemset(&amp;probabilityOfX, 0.0, 256);\n</code></pre>\n\n<p>You don't need to free this memory at the end then, either, reducing the possibility for memory leaks.</p>\n\n<p>Of course, this is fine for small values (like what can fit in a <code>uint8_t</code>), however, using a <code>uint32_t</code> (or larger), this will pre-allocate a large array which could potentially be very sparse. In this case, what you actually want is a dictionary data structure (like a hashmap). Since <code>C</code> doesn't have anything like this inbuilt, I'm going to switch over to <code>C++</code> so we can use <code>std::unordered_map</code> and some other nice things like <code>std::vector</code> (instead of raw <code>uintx_t</code> pointers):</p>\n\n<pre><code>double entropyOfDistribution(const std::vector&lt;uint32_t&gt;&amp; vec)\n{\n std::unordered_map&lt;uint32_t, unsigned&gt; counts;\n\n // Store the number of counts\n for(uint32_t value : vec) {\n ++counts[value];\n }\n\n double sum = 0.0;\n // Note the cast as otherwise we'll be doing integer\n // division and hence rounding to an int -\n // thanks @syb0rg for pointing that out.\n const double num_samples = static_cast&lt;double&gt;(vec.size());\n\n for(auto it = counts.begin(); it != counts.end(); ++it) {\n double probability = it-&gt;second / num_samples;\n sum += probability * log2(probability);\n }\n\n return -1.0 * sum;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:50:09.503", "Id": "79320", "Score": "1", "body": "I you switch for a static array, wouldn't it be better to zero-initialize it by using `= { 0 };` rather than calling `memset`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:27:57.777", "Id": "79323", "Score": "0", "body": "@Morwenn Probably, it just didn't jump to my mind when I was writing it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T02:00:12.870", "Id": "45459", "ParentId": "45444", "Score": "7" } }, { "body": "<p>@Yuushi has already given a pretty good suggestions, but if I were doing this in C++, I'd do it just a bit differently.</p>\n\n<p>Let's start by reviewing your code:</p>\n\n<pre><code> //Counting number of occurrences of a number (using \"buckets\")\n double *probabilityOfX = calloc(sizeof(double), 256);\n</code></pre>\n\n<p>Although it's rarely likely to be a problem, I don't believe that the contents of an array allocated with <code>calloc</code> is guaranteed to contain 0.0 when viewed as <code>double</code>s (but it will in most typical implementations, so you may not care).</p>\n\n<pre><code> //Calculating the probabilities\n for (int i = 0; i &lt; 256; i++)\n probabilityOfX[x[i]] /= length;\n</code></pre>\n\n<p>This (I'm fairly sure) is a bug. I'm pretty sure what was intended was:</p>\n\n<pre><code> //Calculating the probabilities\n for (int i = 0; i &lt; 256; i++)\n probabilityOfX[i] /= length;\n</code></pre>\n\n<p>As it was, it attempted to use 256 characters of the input string, even if the input string was much shorter than that. It could also fail to adjust the probabilities in the counts correctly if the string was longer than 256, but the string contained any characters that didn't occur in the first 256 characters.</p>\n\n<p>As to how I'd do things: I think I'd at least consider implementing it as a (relatively) generic algorithm that could take (for example) any sequence-type container as its input. I'd implement it internally using <code>std::accumulate</code> to do the majority of the work:</p>\n\n<pre><code>template &lt;class Vector&gt;\ndouble entropy(Vector const &amp;v) {\n typedef typename Vector::value_type v_t;\n std::map&lt;v_t, size_t&gt; counts;\n\n for (auto &amp;&amp; c : v)\n ++counts[c];\n\n return -std::accumulate(counts.begin(), counts.end(), 0.0,\n [=](double a, std::pair&lt;v_t, size_t&gt; const &amp;t) { \n double x = t.second / static_cast&lt;double&gt;(v.size()); \n return a + x * log2(x); \n });\n}\n</code></pre>\n\n<p>In this case, using <code>accumulate</code> doesn't really make the code drastically shorter, but it does (IMO) give a little clearer picture of what you're trying to do that using a generic <code>for</code> loop to sum the probabilities.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:33:04.967", "Id": "79316", "Score": "2", "body": "As specified by IEEE 754, a `double` whose bytes are all zero indeed [represents +0.0](http://en.wikipedia.org/wiki/IEEE_754-1985#Zero), for obvious practical reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:53:27.040", "Id": "79344", "Score": "2", "body": "I think what Jerry was getting at was that the C/C++ standards do not guarantee what format will be used for floating-point numbers. Sure, the vast majority of implementations use IEEE-754, which guarantees that a value of all zero bits corresponds to 0.0, but there's no explicit guarantee of this property. With that said, I wouldn't bat an eye at code that makes that assumption; it's simply too common to justify rewriting code that uses it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T07:22:10.877", "Id": "45470", "ParentId": "45444", "Score": "5" } } ]
{ "AcceptedAnswerId": "45459", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:10:04.487", "Id": "45444", "Score": "10", "Tags": [ "c", "beginner" ], "Title": "Counting occurrences of values in C Array (Shannon Entropy)" }
45444
<p>I'm writing a bash script to handle the PPA's on Ubuntu &amp; derivatives. I was wondering how to know if I'm handling this the right way. </p> <p>So, the script works (flawlessly), but I posted it to a blog and got this feedback : </p> <blockquote> <p>The way you wrote you script is the one we all use when we begin : we don't know the variables, so we use traditionnal commands, and in the end if we remove the "#" arguments from the script, the code is sad <em>(maybe he meant 'poor' ?)</em></p> </blockquote> <p>Here is a sample : </p> <pre><code>#! /bin/bash SCRIPT="ppa-tool" VERSION="2.0.1" DATE="2014-03-26" RELEASE="$(lsb_release -si) $(lsb_release -sr)" [ -n "`echo "$1" | grep ppa`" ] &amp;&amp; PPA=$1 [ -n "`echo "$2" | grep ppa`" ] &amp;&amp; PPA=$2 helpsection() { echo -e "Usage : $SCRIPT [OPTION]... [PPA]... -h, --help shows this help -c, --check check if [PPA] is available for your release Version $VERSION - $DATE" exit 0 } error() { echo -e "$SCRIPT - Oops, something went wrong\nTry « $SCRIPT --help » for more information." &amp;&amp; exit 0 ; } ppa_verification() { wget http://ppa.launchpad.net/$(echo $PPA | sed -e 's/ppa://g')/ubuntu/dists -O /tmp/"$SCRIPT-check.tmp" -q if [[ -n "`cat "/tmp/$SCRIPT-check.tmp" | grep $(lsb_release -sc)`" ]] ; then echo -e "$SCRIPT : '$PPA' is available for $RELEASE" else echo -e "$SCRIPT : '$PPA' is NOT available for $RELEASE" fi rm "/tmp/$SCRIPT-check.tmp" } [ "$1" == "--help" ] || [ "$1" == "-h" ] &amp;&amp; helpsection if [ "$1" == "--check" ] || [ "$1" == "-c" ] || [ "$1" == "check" ] ; then [ -n "`echo $2`" ] &amp;&amp; ppa_verification &amp;&amp; exit 0 error fi error </code></pre> <p>(<a href="http://ubuntuone.com/0unKXUZc917pH5UOsBAPOg">complete script</a> - <em><a href="http://ubuntuone.com/2Y6Azu4xohUbUdldPC1KWi">also in French</a></em>)</p> <p>Apparently, my syntax is bad, but I don't see what I could do to improve this, and I don't understand the feedback I recieved. Could you help me figure it out ?</p> <p>EDIT: From Unix&amp;Linux (where I first posted, but was redirected here), someone said it wasn't good to use capital letters for variables. So $SCRIPT should become $script. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:58:33.697", "Id": "79268", "Score": "0", "body": "@Jamal : are you sure this is a better title than \"Bash script : how to know if it's written correctly?\" ? Because if the script itself is for PPA's handling, the main reason I'm here is to find out where I'm wrong with my BASH, not with the stuff the script does at the end" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:02:26.017", "Id": "79269", "Score": "3", "body": "I can assure that this title is better! Here we are doing review so asking for : how to know if it's written correctly is not relevant. And you should not include tag in the title. So yes the title is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:23:22.480", "Id": "79275", "Score": "0", "body": "OP edited, now the full script is in English, should help the reviewers." } ]
[ { "body": "<h3>User experience</h3>\n\n<ul>\n<li><code>-h</code> or <code>--help</code> should print the usage message to standard output, which you do. However, on any unrecognizable command line, you should print the same (or similar) message to standard error and exit with a non-zero status.</li>\n<li>Similarly, other error messages should go to standard error and result in a non-zero status.</li>\n</ul>\n\n<h3>Style issues</h3>\n\n<ul>\n<li>Good job, double-quoting almost every variable you used. A lot of shell programmers neglect to do so.</li>\n<li>Good job, breaking the program up into functions. A lot of shell programmers don't.</li>\n<li>Indent your code consistently. It's hard to see where your functions begin and end.</li>\n<li>Make use of <code>case</code> to replace convoluted <code>if</code> statements.</li>\n<li>Do all of your command-line parsing in one place, and have a coherent parsing strategy. You can either use <code>getopt</code> (which has a bit of a learning curve) or build something based on <code>shift</code> (which is easier for a beginner to understand).</li>\n<li>You can pass parameters to functions. Passing <code>$PPA</code> to <code>ppa_verification()</code> would be more elegant than using a global.</li>\n</ul>\n\n<p>There isn't 100% consensus on whether variable names should be <code>$ALL_CAPS</code> or <code>$lower_case</code>. One common convention is <code>$ALL_CAPS</code> for global and/or exported variables, <code>$lower_case</code> for local or non-exported variables.</p>\n\n<h3>Use of <code>wget</code></h3>\n\n<ul>\n<li>Instead of writing the output of <code>wget</code> to a temporary file, you could just pipe it to <code>grep</code> directly: <code>wget -q -O - \"$url\" | grep -q \"$release\"</code>.</li>\n<li>But then, to distinguish between a <code>wget</code> failure (e.g. network problem) and the release not being found by <code>grep</code>, you would have to interrogate <code>${PIPESTATUS[0]}</code> and <code>${PIPESTATUS[1]}</code>, which is a bit complicated.</li>\n<li>Why not try to fetch the subdirectory of <code>dists/</code> that you care about instead? Then you only need to test whether the server returned an HTTP 200 (Success!) or HTTP 404 (Not Found).</li>\n</ul>\n\n\n\n<pre><code>#! /bin/bash\nSCRIPT=\"ppa-tool\"\nVERSION=\"200_success\"\nDATE=\"2014-03-26\"\nRELEASE=\"$(lsb_release -si) $(lsb_release -sr)\"\n\nhelpsection() \n{ \n echo \"Usage : $SCRIPT [OPTION]... [PPA]... \n-h, --help shows this help\n-c, --check check if [PPA] is available for your release\n\nVersion $VERSION - $DATE\"\n}\n\nppa_verification()\n{ \n local ppa=\"${1#ppa:}\"\n\n local codename=\"$(lsb_release -sc)\"\n local url=\"http://ppa.launchpad.net/$ppa/ubuntu/dists/$codename/\"\n\n wget \"$url\" -q -O /dev/null\n ######################################################################\n # Exit Status\n #\n # Wget may return one of several error codes if it encounters problems.\n # 0 No problems occurred.\n # 1 Generic error code.\n # 2 Parse error--for instance, when parsing command-line options, the `.wgetrc' or `.netrc'...\n # 3 File I/O error.\n # 4 Network failure.\n # 5 SSL verification failure.\n # 6 Username/password authentication failure.\n # 7 Protocol errors.\n # 8 Server issued an error response.\n ######################################################################\n case $? in\n 0) # Success\n echo \"$SCRIPT : '$ppa' is available for $RELEASE\"\n ;;\n 8) # HTTP 404 (Not Found) would result in wget returning 8\n echo \"$SCRIPT : '$ppa' is NOT available for $RELEASE\"\n return 1\n ;;\n *)\n echo \"$SCRIPT : Error fetching $url\" &gt;&amp;2\n return 3\n esac\n}\n\nPPA=\nwhile [ -n \"$*\" ] ; do\n case \"$1\" in\n -h|--help)\n helpsection\n exit 0\n ;;\n --check=*)\n PPA=\"${1#*=}\"\n ;;\n -c|--check|check)\n PPA=\"$2\"\n shift\n ;;\n *)\n helpsection &gt;&amp;2\n exit 2\n ;;\n esac\n shift\ndone\n\nif [ -z \"$PPA\" ]; then\n helpsection &gt;&amp;2\n exit 2\nfi\n\nppa_verification \"$PPA\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T08:18:52.783", "Id": "79533", "Score": "0", "body": "Thank you !! I don't understand everything but I'll make my homeworks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:01:01.480", "Id": "79696", "Score": "0", "body": "There's a little mistake in your $url (from ppa_verification), it should be `local url=\"http://ppa.launchpad.net/$ppa/ubuntu/dists/$codename/\"`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:02:59.537", "Id": "79697", "Score": "0", "body": "A mistake in my code or your your code? I thought I was silently fixing a bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:13:13.797", "Id": "79698", "Score": "0", "body": "Yours. The suggested method is great, but you made a mistake with the url, it shouldn't have '/ppa' inside it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:35:53.747", "Id": "79705", "Score": "0", "body": "Do you expect the user to include `…/ppa` in the parameter then? How else would it work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T00:18:53.127", "Id": "79716", "Score": "0", "body": "I think you're missing the point : the correct url is `**/$ppa/ubuntu/**`, and NOT `**/$ppa/ppa/ubuntu/**` -> You put a `/ppa` directory in the URL that does not exists on Launchpad" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T00:21:31.403", "Id": "79717", "Score": "0", "body": "there is indeed a `/ppa` in http://ppa.launchpad.net/libreoffice/ppa/ubuntu/dists/saucy/ , but do not forget that there is none in http://ppa.launchpad.net/webupd8team/java/ubuntu/dists/saucy/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T01:04:24.487", "Id": "79724", "Score": "0", "body": "I see the `…/ppa` suffix is a convention that some (but not all) PPAs follow, so it would have to be specified on the command line by the user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T09:43:11.553", "Id": "79742", "Score": "1", "body": "it is specified by the user, always. The convention is ppa:user/directory. With `apt`, for example `apt-add-repository ppa:user/directory`, and it is the same with this script." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T07:06:36.920", "Id": "45469", "ParentId": "45445", "Score": "7" } } ]
{ "AcceptedAnswerId": "45469", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T22:23:08.803", "Id": "45445", "Score": "8", "Tags": [ "bash", "shell" ], "Title": "Script for handling PPA's on Ubuntu" }
45445
<p>Ideally the Code Review would target the correctness of the approach implementing the Swing TreeModel.</p> <p>In particular, is the structural separation[1], event message passing, threading[2], object synchronisation, etc. all best practice ?</p> <ul> <li>[1] My understanding is that the TreeModel should have separation between the underlying Tree Model and the object reports changes to the Swing JTree.</li> <li>[2] My understanding is that there should be separate threads for UI and Model changes.</li> </ul> <p>In the interests of disclosure there is a bug that the UI doesn't show new child nodes once the parent node has been expanded in the UI.</p> <p>Once any issues with the correctness of the approach are sorted, and if the bug still exits, assistance in this area would be appreciated.</p> <p><a href="https://github.com/xenomorpheus/MutableJTreeModel">Full Runnable Package is on Github</a></p> <p>Aside: Please note I'm still pretty new to this Code Review site, Swing and Java. I have read and tried to follow the question guidelines.</p> <p>CLASS: Node - A Node in the Tree Model.</p> <pre><code>/** This document is AS-IS. No claims are made for suitability for any purpose. */ package com.example.mutablejtreemodel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import java.util.logging.Logger; import javax.swing.tree.TreePath; /** * A node in a tree structure. * * Nodes will fire change events to listeners which can be other nodes, or * JTreeModel objects. * * @author xenomorpheus * @version $Revision: 1.0 $ */ public class Node implements ActionListener { /** class logger */ private static final Logger LOGGER = Logger.getLogger(Node.class.getName()); /** synchronisation lock */ private static final Object OBJ_LOCK = new Object(); // Read more: // http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html#ixzz2wy76gzSj /** The human identifiable name of this node. */ private String name; /** Our parent node. */ private Node parent; /** The child nodes of this node. */ private List&lt;Node&gt; children; /** * Those that listen for changes to the model. E.g. other nodes or * JTreeModel. Using weak references for listener set. It's very easy to * forget removing listeners when the actual instance isn't in use any more * and thats a source of memory leak. */ private Set&lt;ActionListener&gt; listeners; /** * Constructor. * * @param name * the human identifiable name of this node. */ public Node(String name) { this.name = name; children = new ArrayList&lt;&gt;(); listeners = Collections .newSetFromMap(new WeakHashMap&lt;ActionListener, Boolean&gt;(32, 0.75f)); } /** Constructor. */ public Node() { this("No Name"); } /** * Set the parent Node. * * @param parent * the new parent. */ public void setParent(Node parent) { synchronized (OBJ_LOCK) { this.parent = parent; } } /** * @return the parent node. */ public Node getParent() { synchronized (OBJ_LOCK) { return parent; } } // Tree related methods. /** * @return True only if the node has no children. */ public boolean isLeaf() { return false; } /** * * @return The number of child nodes. */ public int getChildCount() { synchronized (OBJ_LOCK) { return children.size(); } } /** * Return the child node at this position. * * @param index * the position of the child node. * * @return the child node at this position. */ public Node getChild(int index) { synchronized (OBJ_LOCK) { Node child = children.get(index); LOGGER.info("At index=" + index + " found child named '" + child.name + "'"); return child; } } /** * Return the position number this child node is at. * * @param child * the child node to look for. * * @return the position number. */ public int getIndexOfChild(Node child) { synchronized (OBJ_LOCK) { int index = children.indexOf(child); LOGGER.info("getIndexOfChild: In node '" + name + "' found child " + child.name + " at index " + index); return index; } } /** * Return true only if the node is one of our direct children. * * @param node * node we are looking for. * * @return true only if found as a direct child of this object. */ public boolean isOurChild(Node node) { synchronized (OBJ_LOCK) { return children.contains(node); } } /** * Add the child node to the end of a list of children nodes. * * @param child * new child node. */ public void add(Node child) { // Wrapped in sync to ensure size is still correct when add is called. synchronized (OBJ_LOCK) { add(child, children.size()); } } /** * Insert the child to the list of children nodes, at the point specified. * * @param child * new child node. * @param childCount * insertion point. */ public void add(Node child, int childCount) { LOGGER.info("Parent='" + name + "', child='" + child + "' at index=" + childCount); synchronized (OBJ_LOCK) { // child node from current parent, if any. Node currentContainer = child.getParent(); if (null != currentContainer) { currentContainer.remove(child); } // add child to children. children.add(childCount, child); child.setParent(this); // We listen for changes on nodes we hold. child.addActionListener(this); // We inform listeners that we have changed because we have a new // node. fireNodeChanged(new ActionEvent(child, childCount, NodeChangeType.NODE_INSERTED.toString())); } } /** * Remove one of our direct child nodes. * * @param child * the time to remove. */ public void remove(Node child) { LOGGER.info("remove node=" + this); synchronized (OBJ_LOCK) { children.remove(child); child.setParent(null); // Stop listening to child node. child.removeActionListener(this); } } /** * @return a path of nodes leading up to the root node. */ public TreePath getPathToRoot() { Node node = this; ArrayList&lt;Node&gt; nodeArrayList = new ArrayList&lt;Node&gt;(); synchronized (OBJ_LOCK) { while ((null != node)) { nodeArrayList.add(node); node = node.getParent(); } return new TreePath(nodeArrayList.toArray(new Node[nodeArrayList .size()])); } } /** * Notify Listeners that this node has changed in some way. e.g. this node * is about to be die. * * @param e * event. */ private void fireNodeChanged(ActionEvent e) { LOGGER.info("fireTreeNodeChanged node='" + this + "'"); synchronized (OBJ_LOCK) { for (ActionListener listener : listeners) { listener.actionPerformed(e); } } } /** * Remove a listener from the list that wish to listen to events involving * this node. * * @param listener * listener to add. */ public void addActionListener(ActionListener listener) { LOGGER.info("addActionListener for '" + this + "', listener='" + listener + "'"); synchronized (OBJ_LOCK) { listeners.add(listener); } } /** * Add a listener to the list that wish to listen to events involving this * node. * * @param listener * listener to remove. */ public void removeActionListener(ActionListener listener) { LOGGER.info("removeActionListener for '" + this + "', listener=" + listener); synchronized (OBJ_LOCK) { listeners.remove(listener); } } // Misc. methods. /** * Request the destruction of this node. Notify the listeners of this node * of the death. */ public void destroy() { ActionEvent event; LOGGER.info("destroy node=" + this); // Notify listeners this node is being destroyed. event = new ActionEvent(this, 0, NodeChangeType.NODE_REMOVED.toString()); fireNodeChanged(event); // If parent still set, remove this node from parent. synchronized (OBJ_LOCK) { if (null != parent) { parent.remove(this); } } // TODO free resources of this node at this subtype. // TODO call parent class's destroy. } /** * Perform actions when we are notified about an event. e.g. the death of * one of our child nodes. * * @param e * the event we have been informed about. * * @see java.awt.event.ActionListener#actionPerformed(ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { LOGGER.info("actionPerformed, event=" + e.toString()); String command = e.getActionCommand(); Object source = e.getSource(); if (NodeChangeType.NODE_REMOVED.toString().equals(command)) { LOGGER.info(command + " event"); if (source instanceof Node) { Node child = (Node) source; LOGGER.info("actionPerformed, Source is node=" + child); synchronized (OBJ_LOCK) { if (children.contains(child)) { LOGGER.info("actionPerformed, '" + this + "' removing child node called='" + child + "'"); children.remove(child); } } } } } } </code></pre> <p>CLASS: NodeJTreeModel - The Swing JTree will listen to and instance of this TreeModel to recieve notification of changes to the underlying Model ( of Node objects in a tree ). </p> <pre><code>/** This document is AS-IS. No claims are made for suitability for any purpose. */ package com.example.mutablejtreemodel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.Set; import java.util.WeakHashMap; import java.util.logging.Logger; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; /** * Objects of this class form an adapter between a JTree and the model, that * being a tree of Node objects. * * The methods in this class allow the JTree component to traverse the tree. * * @author xenomorpheus * @version $Revision: 1.0 $ **/ public class NodeJTreeModel implements TreeModel, ActionListener { /** class logger */ private static final Logger LOGGER = Logger.getLogger(NodeJTreeModel.class .getName()); /** * synchronisation lock. * http://javarevisited.blogspot.com/2011/04/synchronization * -in-java-synchronized.html#ixzz2wy76gzSj */ private static final Object OBJ_LOCK = new Object(); /** We specify the root directory when we create the model. */ private Node root; /** * Those that listen for changes to the model. Using weak references for * listener set. It's very easy to forget removing listeners when the actual * instance isn't in use any more and thats a source of memory leak. */ private Set&lt;TreeModelListener&gt; listeners; /** * Constructor. */ public NodeJTreeModel() { listeners = Collections .newSetFromMap(new WeakHashMap&lt;TreeModelListener,Boolean&gt;(32, 0.75f)); } // Getters and Setters /** * The model knows how to return the root object of the tree. * * @return Object * @see javax.swing.tree.TreeModel#getRoot() */ @Override public Object getRoot() { return root; } /** * Set the root node. * * @param root * set the root node that this TreeModel is listening to. */ public void setRoot(Node root) { this.root = root; root.addActionListener(this); } // Misc methods /** * Notifies the listener that the structure below a given node has been * completely changed. * * @param path * the sequence of nodes that lead up the tree to the root node. */ private void fireStructureChanged(TreePath path) { TreeModelEvent event = new TreeModelEvent(this, path); synchronized (OBJ_LOCK) { for (TreeModelListener lis : listeners) { lis.treeStructureChanged(event); } } } /** * Notifies the listener that some nodes have been removed below a node. * * @param parentPath * the sequence of nodes from the parent node to the root node. * @param indices * @param nodes */ private void fireNodesRemoved(TreePath parentPath, int[] indices, Object[] nodes) { TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, nodes); synchronized (OBJ_LOCK) { for (TreeModelListener lis : listeners) { lis.treeNodesRemoved(event); } } } /** * Notifies the listener that a particular node has been removed. * * @param path * @param index * @param node */ private void fireNodeRemoved(TreePath path, int index, Object node) { fireNodesRemoved(path, new int[] { index }, new Object[] { node }); } /** * Notifies the listener that the appearance of some sub-nodes a node has * changed. * * @param parentPath * @param indices * @param nodes */ private void fireNodesChanged(TreePath parentPath, int[] indices, Object[] nodes) { TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, nodes); synchronized (OBJ_LOCK) { for (TreeModelListener lis : listeners) { lis.treeNodesChanged(event); } } } /** * Notifies the listener that the appearance of a node has changed. * * @param parentPath * the path of the parent node of the relevant node. * @param index * the index of the node under the parent node. If &lt;0, the * listener will not be notified. * @param node * the subnode. */ private void fireNodeChanged(TreePath parentPath, int index, Object node) { if (index &gt;= 0) { fireNodesChanged(parentPath, new int[] { index }, new Object[] { node }); } } /** * Notifies listeners that below a node, some nodes were inserted. * * @param parentPath * TreePath * @param indices * int[] * @param subNodes * Object[] */ private void fireNodesInserted(TreePath parentPath, int[] indices, Object[] subNodes) { TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, subNodes); synchronized (OBJ_LOCK) { for (TreeModelListener lis : listeners) { lis.treeNodesInserted(event); } } } /** * Notifies the listener that a node has been inserted. * * @param parentPath * @param index * @param node */ private void fireNodeInserted(TreePath parentPath, int index, Object node) { fireNodesInserted(parentPath, new int[] { index }, new Object[] { node }); } /** * Method actionPerformed. * * @param e * ActionEvent * @see java.awt.event.ActionListener#actionPerformed(ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); NodeChangeType command = NodeChangeType.get(e.getActionCommand()); int id = e.getID(); LOGGER.info("actionPerformed was called: " + e); LOGGER.info(" source =" + source); LOGGER.info(" command =" + command); LOGGER.info(" ID =" + id); if (source instanceof Node) { Node node = (Node) source; LOGGER.info("command type: " + command); LOGGER.info("fire events: Node path to root" + node.getPathToRoot()); switch (command) { case STRUCTURE_CHANGED: fireStructureChanged(node.getPathToRoot()); break; // case NODES_REMOVED: // fireNodesRemoved(node.getParent().getPathToRoot(), indices, // nodes); // break; case NODE_REMOVED: fireNodeRemoved(node.getParent().getPathToRoot(), id, node); break; // case NODES_CHANGED: // fireNodesChanged(node.getParent().getPathToRoot(), indices, // nodes); // break; case NODE_CHANGED: fireNodeChanged(node.getParent().getPathToRoot(), id, node); break; // case NODES_INSERTED: // fireNodesInserted(node.getParent().getPathToRoot(), indices, // subNodes); // break; case NODE_INSERTED: fireNodeInserted(node.getParent().getPathToRoot(), id, node); break; default: LOGGER.info("Unsupported command type: " + command); } } } /** * Method addTreeModelListener. * * @param listener * TreeModelListener * @see javax.swing.tree.TreeModel#addTreeModelListener(TreeModelListener) */ @Override public void addTreeModelListener(TreeModelListener listener) { LOGGER.info("Adding Listener: " + listener); synchronized (OBJ_LOCK) { listeners.add(listener); } } /** * Method removeTreeModelListener. * * @param listener * TreeModelListener * @see javax.swing.tree.TreeModel#removeTreeModelListener(TreeModelListener) */ @Override public void removeTreeModelListener(TreeModelListener listener) { LOGGER.info("Remove Listener: " + listener); synchronized (OBJ_LOCK) { listeners.remove(listener); } } /** * Tell JTree whether an object in the tree is a leaf or not. * * * @param node * Object * @return tree if node is a leaf. * @see * javax.swing.tree.TreeModel#isLeaf(Object) */ @Override public boolean isLeaf(Object node) { return ((Node) node).isLeaf(); } /** * Tell JTree how many children a node has. * * * @param node * Object * @return how many children. * @see * javax.swing.tree.TreeModel#getChildCount(Object) */ @Override public int getChildCount(Object node) { int count = ((Node) node).getChildCount(); LOGGER.info("node='" + node + "', count=" + count); return count; } /** * Fetch any numbered child of a node for the JTree. Our model returns * MyNode objects for all nodes in the tree. The JTree displays these by * calling the MyNode.toString() method. * * @param parent * @param index * * @return child at the requested index. * @see * javax.swing.tree.TreeModel#getChild(Object, int) */ @Override public Object getChild(Object parent, int index) { Node child = ((Node) parent).getChild(index); LOGGER.info("getChild - parent=" + parent + ", index=" + index + ", RETURN child=" + child); return child; } /** * Figure out a child's position in its parent node. * * @param parent * the parent node * @param child * the child node to find index of. * @return int * @see javax.swing.tree.TreeModel#getIndexOfChild(Object, Object) */ @Override public int getIndexOfChild(Object parent, Object child) { int index = ((Node) parent).getIndexOfChild((Node) child); LOGGER.info("getIndexOfChild - parent=" + parent + ", child=" + child + ", RETURN index=" + index); return index; } /** * This method is only invoked by the JTree for editable trees. * * @param path * TreePath * @param newValue * Object * @see javax.swing.tree.TreeModel#valueForPathChanged(TreePath, Object) */ @Override public void valueForPathChanged(TreePath path, Object newValue) { LOGGER.info("valueForPathChanged path=" + path + ", newValue=" + newValue); Node node = (Node) path.getLastPathComponent(); node.setName((String) newValue); } /** * * @return string representation of this object. */ public String toString() { return this.getClass().getSimpleName(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:50:01.240", "Id": "79331", "Score": "0", "body": "I have updated the code on GitHub as per @rolfl suggestions. 1) Node lock is now per node, not static. 2) Listeners don't lead the lock. 3) Replaced weakHashMap with list." } ]
[ { "body": "<h2>static</h2>\n<p>What a difference 1 word can make:</p>\n<blockquote>\n<pre><code>/** synchronisation lock */\nprivate static final Object OBJ_LOCK = new Object();\n</code></pre>\n</blockquote>\n<p>That 1 word is <em>'static'</em>.</p>\n<p>In this case, each and every Node shares the exact same OBJ_LOCK instance.</p>\n<p>But, that instance is only used to control details inside the actual <code>Node</code>.</p>\n<p>What you are doing is locking all threads accessing ANY Node, even though you are only changing the details in one node.</p>\n<p>Remove the <code>static</code>, and change the case to <code>objLock</code>, and you should have better thread concurrency.</p>\n<h2>Listeners</h2>\n<blockquote>\n<pre><code>private void fireNodeChanged(ActionEvent e) {\n LOGGER.info(&quot;fireTreeNodeChanged node='&quot; + this + &quot;'&quot;);\n synchronized (OBJ_LOCK) {\n for (ActionListener listener : listeners) {\n listener.actionPerformed(e);\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>This code 'leaks' the lock on the listeners. While you are calling the <code>actionPerformed(e)</code> events in the listeners you are still locking this <code>Node</code> (in fact, every <code>Node</code>).</p>\n<p>You only need to synchronize the access to the <code>listeners</code> data. A simple way to solve this is to:</p>\n<pre><code>private void fireNodeChanged(ActionEvent e) {\n LOGGER.info(&quot;fireTreeNodeChanged node='&quot; + this + &quot;'&quot;);\n ActionListener[] tmpListeners = null;\n synchronized (OBJ_LOCK) {\n tmpListeners = listeners.toArray(new ActionListener[listeners.size()]);\n }\n for (ActionListener listener : tmpListeners) {\n listener.actionPerformed(e);\n }\n\n}\n</code></pre>\n<p>Now there is not a lock-leak.</p>\n<p>This type of problem happens in a few places.</p>\n<h2>WeakHashMap</h2>\n<blockquote>\n<pre><code>listeners = Collections\n .newSetFromMap(new WeakHashMap&lt;TreeModelListener,Boolean&gt;(32, 0.75f));\n</code></pre>\n</blockquote>\n<p>This is not doing what you think it does.</p>\n<p>Because the <code>TreeModelListener</code> instances are the key to the WeakHashMap, they will never be garbage-collected (the key is a strong-reference....).</p>\n<p>Using a WeakHashMap is complicated, and harder to describe than what can easily go here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:00:02.587", "Id": "79334", "Score": "0", "body": "Thank you for the great suggestions. Any thoughts on the bug when new child nodes not showing up after a node has been expanded in UI? I have updated the code on GitHub. 1) Node lock is now per node, not static. 2) Listeners don't lead the lock. 3) Replaced weakHashMap with list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T00:38:43.320", "Id": "45451", "ParentId": "45449", "Score": "2" } } ]
{ "AcceptedAnswerId": "45451", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T23:30:53.967", "Id": "45449", "Score": "6", "Tags": [ "java", "thread-safety", "tree", "swing", "event-handling" ], "Title": "Correctly implementing the Swing TreeModel" }
45449
<p>I'm trying to design a binary relation interface in Java and then implement it, but I'm not sure if I'm doing it right. I'd really appreciate a little feedback just so I know if I'm way in the wrong direction or not.</p> <p>This is what I've got so far:</p> <p>Interface:</p> <pre><code>public boolean compare(Object that, Object ths); // compares relations to see if they are equal. public Set&lt;Y&gt; getY(X value); //return set of all Y values with relation X public Set&lt;X&gt; getX(Y value); //return set of all X values with relation Y public void clear(); //clear relation of values public Set&lt;Relation&lt;X, Y&gt;&gt; delY(X value); //remove all relations containing given Y public Set&lt;Relation&lt;X, Y&gt;&gt; delX(Y value); //remove all relations containing given X public String write(Object that); //output Relation in string format public Y addPair (X valX, Y valY); //adds the entry (X, Y) to the Relation public Y delPair (X valX, Y valY); //deletes entry (X, Y) from the Relation </code></pre> <p>Implementation:</p> <pre><code>int size; String[][] basket = new String[16][2]; String[][] bag = basket; public String addPair(String X, String Y){ basket[size][0] = X; basket[size][1] = Y; String pair = basket[size][0] + basket[size][1]; size++; return pair; } public boolean compare(String[][] that, String[][] ths){ that = basket; ths = bag; boolean equal; if(that.equals(ths)) equal = true; else equal = false; return equal; } public Set&lt;String&gt; getY(String X){ Set&lt;String&gt; Y = new TreeSet&lt;String&gt;(); for(int i = 0;i&lt;size;i++) { if(basket[i][0]==X) Y.add(basket[i][1]); } return Y; } public Set&lt;String&gt; getX(String Y){ Set&lt;String&gt; X = new TreeSet&lt;String&gt;(); for(int i = 0;i&lt;size;i++) { if(basket[i][1]==Y) X.add(basket[i][0]); } return X; } public String write(Object o){ o = basket; String out = ""; out += o.toString(); System.out.println("OUT: " + out); return out; } public void clear(){ for(int i = 0;i&lt;size;i++) { if(basket[i][0]!= null){ basket[i][0] = null; basket[i][1] = null; } } } public Set&lt;String&gt; delY(String X, Relation r){ Set&lt;String&gt; Y = new TreeSet&lt;String&gt;(); for(int i = 0;i&lt;size;i++) { if(basket[i][0]==X){ Y.add(basket[i][1]); basket[i][1]=null; } } return Y; } public Set&lt;String&gt; delX(String Y){ Set&lt;String&gt; X = new TreeSet&lt;String&gt;(); for(int i = 0;i&lt;size;i++) { if(basket[i][1]==Y){ X.add(basket[i][1]); basket[i][1]=null; } } return X; } public String delPair (String X, String Y){ X = "Orange"; Y = "Fruit"; for(int i = 0;i&lt;size;i++) { if(basket[i][0]==X &amp;&amp; basket[i][1]==Y){ basket[i][1]=null; basket[i][0]=null; } } return (X + Y); } </code></pre>
[]
[ { "body": "<p>There are a couple of things in here that concern me.... but, the most concerning is:</p>\n\n<p><strong>Use <code>.equals()</code> to compare String values</strong></p>\n\n<p>Code like this:</p>\n\n<blockquote>\n<pre><code>if(basket[i][0]==X){\n</code></pre>\n</blockquote>\n\n<p>will fail when you get data that is not String-constant data.</p>\n\n<p>That line should be:</p>\n\n<pre><code> if(basket[i][0].equals(X)){\n</code></pre>\n\n<p>This problem is found all over your code.</p>\n\n<hr>\n\n<p>In addition, there are other problems:</p>\n\n<ul>\n<li><p>your arrays are pre-sized. This code:</p>\n\n<blockquote>\n<pre><code>String[][] basket = new String[16][2];\n</code></pre>\n</blockquote>\n\n<p>is potentially OK if you are initializing the array, but what if there are more than 16 pairs?</p></li>\n<li><p>it would be better to create a 'Pair' class to contain your two strings, than to use the 2-size array on the <code>basket</code>. Then your <code>basket</code> could be something like:</p>\n\n<pre><code>StringPair[] basket = new StringPair[SIZE];\n</code></pre>\n\n<p>your StringPair class could look something like:</p>\n\n<pre><code>public class StringPair {\n private final String first, second;\n\n public StringPair(String first, String second) {\n this.first = first;\n this.second = second;\n }\n\n ..... getFirst() .....\n ..... getSecond() .....\n\n}\n</code></pre></li>\n<li><p><code>compare(String[][] that, String[][] ths)</code> is a method that needs no state data. It should be a static method, or a utility method. Alternatively, it should be a simple 1-value method <code>compare(MyClass that)</code> ... which, for what it is worth, would be very similar to the <code>equals(...)</code> method.</p>\n\n<p>but, that method is pretty broken. It has the two input parameters <code>that</code> and <code>ths</code>, but it then overwrites those values with the internal versions <code>bag</code> and <code>basket</code>.</p>\n\n<blockquote>\n<pre><code>that = basket;\nths = bag;\nboolean equal;\n\nif(that.equals(ths))\n equal = true;\nelse\n equal = false;\nreturn equal;\n</code></pre>\n</blockquote>\n\n<p>now, since you set <code>bag = basket</code> earlier, this will always return <code>true</code>.</p>\n\n<p>Further, that last 5 lines of the method can be replaced with:</p>\n\n<pre><code>return (that.equals(ths));\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T01:13:08.097", "Id": "45454", "ParentId": "45452", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T00:44:44.610", "Id": "45452", "Score": "5", "Tags": [ "java", "interface" ], "Title": "Binary relation interface" }
45452
<p>Below is some code which verifies a credit card number using the checksum as well as check if number of digits are appropriate as well if digits start with right numbers. I am not sure if converting the <code>double</code> into a string was the best bet. I wasn't going to at first but had trouble figuring out the modulo math to get every second digit without knowing the length of the <code>double</code> (# of digits).</p> <p>Also, in my use of <code>strtok()</code>, what should I be doing with the balance of the string after the delimiter? Is that hanging out in memory somewhere?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main(void) { double cardnumber; printf("Give me a number: \n"); scanf("%lf", &amp;cardnumber); if(cardnumber &lt; 1000000000000 || cardnumber &gt; 10000000000000000) { printf("INVALID\n"); return 0; } if(cardnumber &lt; 100000000000000 &amp;&amp; cardnumber &gt; 9999999999999) { printf("INVALID\n"); return 0; } char creditcard[17]; sprintf(creditcard, "%f", cardnumber); char* ptr_cc; ptr_cc = strtok(creditcard,"."); int card_size = strlen(ptr_cc); int sum = 0; for(int i = 1; i &lt; card_size; i+=2) { int x = creditcard[card_size-1-i] - '0'; int prod = 2 * x; if(prod&gt;=10) { prod = prod%10 + prod/prod%10; } sum += prod; } for(int i = 0; i &lt; card_size; i+=2) { int x = creditcard[card_size-1-i] - '0'; sum += x; } if(sum%10 != 0) { printf("INVALID\n"); return 0; } else if(creditcard[0] == '4') { printf("VISA\n"); return 0; } else if(creditcard[0] == '3' &amp;&amp; (creditcard[1] == '7' || creditcard[1] =='4')) { printf("AMEX\n"); return 0; } else if(creditcard[0] == '5' &amp;&amp; (creditcard[1] &gt;='1' &amp;&amp; creditcard[1] &lt;='5')) { printf("MASTERCARD\n"); return 0; } else { printf("INVALID\n"); return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T02:49:59.473", "Id": "79285", "Score": "5", "body": "I'd suggest never storing the `number` in a `double` in the first place. The card `number` is really a digit string; note that the format technically allows a leading digit of `0`. [ Wikipedia]. [Another example of a number that isn't is a 'phone number'.] Using a string has the natural benefit that you can allow the I/O to have internal spaces as well - making it much more usable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-15T05:50:34.217", "Id": "177309", "Score": "0", "body": "Agree with the spaces. User interface should allow the gaps to be captured. Also beware of your description, this code does not \"verify\" a card, it \"validates\" the card number. One of the major weaknesses of the Luhn check is that you can swap adjacent middle digits if they are both under 5 and the number will still pass.." } ]
[ { "body": "<p>As @Keith says, credit card numbers should be treated as strings, not numbers, and definitely not floating-point numbers. If you want to ensure that the input contains only digits (and maybe spaces), use <code>strspn()</code>. Squeeze out any spaces, then validate the length using <code>strlen()</code>.</p>\n\n<p>The Luhn checksum check should be in its own function. The loop indexes would be more natural counting down, I think, since you are taking every other digit starting from the right.</p>\n\n<pre><code>int is_valid_luhn(const char *creditcard)\n{\n int card_size = strlen(creditcard);\n int sum = 0;\n for(int i = card_size - 2; i &gt;= 0; i -= 2)\n {\n int digit = creditcard[i] - '0';\n int prod = 2 * digit;\n sum += prod / 10 + prod % 10; /* No special case needed */\n }\n for(int i = card_size - 1; i &gt;= 0; i -= 2)\n {\n sum += creditcard[i] - '0';\n }\n return sum % 10 == 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:09:28.670", "Id": "45474", "ParentId": "45455", "Score": "12" } }, { "body": "<h1>Things you did well</h1>\n\n<ul>\n<li><p>Readability - everything was well organized and spaced neatly.</p></li>\n<li><p>Initializing variables within your <code>for</code> loops/adhering to the C99 standard (which is the minimum you should abide by in my opinion).</p></li>\n<li><p>Marking your function arguments as <code>void</code> when you don't take in any parameters.</p></li>\n<li><p>Use of <code>double</code> instead of <code>float</code> (even though you should be using a string to represent the credit card number).</p></li>\n<li><p>Implementation of the <a href=\"https://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">Luhn algorithm</a>, even though it isn't the most elegant. @200_success covered that in depth (+1 to that answer), I won't go into it.</p></li>\n</ul>\n\n<h1>Things you could improve</h1>\n\n<h3>Bugs</h3>\n\n<ul>\n<li><p>As already noted, you should be using strings to hold the credit card numbers, not integers, and especially not floating point numbers. But I won't completely re-iterate what has been already mentioned.</p></li>\n<li><p>Right now you are using the <code>float</code> format (<code>%f</code>) to compose a string.</p>\n\n<blockquote>\n<pre><code>sprintf(creditcard, \"%f\", cardnumber);\n</code></pre>\n</blockquote>\n\n<p>This didn't work for me when I ran the program on my system, and caused a error to be thrown during runtime. Since <code>cardnumber</code> was declared as a <code>double</code>, you should use the general format instead, which can handle both <code>float</code> and <code>double</code> types.</p>\n\n<pre><code>sprintf(creditcard, \"%g\", cardnumber);\n</code></pre></li>\n</ul>\n\n<h3>Variables/Initialization</h3>\n\n<ul>\n<li><p><code>card_size</code> will lose integer precision because of the implicit conversion from an <code>unsigned long</code> to <code>int</code>.</p>\n\n<blockquote>\n<pre><code>int card_size = strlen(ptr_cc);\n</code></pre>\n</blockquote>\n\n<p>You could either manually cast the return value from <code>strlen()</code> to an <code>int</code>, or you could simply declare the type of <code>card_size</code> to be <code>unsigned long</code> or <a href=\"https://stackoverflow.com/questions/2550774/what-is-size-t-in-c\"><code>size_t</code></a>.</p>\n\n<pre><code>size_t card_size = strlen(ptr_cc)\n</code></pre></li>\n</ul>\n\n<h3>Standards</h3>\n\n<ul>\n<li><p><code>strtok</code> is limited to tokenizing only one string (with one set of delimiters) at a time, and it can't be used while threading. Therefore, <code>strtok</code> is considered deprecated. </p>\n\n<p>Instead, use <a href=\"http://linux.die.net/man/3/strtok_r\" rel=\"nofollow noreferrer\"><code>strtok_r</code></a> or <code>strtok_s</code> which are threading-friendly versions of <code>strtok</code>. The POSIX standard provided <code>strtok_r</code>, and the C11 standard provides <code>strtok_s</code>. The use of either is a little awkward, because the first call is different from the subsequent calls.</p>\n\n<ol>\n<li><p>The first time you call the function, send in the string to be parsed as the first argument.</p></li>\n<li><p>On subsequent calls, send in NULL as the first argument.</p></li>\n<li><p>The last argument is the scratch string. You don't have to initialize it on first use; on subsequent uses it will hold the string as it is parsed so far.</p></li>\n</ol>\n\n<p>To demonstrate its use, I've written a simple line counter (of only non-blank lines) using the POSIX standard one. I'll leave the choice of what version to use and implementation into your program up to you.</p>\n\n<pre><code>#include &lt;string.h&gt; // strtok_r\n\nint countLines(char* instring)\n{\n int counter = 0;\n char *scratch, *txt;\n char *delimiter = \"\\n\";\n for (; (txt = strtok_r((!counter ? instring : NULL), delimiter, &amp;scratch)); counter++);\n return counter;\n}\n</code></pre>\n\n<p>If you implement this, you have your question answered.</p>\n\n<blockquote>\n <p>Also, in my use of <code>strtok()</code>, what should I be doing with the balance\n of the string after the delimiter? Is that hanging out in memory\n somewhere?</p>\n</blockquote>\n\n<p>It's not hanging out in memory, it's in the scratch string you provided.</p></li>\n<li><p>You don't have to return <code>0</code> at the end of <code>main()</code>, just like you wouldn't bother putting <code>return;</code> at the end of a <code>void</code>-returning function. The C standard knows how frequently this is used, and lets you not bother.</p>\n\n<blockquote>\n <p><strong>C99 &amp; C11 §5.1.2.2(3)</strong></p>\n \n <p>...reaching the <code>}</code> that terminates the <code>main()</code> function returns a\n value of <code>0</code>.</p>\n</blockquote></li>\n</ul>\n\n<h3>Syntax/Styling</h3>\n\n<ul>\n<li><p>You don't have to return inside every conditional test.</p>\n\n<blockquote>\n<pre><code>if(sum%10 != 0)\n{\n printf(\"INVALID\\n\");\n return 0; \n}\nelse if(creditcard[0] == '4')\n{\n printf(\"VISA\\n\");\n return 0; \n}\nelse if(creditcard[0] == '3' &amp;&amp; (creditcard[1] == '7' || creditcard[1] =='4'))\n{\n printf(\"AMEX\\n\");\n return 0; \n}\nelse if(creditcard[0] == '5' &amp;&amp; (creditcard[1] &gt;='1' &amp;&amp; creditcard[1] &lt;='5'))\n{\n printf(\"MASTERCARD\\n\");\n return 0; \n}\nelse\n{\n printf(\"INVALID\\n\");\n return 0; \n}\n</code></pre>\n</blockquote>\n\n<p>You can pull out all of those <code>return 0;</code>'s out to the end of the entire test block, so you have the return in one place. But returning <code>0</code> is unnecessary, as seen in my previous points.</p></li>\n<li><p>You don't return unique identifiers when you encounter an error.</p>\n\n<blockquote>\n<pre><code>if(cardnumber &lt; 100000000000000 &amp;&amp; cardnumber &gt; 9999999999999)\n{\n printf(\"INVALID\\n\");\n return 0; \n}\n</code></pre>\n</blockquote>\n\n<p>Using unique identifiers will aid you a lot in debugging, because it can help you pinpoint where something went wrong. Typically, positive numbers are used to indicate errors.</p>\n\n<pre><code>if(cardnumber &lt; 100000000000000 &amp;&amp; cardnumber &gt; 9999999999999)\n{\n printf(\"INVALID\\n\");\n return 1; \n}\n</code></pre></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow noreferrer\"><code>puts()</code></a> instead of <code>printf()</code> when you aren't formatting a string.</p>\n\n<pre><code>puts(\"INVALID\");\n</code></pre></li>\n<li><p>Prefer <a href=\"http://www.cplusplus.com/reference/cstdio/snprintf/\" rel=\"nofollow noreferrer\"><code>snprintf()</code></a> to <code>sprintf()</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T00:25:56.563", "Id": "79815", "Score": "2", "body": "A `double` can accurately store every integer [up to 9,007,199,254,740,992](http://en.wikipedia.org/wiki/Double-precision_floating-point_format). Sixteen-digit integers 9007 1992 5474 0993 and higher will be rounded to an even number. Fortunately, the largest valid number you need to accept is a 16-digit MasterCard number of the form 55xx xxxx xxxx xxxx. Still, using any kind of floating point to handle what should be an exact string of digits is playing with fire!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T22:33:19.890", "Id": "45714", "ParentId": "45455", "Score": "11" } }, { "body": "<p>The other answers offer great advice, but I have some things to add pertaining to naming:</p>\n\n<ul>\n<li><p>This doesn't sound like a good input prompt:</p>\n\n<blockquote>\n<pre><code>printf(\"Give me a number: \\n\");\n</code></pre>\n</blockquote>\n\n<p>Imagine, for a second, that the user briefly forgot what this program is for. If they see this prompt, they'll just input any number. Even with input validation, you should make the process as clear as possible for the user.</p>\n\n<p>Instead, you should ask specifically for a credit card number. Also consider using something more formal than \"give me\" at the start.</p>\n\n<pre><code>puts(\"Input a credit card number: \\n\");\n</code></pre>\n\n<p>(@syb0rg's advice regarding <code>puts()</code> also applies here.)</p></li>\n<li><p>Your variable naming is inconsistent:</p>\n\n<blockquote>\n<pre><code>double cardnumber;\n</code></pre>\n</blockquote>\n\n<p></p>\n\n<blockquote>\n<pre><code>int card_size;\n</code></pre>\n</blockquote>\n\n<p>The latter variable is an example of \"snake_case\" naming, which is an acceptable form of naming (the alternative being \"camelCase\").</p>\n\n<p>Since the former variable consists of two words, consider using the same naming convention with that and similar variables of the same form:</p>\n\n<pre><code>double card_number;\n</code></pre></li>\n<li><p>This variable sounds very generic:</p>\n\n<blockquote>\n<pre><code>int sum = 0;\n</code></pre>\n</blockquote>\n\n<p>Sum of what, exactly? Even if you're only summing one thing here, you should still name it based on what it's summing. It'll also be beneficial if you end up needing another sum-type variable.</p>\n\n<p>The same also applies to <code>prod</code>, which should <em>at least</em> be spelled out completely.</p></li>\n<li><p>Try to avoid single-character variable names (except for simple loop counters):</p>\n\n<blockquote>\n<pre><code>int x;\n</code></pre>\n</blockquote>\n\n<p>Unless the context is obvious, the variable name should adequately convey its meaning, enough to not need a comment to do the same. This also helps with maintenance and prevents the reader, or even yourself, from having to remember its meaning at any later point in the code.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T00:46:13.287", "Id": "45719", "ParentId": "45455", "Score": "10" } } ]
{ "AcceptedAnswerId": "45474", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T01:30:54.523", "Id": "45455", "Score": "19", "Tags": [ "c", "validation", "finance" ], "Title": "Credit card verification: string conversion most optimal?" }
45455
<p>I've watched quite a few videos and read a couple of articles on unit testing and I've tried my best to make this test case as good as possible. In which areas can it still be improved?</p> <p>I should probably add that SM2Scheduler is an implementation of the SM2 algorithm, which is used in flashcard software such as Anki and Mnemosyne.</p> <pre><code>import datetime import os import pathlib import sys import unittest # Resolve the relative import error path_to_this_file = pathlib.Path(__file__) path_to_srsalgorithms = path_to_this_file.parents[1] sys.path.append(str(path_to_srsalgorithms)) from sm2 import SM2Scheduler class TestSM2Scheduler(unittest.TestCase): def setUp(self): self.scheduler = SM2Scheduler() def test_init_last_review_date_is_today(self): last_review_date = self.scheduler.last_review_date today = datetime.date.today() self.assertEqual(last_review_date, today) def test_init_new_card_is_to_be_seen_today(self): days_until_next_review = self.scheduler.days_until_next_review self.assertEqual(days_until_next_review, 0) def test_init_new_card_has_not_been_reviewed_yet(self): number_of_repetitions = self.scheduler.number_of_repetitions self.assertEqual(number_of_repetitions, 0) def test_init_default_easiness_factor_is_2_point_5(self): easiness_factor = self.scheduler.easiness_factor self.assertEqual(easiness_factor, 2.5) def test_feed_last_review_date_is_updated_after_repetition(self): self.scheduler.feed(5) last_review_date = self.scheduler.last_review_date today = datetime.date.today() self.assertEqual(last_review_date, today) def test_feed_number_of_repetitions_is_set_to_0_if_card_rating_is_below_3(self): self.scheduler.feed(2) number_of_repetitions = self.scheduler.number_of_repetitions self.assertEqual(number_of_repetitions, 0) def test_feed_number_of_repetitions_is_incremented_if_card_rating_is_3_or_more(self): self.scheduler.feed(3) number_of_repetitions = self.scheduler.number_of_repetitions self.assertEqual(number_of_repetitions, 1) def test_get_date_due_for_review_returns_correct_date(self): self.scheduler.days_until_next_review = 5 next_review_date = self.scheduler.get_date_due_for_review() in_5_days = datetime.date.today() + datetime.timedelta(days=5) self.assertEqual(next_review_date, in_5_days) def test_get_new_easiness_factor_lowest_possible_easiness_factor_is_1_point_3(self): self.scheduler.easiness_factor = 1.3 new_easiness_factor = self.scheduler._get_new_easiness_factor(0) self.assertEqual(new_easiness_factor, 1.3) def test_get_new_easiness_factor_calculates_correctly(self): easiness_factor = self.scheduler._get_new_easiness_factor(0) self.assertAlmostEqual(easiness_factor, 1.7) easiness_factor = self.scheduler._get_new_easiness_factor(1) self.assertAlmostEqual(easiness_factor, 1.96) easiness_factor = self.scheduler._get_new_easiness_factor(2) self.assertAlmostEqual(easiness_factor, 2.18) easiness_factor = self.scheduler._get_new_easiness_factor(3) self.assertAlmostEqual(easiness_factor, 2.36) easiness_factor = self.scheduler._get_new_easiness_factor(4) self.assertAlmostEqual(easiness_factor, 2.5) easiness_factor = self.scheduler._get_new_easiness_factor(5) self.assertAlmostEqual(easiness_factor, 2.6) def test_get_new_days_until_next_review_card_is_to_be_seen_again_today_if_rating_is_below_3(self): days_until_next_review = self.scheduler._get_new_days_until_next_review(2) self.assertEqual(days_until_next_review, 0) def test_get_new_days_until_next_review_card_is_to_be_seen_tomorrow_if_it_has_only_been_repeated_once(self): self.scheduler.number_of_repetitions = 1 days_until_next_review = self.scheduler._get_new_days_until_next_review(3) self.assertEqual(days_until_next_review, 1) def test_get_new_days_until_next_review_card_is_to_be_seen_in_6_days_if_it_has_only_been_repeated_twice(self): self.scheduler.number_of_repetitions = 2 days_until_next_review = self.scheduler._get_new_days_until_next_review(3) self.assertEqual(days_until_next_review, 6) def test_get_new_days_until_next_review_calculates_correctly(self): self.scheduler.number_of_repetitions = 3 self.scheduler.days_until_next_review = 6 self.scheduler.easiness_factor = 2.5 days_until_next_review = self.scheduler._get_new_days_until_next_review(3) self.assertEqual(days_until_next_review, 6*2.5) if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T03:58:27.420", "Id": "79287", "Score": "1", "body": "In addition to help here - you can look into a coverage measurement tools, like `coverage.py` to spot branches you did not cover with tests." } ]
[ { "body": "<p>Drop one-time use local variables and use libraries such as <a href=\"http://github.com/hamcrest/PyHamcrest\" rel=\"nofollow\">PyHamcrest</a> to improve assertion readability.</p>\n\n<p>Compare</p>\n\n<pre><code>def test_init_last_review_date_is_today(self):\n assert_that(self.scheduler.last_review_date, is(datetime.date.today))\n</code></pre>\n\n<p>with the original</p>\n\n<pre><code>def test_init_last_review_date_is_today(self):\n self.assertEqual(self.scheduler.last_review_date, datetime.date.today())\n</code></pre>\n\n<p>BTW, does <code>assertEqual</code> follow xUnit conventions and put the <em>expected</em> value before the <em>actual</em> value? If so, your assertion error messages will be backwards: \"expected 'foo' but got 'bar'\" when testing the stub method <code>bar() { return \"foo\"; }</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T03:49:32.430", "Id": "79286", "Score": "0", "body": "For the sake of fairness I have to add that this is a matter of preference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:27:00.940", "Id": "79297", "Score": "0", "body": "@RuslanOsipov Aren't all code reviews a combination of personal and group preferences? Following best practices includes simplifying *all* code IMHO. TDD purists would say this comes naturally from creating fixtures on the fly and refactoring test code. When the tests provide the best examples of using your API, any work to improve them benefits every client. A cleaner implementation eases maintenance for the developers whereas a cleaner API improves the lives of *everyone*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T05:25:33.073", "Id": "79301", "Score": "1", "body": "I really don't get why people like the syntax pyHamcrest and similiar libraries provide. To me it feels akward relative the xUnit style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T06:46:49.733", "Id": "79307", "Score": "0", "body": "@WinstonEwert I like that Hamcrest assertions read like English prose: \"assert that the computed value is what I expect\" versus \"assert equality for the value I expect and the one computed\". Plus you can easily combine matchers: `assert_that(myDict, has_entry(\"foo\", greater_than(10)))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:48:44.843", "Id": "79393", "Score": "0", "body": "@DavidHarkness, see I don't understand why people want their tests (or any code) to look like English. For your example, `assert myDict[\"foo\"] > 10` is way easier for me to parse then the mix of Python and English that your example provides. Its probably just me, but I don't get it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:35:49.397", "Id": "79425", "Score": "0", "body": "@WinstonEwert If reading the assertions was all that mattered, I'd agree. But this is test code which will be read less often. The real difference is in the message when the assertion fails: `expected true but got false` (or worse `ReferenceError` in less forgiving languages) versus `expected a dict with \"foo\" mapped to a value greater than 10 but got a dict with no entry for \"foo\"`. Sure, you can jump to the line number and read the test, but I with the more descriptive failure message and the name of the test I can typically jump right to the bug in the class under test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:34:36.620", "Id": "79502", "Score": "0", "body": "@DavidHarkness, granted that's a perfectly valid point." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T02:22:23.117", "Id": "45460", "ParentId": "45457", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T01:58:55.113", "Id": "45457", "Score": "12", "Tags": [ "python", "unit-testing" ], "Title": "Do my unit tests follow best practices?" }
45457
<p>I am trying create an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class, but I feel like I'm fighting against Numpy instead of working with it.</p> <pre><code>import numpy as np range_inc = lambda start, end: range(start, end+1) # Find the zero crossing in the l_o_g image # Done in the most naive way possible def z_c_test(l_o_g_image): print(l_o_g_image) z_c_image = np.zeros(l_o_g_image.shape) for i in range(1, l_o_g_image.shape[0] - 1): for j in range(1, l_o_g_image.shape[1] - 1): neg_count = 0 pos_count = 0 for a in range_inc(-1, 1): for b in range_inc(-1, 1): if a != 0 and b != 0: print("a ", a, " b ", b) if l_o_g_image[i + a, j + b] &lt; 0: neg_count += 1 print("neg") elif l_o_g_image[i + a, j + b] &gt; 0: pos_count += 1 print("pos") else: print("zero") # If all the signs around the pixel are the same # and they're not all zero # then it's not a zero crossing and an edge. # Otherwise, copy it to the edge map. z_c = ((neg_count &gt; 0) and (pos_count &gt; 0)) if z_c: print("True for", i, ",", j) print("pos ", pos_count, " neg ", neg_count) z_c_image[i, j] = 1 return z_c_image </code></pre> <p>Here is the test cases it should pass:</p> <pre><code>test1 = np.array([[0,0,1], [0,0,0], [0,0,0]]) test2 = np.array([[0,0,1], [0,0,0], [0,0,-1]]) test3 = np.array([[0,0,0], [0,0,-1], [0,0,0]]) test4 = np.array([[0,0,0], [0,0,0], [0,0,0]]) true_result = np.array([[0,0,0], [0,1,0], [0,0,0]]) false_result = np.array([[0,0,0], [0,0,0], [0,0,0]]) real_result1 = z_c_test(test1) real_result2 = z_c_test(test2) real_result3 = z_c_test(test3) real_result4 = z_c_test(test4) assert(np.array_equal(real_result1, false_result)) assert(np.array_equal(real_result2, true_result)) assert(np.array_equal(real_result3, false_result)) assert(np.array_equal(real_result4, false_result)) </code></pre> <p>How do I vectorize checking a property in a matrix range? Is there a quick way of accessing all of the entries adjacent to an entry in a matrix?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:18:28.213", "Id": "79312", "Score": "0", "body": "adjacent meaning N,S,W,E or the 8 (or just 3) around the checked? currently it looks like the NSWE solution, but just to make sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:26:06.510", "Id": "79315", "Score": "0", "body": "It's supposed to be the 8." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:36:03.510", "Id": "79317", "Score": "0", "body": "@Vogel612 As shown in the unit tests and with my very awkward iteration using `a` and `b`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:01:35.337", "Id": "79321", "Score": "0", "body": "you might want to have a look at [this answer](http://stackoverflow.com/a/20200199/1803692)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:55:13.730", "Id": "79325", "Score": "0", "body": "@Vogel612 I read in that answer that accessing adjacent cells should not be optimized. Was there anything else that I missed? I think that may be relevant for half of my problem, but for the other half where I'm iterating through each cell of the matrix, I think my question still stands." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:58:28.037", "Id": "79326", "Score": "0", "body": "it was only planned to give some help on the half of the problem.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T15:12:27.173", "Id": "83202", "Score": "2", "body": "You can try to either express this operation as a convolution, which I am not sure if your check can be expressed as. Otherwise, the function [scipy.ndimage.filters.generic_filter](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.generic_filter.html) with `size` set to 3 should leave you with only writing a short function doing the check on the vector of neighborhood elements." } ]
[ { "body": "<p>One way to get the neighbor coordinates without checking for (a != 0) or (b != 0) on every iteration would be to use a generator. Something like this:</p>\n\n<pre><code>def nborz():\n l = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1),(1,0),(1,1)]\n try:\n while True:\n yield l.pop(0)\n except StopIteration:\n return None\n....\n\nfor i in range(1,l_o_g_image.shape[0]-1):\n for j in range(1,l_o_g_image.shape[1]-1):\n neg_count = 0\n pos_count = 0\n nbrgen = nborz()\n for (a,b) in nbrgen:\n print \"a \" + str(a) + \" b \" + str(b)\n if(l_o_g_image[i+a,j+b] &lt; 0):\n neg_count += 1\n print \"neg\"\n elif(l_o_g_image[i+a,j+b] &gt; 0):\n pos_count += 1\n print \"pos\"\n else:\n print \"zero\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T06:02:03.390", "Id": "83594", "Score": "0", "body": "Would that actually be faster?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:43:59.747", "Id": "83616", "Score": "0", "body": "I would think it might, 1) because it avoids a comparison on every iteration of the inner loops, and 2) because it avoids computation of the index values for the inner loops (counting -1, 0, 1 twice in a nested fashion). However, I have not actually tried it so I don't know for sure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T03:39:41.580", "Id": "47693", "ParentId": "45458", "Score": "1" } }, { "body": "<p>Here's concise method to get the coordinates of the zero-crossings that seems to work according to my tests :</p>\n\n<pre><code>def zcr(x, y):\n return x[numpy.diff(numpy.sign(y)) != 0]\n</code></pre>\n\n<p>Some simple test case :</p>\n\n<pre><code>&gt;&gt;&gt; zcr(numpy.array([0, 1, 2, 3, 4, 5, 6, 7]), [1, 2, 3, -1, -2, 3, 4, -4])\narray([2, 4, 6])\n</code></pre>\n\n<p>This is 2d only, but I believe it is easy to adapt to more dimensions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-23T08:35:01.540", "Id": "67662", "ParentId": "45458", "Score": "7" } } ]
{ "AcceptedAnswerId": "67662", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-27T02:00:06.057", "Id": "45458", "Score": "19", "Tags": [ "python", "matrix", "numpy" ], "Title": "Finding a zero crossing in a matrix" }
45458
<p>I had posted this here and was asked to move it to code review since my code works and am looking for the best possible solution : <a href="https://stackoverflow.com/questions/21998312/gae-datastore-join-group-by/21998313#21998313">original post</a></p> <p><strong>NOTE:</strong> I have seen the JOIN in GAE related posts but GROUP BY in my requirements made me make a new post and I have made a solution of my own which I wanted to check how good is it.</p> <hr> <p><strong>Datastore Entities properties and types (database)</strong></p> <ol> <li><p><strong>Entity</strong> : PartyEntity <em>let's call this as a</em></p> <ul> <li>String partyName</li> <li>String partyId</li> <li>BlobKey image</li> </ul></li> <li><p><strong>Entity</strong> : InsertEntity <em>let's call this as b</em></p> <ul> <li>String partyIdentifier</li> <li>String name</li> <li>String constituency</li> </ul></li> </ol> <hr> <p><strong>Objective</strong></p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM a JOIN b on a.partyId = b.partyIdentifier GROUP BY b.constituency; </code></pre> <hr> <p>The solution I made is as follows. Do suggest any changes or better ideas.</p> <pre><code>// SELECT * FROM a (PartyEntity holds unique partyId) and for each partyId SELECT * FROM b private List&lt;ListDisplay&gt; initData() { DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); List&lt;ListDisplay&gt; data = new ArrayList&lt;ListDisplay&gt;(); Query query = new Query("PartyEntity"); PreparedQuery preparedQuery = datastore.prepare(query); List&lt;Entity&gt; entities = preparedQuery.asList(FetchOptions.Builder .withDefaults()); for (Entity entity : entities) { String PARTY_ID = (String) entity.getProperty("partyId"); // fetch from another Query query2 = new Query("InsertEntity"); Filter filterByPartyId = new Query.FilterPredicate( "partyIdentifier", FilterOperator.EQUAL, PARTY_ID); query2.setFilter(filterByPartyId); PreparedQuery preparedQuery2 = datastore.prepare(query2); List&lt;Entity&gt; entities2 = preparedQuery2.asList(FetchOptions.Builder .withDefaults()); for (Entity entity2 : entities2) { ListDisplay display = new ListDisplay(); display.setPartyId((String) entity.getProperty("partyId")); display.setPartyName((String) entity.getProperty("partyName")); display.setImage((BlobKey) entity.getProperty("image")); display.setName((String) entity2.getProperty("name")); display.setConstituency((String) entity2 .getProperty("constituency")); data.add(display); } // end loop entity2 } // end loop entity return data; } </code></pre> <hr> <pre><code>// GROUP BY constituency clause part public HashMap&lt;String, List&lt;ListDisplay&gt;&gt; getData() { HashMap&lt;String, List&lt;ListDisplay&gt;&gt; data = new HashMap&lt;&gt;(); List&lt;ListDisplay&gt; list = initData(); for (ListDisplay d : list) { // if null add if (data.get(d.getConstituency()) == null) { List&lt;ListDisplay&gt; internal = new ArrayList&lt;&gt;(); internal.add(d); data.put(d.getConstituency(), internal); } // else modify else { List&lt;ListDisplay&gt; hashlist = data.get(d.getConstituency()); hashlist.add(d); data.remove(d.getConstituency()); data.put(d.getConstituency(), hashlist); } } return data; } </code></pre>
[]
[ { "body": "<p>Just a few generic notes, I'm not familiar with Google App Engine:</p>\n\n<ol>\n<li><p><code>HashMap&lt;...&gt;</code> reference types could be <code>Map&lt;...&gt;</code>:</p>\n\n<pre><code>public Map&lt;String, List&lt;ListDisplay&gt;&gt; getData() {\n</code></pre>\n\n<p>See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p>I'd rename this variable to <code>result</code> to express its purpose: </p>\n\n<blockquote>\n<pre><code>List&lt;ListDisplay&gt; data = new ArrayList&lt;ListDisplay&gt;();\n</code></pre>\n</blockquote></li>\n<li><p><code>remove</code> is unnecesary here, put will override it:</p>\n\n<blockquote>\n<pre><code>data.remove(d.getConstituency());\ndata.put(d.getConstituency(), hashlist);\n</code></pre>\n</blockquote></li>\n<li><p>Consider replacing the following with a <code>Multimap</code>:</p>\n\n<blockquote>\n<pre><code>// if null add\nif (data.get(d.getConstituency()) == null) {\n List&lt;ListDisplay&gt; internal = new ArrayList&lt;&gt;();\n internal.add(d);\n data.put(d.getConstituency(), internal);\n}\n// else modify\nelse {\n List&lt;ListDisplay&gt; hashlist = data.get(d.getConstituency());\n hashlist.add(d);\n data.remove(d.getConstituency());\n data.put(d.getConstituency(), hashlist);\n}\n</code></pre>\n</blockquote>\n\n<p>The following uses <a href=\"http://guava-libraries.googlecode.com/\" rel=\"nofollow noreferrer\">Google Guava</a>'s <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow noreferrer\"><code>Multimap</code></a> and much simpler:</p>\n\n<pre><code>final ArrayListMultimap&lt;String, ListDisplay&gt; data = ArrayListMultimap.create();\n\nfor (ListDisplay d : list) {\n data.put(d.getConstituency(), d);\n}\n</code></pre>\n\n<p>If you really need <code>Map</code> return type you can convert it back to <code>Map</code> with <code>data.asMap()</code> which returns a <code>Map&lt;String, Collection&lt;ListDisplay&gt;&gt;</code> but you cast it down safely to <code>Map&lt;String, List&lt;ListDisplay&gt;&gt;</code>. (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ArrayListMultimap.html#asMap%28%29\" rel=\"nofollow noreferrer\"><code>ArrayListMultimap</code> javadoc supports this</a> as well as <a href=\"https://stackoverflow.com/q/11204143/843804\">these Stack Overflow posts</a>.)</p></li>\n<li><p>Variable names in Java usually <code>camelCase</code>.</p>\n\n<blockquote>\n<pre><code>String PARTY_ID = (String) entity.getProperty(\"partyId\");\n</code></pre>\n</blockquote></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs and editors could show blocks.</p>\n\n<pre><code> } // end loop entity2\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T12:22:04.263", "Id": "46264", "ParentId": "45464", "Score": "3" } } ]
{ "AcceptedAnswerId": "46264", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T05:31:13.797", "Id": "45464", "Score": "6", "Tags": [ "java", "google-app-engine" ], "Title": "GAE datastore JOIN + GROUP BY" }
45464
<p>This is the stored procedure I'm using to list some places in my website. How can I optimize it to perform well? Which functions in query is taking much time for its execution?</p> <pre><code>ALTER PROCEDURE [dbo].[PlaceListSelect] @cateID int, @searchTxt varchar(50), @userID int, @RowIndex int, @MaxRows int, @Location varchar(50), @IsMuslimFaceSpecial int, @IsUserHadNotBeenTo int, @IsUserHadBeenTo int, @IsUserFriendsHaveBeenTo int, @IsMyPlacesonly int AS BEGIN DECLARE @EndRow AS int; SET @EndRow = @RowIndex + @MaxRows - 1; WITH tbl AS (SELECT P.*, (SELECT SUM(R.Rating) / COUNT(R.Rating) FROM PlaceReview AS R WHERE R.PlaceId = P.PlaceId AND R.Rating != 0) AS Rating, pc.PlaceCategory, ISNULL(PP.DefaultLandingTab, 0) AS DefaultLandingTab, ISNULL(Cty.City, '') AS City, ISNULL(Ctry.Country, '') AS Country, (SELECT COUNT(likeid) FROM Likes WHERE KeyID = P.PlaceId AND liketypeid = 48) AS totalLikes, ROW_NUMBER() OVER (ORDER BY P.PlaceId ASC) AS RowRank, '' AS mapaddress FROM Places AS P INNER JOIN dbo.PlaceCategory AS pc ON p.PlaceCategoryId = pc.PlaceCategoryId LEFT OUTER JOIN PlacePermissions AS PP ON P.PlaceId = PP.PlaceId LEFT OUTER JOIN dbo.Cities AS Cty ON P.CityId = Cty.CityId LEFT OUTER JOIN dbo.Countries Ctry ON P.CountryID = Ctry.CountryID WHERE P.status = 1 AND pc.status = 1 AND P.IsVerified = 1 AND (PlaceName LIKE '%' + @searchTxt + '%' OR PlaceCategory LIKE '%' + @searchTxt + '%' OR P.[Description] LIKE '%' + @searchTxt + '%' ) AND ([Address] LIKE '%' + @Location + '%' OR City LIKE '%' + @Location + '%') AND (@cateID = 0 OR PC.PlaceCategoryId = @cateID) AND [dbo].[PrivacyCheck](@Userid, P.PlaceId, 33) = 1 AND dbo.CheckPlacePermission(@userID, P.PlaceId) = 1 AND (@IsMuslimFaceSpecial = 0 OR P.IsSpecial = 1) AND (@IsMyPlacesonly = 0 OR P.UserId = @userID) AND (@IsUserHadBeenTo = 0 OR P.PlaceId IN (SELECT PlaceId FROM PlaceVisited WHERE UserID = @userID) ) AND (@IsUserFriendsHaveBeenTo = 0 OR P.PlaceId IN (SELECT PlaceId FROM PlaceVisited AS pv INNER JOIN dbo.GetFriends(@userID) AS uf ON pv.UserID = uf.UserID) ) AND (@IsUserHadNotBeenTo = 0 OR P.PlaceId NOT IN (SELECT PlaceId FROM PlaceVisited WHERE UserID = @userID) )) SELECT * FROM tbl WHERE RowRank BETWEEN @RowIndex AND @EndRow ORDER BY dbo.GetSearchPlaceCount(@userID, PlaceId) DESC, totalLikes DESC; END </code></pre> <p>Is there any performance improvement if I change <code>PC.PlaceCategoryId = @cateID OR @cateID = 0</code> to <code>@cateID = 0 OR PC.PlaceCategoryId = @cateID</code></p> <p>Execution plan can be downloaded from my <a href="http://1drv.ms/1dzLB7P" rel="nofollow">OneDrive Account</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:09:10.747", "Id": "79327", "Score": "0", "body": "Might you get better answers (about performance) if you added the query plan to your questions, and add the DDL which shows what the database indexes are?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T04:20:48.297", "Id": "79517", "Score": "2", "body": "For a real answer, provide DDL, sample data (INSERT statements), sample queries and actual execution plans (not estimated). On a quick glance, LIKE with a starting % is nonsargable (can't use indexes) for obvious reasons - do you really need that leading %? Try putting WHERE clause conditions relating solely to one JOIN table into the JOIN clauses (i.e. P.IsVerified = 1). Don't use scalar functions in your JOIN or WHERE clauses, performance is awful (PrivacyCheck, CheckPlacePermission, etc.) even before we consider sargability or the lack thereof. And use parameters, not concatenation :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:08:50.300", "Id": "79518", "Score": "0", "body": "@Anti-weakpasswords I didn't understand this `Try putting WHERE clause conditions relating solely to one JOIN table into the JOIN clauses (i.e. P.IsVerified = 1)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:21:35.087", "Id": "79520", "Score": "0", "body": "@Anti-weakpasswords Actula execution pla attached" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:38:04.793", "Id": "79523", "Score": "2", "body": "@SubinJacob: Instead of SELECT Col1 FROM TblA INNER JOIN TblB ON TblA.Col1 = TblB.Col1 WHERE TblB.Col2 = 1, try SELECT Col1 FROM TblA INNER JOIN TblB ON TblA.Col1 = TblB.Col1 AND TblB.Col2 = 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:06:57.973", "Id": "79525", "Score": "0", "body": "@Anti-weakpasswords Thanks. Any suggestions after seeing the execution plan?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:31:46.390", "Id": "79529", "Score": "0", "body": "@Anti-weakpasswords if I move `scalar functions` to `JOIN clauses` will it improve performance? and sargable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:29:39.847", "Id": "79628", "Score": "0", "body": "Why do you use a CTE to Select all but some records, when you should just do that in the main query. the structure (at first glance) looks really bad to start with." } ]
[ { "body": "<p>It is hard to give an accurate answer without seeing all the code (there are a few functions like GetSearchPlaceCount, and GetFriends, [PrivacyCheck], CheckPlacePermission ...), and without knowing what the indexes are.</p>\n\n<p>Things that i have noticed:</p>\n\n<ol>\n<li><p>In the first block, the average rating calculation and the number of likes calculation can be avoided altogether if you make a couple of computed columnns in the Places table (one for average rating and one for number of likes).</p></li>\n<li><p>This join seems redundant to me (I think can just remove it):</p>\n\n<pre><code>LEFT OUTER JOIN PlacePermissions AS PP\n ON P.PlaceId = PP.PlaceId\n</code></pre></li>\n<li><p>I notice in the like's you don't check if @searchTxt and @Location are empty, if those variables can indeed be empty, it would be good if you could spare the engine having to scan for like '%%' </p></li>\n<li><p>Everywhere I look in the Stored proc, I see a relation between (UserId and a PlaceId), and everytime this relation is handled with a different query:</p>\n\n<ul>\n<li>(1x) ... AND [dbo].[PrivacyCheck](@Userid, P.PlaceId, 33) = 1 ... </li>\n<li>(1x) ... LEFT OUTER JOIN PlacePermissions AS PP ON P.PlaceId = PP.PlaceId ...</li>\n<li>(1x) ... AND (@IsMyPlacesonly = 0 OR P.UserId = @userID) ... </li>\n<li>(1x) ... AND dbo.CheckPlacePermission(@userID, P.PlaceId) ... </li>\n<li>(1x) ... dbo.GetSearchPlaceCount(@userID, PlaceId) ... </li>\n<li>(3x) ... P.PlaceId IN (SELECT PlaceId FROM PlaceVisited WHERE UserID = @userID ... </li>\n</ul></li>\n</ol>\n\n<p>I have the feeling that you can create a temporary table (or a view) 'AvailablePlaces' with only the places which passes all the filters (including permissions and privacy check, including all the conditional statemens such as @IsUserHadNotBeenTo, @IsUserHadBeenTo, status=1, isVerified=1, PC.PlaceCategoryId = @cateID, etc), and then use this view just once instead of 6 times with conditional left joins </p>\n\n<p>As an added bonus by grouping all the places into one object, you can make sure in one place that all the filters are applied consistently (privacy, permissions, isVerified, status etc: in the clauses in the bottom (PlaceVisited) that is taken for granted somehow). All these filters would also help the db engine to use the existing indexes better.</p>\n\n<p>then you could replace</p>\n\n<pre><code> FROM Places AS P\n</code></pre>\n\n<p>with</p>\n\n<pre><code> FROM AvailablePlaces AS P \n</code></pre>\n\n<p>And you would then be able to remove most of those Where clauses, the likes would remain though</p>\n\n<p>Then you should try to see if you can replace the functions (specially dbo.GetSearchPlaceCount) with a query based on availablePlaces</p>\n\n<p>And finally, as a general note, you need of course to look at your indexes to maximize the performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:39:22.970", "Id": "79555", "Score": "0", "body": "By adding view can I improve performance? It just improve the code readability I suppose? Will SqlServer Cache results if views were used?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:47:56.297", "Id": "79558", "Score": "0", "body": "Also can i use computed columns for like count? likes are defined in another table and msdn documentation says `A computed column is computed from an expression that can use other columns in the same table.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:54:17.590", "Id": "79559", "Score": "0", "body": "Also this quote confusing me `Views create the appearance of a table, but the DBMS must still translate queries against the view into queries against the underlying source tables. If the view is defined by a complex, multi-table query then simple queries on the views may take considerable time.` See this link http://www.c-sharpcorner.com/Blogs/10575/advantages-and-disadvantages-of-views-in-sql-server.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:01:22.810", "Id": "79560", "Score": "0", "body": "Mainly readability, but by adding all the checks (verified, status, permissions, etc) I think the engine can make a better query and possible decrease the resultset, that would improve performance. It will not cache the view. You can try to make a materialized view (see http://stackoverflow.com/questions/3986366/how-to-create-materialized-views-in-sql-server) if you want it cached" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:10:35.097", "Id": "79561", "Score": "0", "body": "You can use a User Defined function to get values from another table, or even better an indexed view, see here: http://stackoverflow.com/questions/13488822/create-computed-column-using-data-from-another-table" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:14:56.890", "Id": "45593", "ParentId": "45466", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T05:48:56.737", "Id": "45466", "Score": "0", "Tags": [ "performance", "sql", "sql-server", "stored-procedure" ], "Title": "A search for reviews of places" }
45466
<p>Recently I worked on one of the Codility Training - Genomic Range Query (please refer to one of the evaluation report for the detail of <a href="https://codility.com/demo/results/demoYC9TD5-324/" rel="nofollow">this training</a>).</p> <p>The proper approach for this question is using prefix sum. Here is the implementation:</p> <pre><code>struct Results solution(char *S, int P[], int Q[], int M) { struct Results result; int* ans = (int*)calloc(M, sizeof(int)); int pre_sum_arr[strlen(S)][4]; int i, j; memset(pre_sum_arr, 0, sizeof(pre_sum_arr)); for(i = 0 ; i &lt; strlen(S) ; i++){ if(S[i] == 'A') pre_sum_arr[i][0] = 1; else if(S[i] == 'C') pre_sum_arr[i][1] = 1; else if(S[i] == 'G') pre_sum_arr[i][2] = 1; else pre_sum_arr[i][3] = 1; } for(i = 1; i &lt; strlen(S) ; i++){ for(j = 0 ; j &lt; 4 ; j++){ pre_sum_arr[i][j] += pre_sum_arr[i - 1][j]; } } for(i = 0 ; i &lt; M ; i++){ for(j = 0 ; j &lt; 4 ; j++){ if((P[i] == 0 &amp;&amp; pre_sum_arr[Q[i]][j]) || \ (pre_sum_arr[Q[i]][j] - pre_sum_arr[P[i] - 1][j] &gt; 0)){ ans[i] = j + 1; break; } } } result.A = ans; result.M = M; return result; } </code></pre> <p>However, the evaluation report said that it exceeds the time limit for large-scale testing case (the report link is above).</p> <p>The detected time complexity is O(M * N) instead of O(M + N). But in my view, it should be O(M + N) since I ran loop for N and M independently (N for calculating the prefix sum and M for getting the answer).</p> <p>I also used an alternate solution for this question. I also think its complexity is O(M + N), but I got the same result. Here is my code:</p> <pre><code>struct _pre_min_idx{ int pre_1_idx; int pre_2_idx; int pre_3_idx; }; int mapping(char c){ if(c == 'A') return 1; if(c == 'C') return 2; if(c == 'G') return 3; if(c == 'T') return 4; return -1; } typedef struct _pre_min_idx pre_min_idx; struct Results solution(char *S, int P[], int Q[], int M) { struct Results result; // A = 1, C = 2, G = 3, T = 4 pre_min_idx pre_min_idx_arr[strlen(S)]; int* min_nuc_arr = (int*)calloc(M, sizeof(int)); int i; int pre_1_idx = -1, pre_2_idx = -1, pre_3_idx = -1; memset(pre_min_idx_arr, 0, sizeof(pre_min_idx_arr)); for(i = 0 ; i &lt; strlen(S) ; i++){ if(S[i] == 'T'){ pre_min_idx_arr[i].pre_1_idx = pre_1_idx; pre_min_idx_arr[i].pre_2_idx = pre_2_idx; pre_min_idx_arr[i].pre_3_idx = pre_3_idx; } else if(S[i] == 'G'){ pre_min_idx_arr[i].pre_1_idx = pre_1_idx; pre_min_idx_arr[i].pre_2_idx = pre_2_idx; pre_min_idx_arr[i].pre_3_idx = -1; pre_3_idx = i; } else if(S[i] == 'C'){ pre_min_idx_arr[i].pre_1_idx = pre_1_idx; pre_min_idx_arr[i].pre_2_idx = -1; pre_min_idx_arr[i].pre_3_idx = -1; pre_2_idx = i; } else{ pre_min_idx_arr[i].pre_1_idx = -1; pre_min_idx_arr[i].pre_2_idx = -1; pre_min_idx_arr[i].pre_3_idx = -1; pre_1_idx = i; } } for(i = 0 ; i &lt; M ; i++){ pre_min_idx pmi_Q = pre_min_idx_arr[Q[i]]; if(pmi_Q.pre_1_idx &gt;= P[i]) min_nuc_arr[i] = 1; else if(pmi_Q.pre_2_idx &gt;= P[i]) min_nuc_arr[i] = 2; else if(pmi_Q.pre_3_idx &gt;= P[i]) min_nuc_arr[i] = 3; else{ min_nuc_arr[i] = mapping(S[Q[i]]); } } result.A = min_nuc_arr; result.M = M; return result; } </code></pre> <p>The evaluation report is <a href="https://codility.com/demo/results/demoKYT9PV-FVP/" rel="nofollow">here</a>.</p> <p>Could anyone help me to figure out what the problem is for my solution? I get stuck for long time. Any performance improvement trick or advice will be appreciated.</p>
[]
[ { "body": "<p><code>strlen</code> takes a linear time in the length of the string. Thus, <code>for(i = 0 ; i &lt; strlen(S) ; i++)</code> will call it <code>n</code> times and the result will be quadratic.</p>\n\n<p>Changing this and a few other details (moving stuff to the smallest possible scope) and you get this :</p>\n\n<pre><code>struct Results solution(char *S, int P[], int Q[], int M) {\n int len = strlen(S);\n int pre_sum_arr[len][4];\n\n memset(pre_sum_arr, 0, sizeof(pre_sum_arr));\n for(int i = 0 ; i &lt; len ; i++){\n if(S[i] == 'A') pre_sum_arr[i][0] = 1;\n else if(S[i] == 'C') pre_sum_arr[i][1] = 1;\n else if(S[i] == 'G') pre_sum_arr[i][2] = 1;\n else pre_sum_arr[i][3] = 1;\n }\n\n for(int i = 1; i &lt; len; i++){\n for(j = 0 ; j &lt; 4 ; j++){\n pre_sum_arr[i][j] += pre_sum_arr[i - 1][j];\n }\n }\n\n int* ans = (int*)calloc(M, sizeof(int));\n for(int i = 0 ; i &lt; M ; i++){\n for(int j = 0 ; j &lt; 4 ; j++){\n if((P[i] == 0 &amp;&amp; pre_sum_arr[Q[i]][j]) || \\\n (pre_sum_arr[Q[i]][j] - pre_sum_arr[P[i] - 1][j] &gt; 0)){\n ans[i] = j + 1;\n break;\n }\n }\n }\n\n struct Results result;\n result.A = ans;\n result.M = M;\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:02:38.063", "Id": "79487", "Score": "0", "body": "Josay, thank you for pointing out where I missed, it helps a lot. Such a silly mistake I made :/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-03T11:32:27.500", "Id": "154594", "Score": "0", "body": "Might be dodgy putting int pre_sum_arr[len][4]; on the stack, if len is huge." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T09:46:21.083", "Id": "45473", "ParentId": "45467", "Score": "5" } }, { "body": "<p>Just a few notes not mentioned in other answers:</p>\n\n<ul>\n<li><p>You can <code>typedef</code> your <code>struct</code> right away.</p>\n\n<pre><code>typedef struct\n{\n int pre_1_idx;\n int pre_2_idx;\n int pre_3_idx;\n} PreMinIdx;\n</code></pre>\n\n<p>Then initialize it with a more unique name.</p>\n\n<pre><code>PreMinIdx UniqueName;\n</code></pre></li>\n<li><p>Use <code>else if</code>s in your <code>mapping()</code> method. And since you aren't modifying the function parameter, declare it as <code>const</code> (as you should do with all function parameters you don't modify within the function).</p>\n\n<pre><code>int mapping(const char c)\n{\n if (c == 'A') return 1;\n else if (c == 'C') return 2;\n else if (c == 'G') return 3;\n else if (c == 'T') return 4;\n else return -1;\n}\n</code></pre></li>\n<li><p>Some of your variable name do not follow the standard naming conventions of beginning with a lowercase letter, and they aren't very descriptive.</p>\n\n<blockquote>\n<pre><code>char *S, int P[], int Q[], int M\n</code></pre>\n</blockquote>\n\n<p>Even short names such as <code>str</code> would be more descriptive.</p></li>\n<li><p>Declare <code>i</code> inside of your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for(int i = 0; i &lt; strlen(S); i++)\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T04:39:40.177", "Id": "45726", "ParentId": "45467", "Score": "5" } } ]
{ "AcceptedAnswerId": "45473", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T06:55:47.577", "Id": "45467", "Score": "6", "Tags": [ "c", "complexity", "programming-challenge", "bioinformatics" ], "Title": "Genomic Range Query" }
45467
<p>I start with an array containing some 'ids' and some 'values'.</p> <p>What I need is to organize the 'ids' in a new array to be, if possible, apart when the 'values' they are associated with are alike.</p> <p>So I came up with a solution. If there is too much of a value type, the spreading is uneven. So if one of you has a different, better, solution, I'm all ears!</p> <p>Here is what I came up with:</p> <pre><code>function discontinus_sort($to_sort, $order_by, $id){ while (count(array_count_values($to_sort)) &gt;1) { $order[] = [$id =&gt; key($to_sort) , $order_by =&gt; $to_sort[key($to_sort)]]; $holder = $to_sort[key($to_sort)]; unset($to_sort[key($to_sort)]); reset($to_sort); if (isset($to_sort[key($to_sort)])) { while( $holder == $to_sort[key($to_sort)] ) { next($to_sort); } } } while ($to_sort) { $order[] = [$id =&gt; key($to_sort) , $order_by =&gt; $to_sort[key($to_sort)]]; unset($to_sort[key($to_sort)]); } return $order; } </code></pre> <p>And for an example:</p> <pre><code>$test[0=&gt;'red',1=&gt;'red',2=&gt;'red',3=&gt;'crimson',4=&gt;'aqua',5=&gt;'chartreuse',6=&gt;'green',7=&gt;'chartreuse',8=&gt;'red',9=&gt;'crimson',10=&gt;'crimson',11=&gt;'aqua',12=&gt;'aqua',13=&gt;'green',14=&gt;'crimson']; $test_order = discontinus_sort($test, 'couleur', 'id'); foreach ($test_order as $key) { echo '&lt;div style="height: 100px; width: 100px; margin:5px; float: left; background-color:'.$key['couleur'].'; " &gt;&lt;/div&gt;'; } </code></pre> <p>If you change too many values, let's say by red, you'll end up with a big stack of red at the end.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T08:18:44.263", "Id": "79313", "Score": "2", "body": "I think what you're trying to say is, you want the output to be such that no two consecutive entries are identical?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:12:51.067", "Id": "79369", "Score": "2", "body": "can you give us a sample output (result) of what your algorithm suppose to give and what is it giving now" } ]
[ { "body": "<p>Maybe this answer is a bit late, but hopefully someone can benefit from it!</p>\n\n<p>First off, very interesting concept... It was a challenge to try and figure this one out! I have come up with another implementation, whether it's truly better or not is for the author to decide. Here it is:</p>\n\n<pre><code>&lt;?php\n\nfunction discontinuous_sort($input) {\n $new = array();\n\n while ($input) {\n $curr = current($input);\n if (end($new) == $curr) {\n next($input);\n continue;\n } else {\n $new[] = $curr;\n unset($input[key($input)]);\n reset($input);\n }\n }\n return array_filter($new);\n}\n\n$test = array('red', 'red', 'red', 'crimson', 'aqua', 'chartreuse', 'green', 'chartreuse', 'red', 'crimson', 'crimson', 'aqua', 'aqua', 'green', 'crimson');\n\n\n$test_order = discontinuous_sort($test);\n\nforeach ($test_order as $key) { \n echo '&lt;div style=\"height: 100px; width: 100px; margin:5px; float: left; background-color:'.$key.'; \" &gt;&lt;/div&gt;';\n}\n</code></pre>\n\n<p>I'll see what I can do to explain things.</p>\n\n<p>In all honesty, looking at your algorithm, I knew things could be changed. Sorry for making it so drastic!</p>\n\n<ul>\n<li>The first thing I knew I could do was take away the manual indexing on the input array. It does us no good to do this. This also means I can take away the last two parameters in your function. We shouldn't need to name them or create a multidimensional array.</li>\n<li>You were onto something with the <code>while</code> loop, it just needed something else!</li>\n<li>I've taken away the aspect of a \"holder\". At first I thought I'd need one too, but after more work it became apparent I didn't. I am just utilizing the array positioning functions in a different manner.</li>\n<li><p>My snippet basically works like this: </p>\n\n<p><em>While the original array exists, begin a check. Check if the last element of the new array is equal to the current element in the original. If it is, move onto the next element so we don't get two identical elements next to each other. If the last element isn't equal to the current, append it to the new array and delete that element from the original. Then go back to the beginning! Lastly, erase any empty values (empties are made when we have lots of reds or whatever).</em></p></li>\n</ul>\n\n<p>And that's it! I'm sure mine could be simplified, but we're not Code Golf here! ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-29T21:09:30.590", "Id": "64189", "ParentId": "45471", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T07:59:25.330", "Id": "45471", "Score": "8", "Tags": [ "php", "array", "sorting" ], "Title": "Sorting a PHP array in a discontinuous manner" }
45471
<p>I'm currently having this code &amp; looking for a simpler and shorter way of showing, hiding &amp; disabling my elements...</p> <pre><code>$("#chReportData").click(function(){ if($(this)[0].checked){ $("#reportDataOptions").show(); } else { $("#ReportDataStatusOptions").hide(); $("#reportDataOptions").hide(); $('#chkReportPermission').attr('checked', false); $('#chReportDataStatus').attr('checked', false); $('#chReportDataCummulative').attr('checked', false); $('.allowedUpload').attr('checked', false); $('.allowedDelete').attr('checked', false); } }); $("#chReportDataStatus").click(function() { if ($(this)[0].checked) { $("#ReportDataStatusOptions").show(); } else if ($('#chReportDataCummulative').is('checked')) { $("#ReportDataStatusOptions").hide(); $('.allowedUpload').attr('checked', false); $('.allowedDelete').attr('checked', false); } else { $("#ReportDataStatusOptions").hide(); $('.allowedUpload').attr('checked', false); $('.allowedDelete').attr('checked', false); } }); </code></pre> <p>It works fine, I'm just looking for a simpler way... If you know of a shorter &amp; simpler way, please share...</p> <p><strong>Added HTML...</strong></p> <pre><code>&lt;label class="typ3"&gt;Report Data:&lt;/label&gt;&lt;asp:CheckBox ID="chReportData" runat="server" CssClass="floatL shad1 trans1" ClientIDMode="Static"/&gt;&lt;br class="floatClear" /&gt; &lt;span id="reportDataOptions" style="display: none;"&gt; &lt;label class="typ3"&gt;Report Management:&lt;/label&gt;&lt;asp:CheckBox ID="chkReportPermission" runat="server" CssClass="floatL shad1 trans1" ClientIDMode="Static"/&gt;&lt;br class="floatClear" /&gt; &lt;asp:RadioButton ID="chReportDataStatus" runat="server" ClientIDMode="Static" CssClass="floatL shad1 trans1" GroupName="reportData" Text="Report Type: Status" TextAlign="Left"/&gt;&lt;br class="floatClear" /&gt; &lt;asp:RadioButton ID="chReportDataCummulative" runat="server" ClientIDMode="Static" CssClass="floatL shad1 trans1" GroupName="reportData" Text="Report Type: Cummulative" TextAlign="Left"/&gt;&lt;br class="floatClear" /&gt; &lt;/span&gt; &lt;span id="ReportDataStatusOptions" style="display: none;"&gt; &lt;label class="typ3"&gt;Upload Files&lt;/label&gt; &lt;asp:CheckBox ID="chkAllowedUpload" runat="server" CssClass="floatL shad1 trans1" class="allowUpload"/&gt;&lt;br class="floatClear"/&gt; &lt;label class="typ3"&gt;Delete Files&lt;/label&gt; &lt;asp:CheckBox ID="chkAllowedDelete" runat="server" CssClass="floatL shad1 trans1" class ="allowDelete"/&gt;&lt;br class="floatClear"/&gt; &lt;/span&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:20:49.853", "Id": "79338", "Score": "0", "body": "can you share you html?" } ]
[ { "body": "<p><strong>Edit: now that you have shared your html I could make a better response ... <a href=\"http://jsfiddle.net/EjBW7/2/\" rel=\"nofollow\">http://jsfiddle.net/EjBW7/2/</a></strong></p>\n\n<p>There is a lot of repeated code, you could write some functions to avoid repeating the code, the branches in the second block seem redundant. You could use jquery's ability to target multiple elements in one selector.</p>\n\n<pre><code>setCheckboxValue = function (selector, enable)\n{\n return $(selector).attr('checked', enable);\n}\n\n$(\"#chReportData\").click(function(){\n\n if($(\"#chReportData\").is(':checked') ){\n console.log('#chReportData show');\n $(\"#reportDataOptions\").show();\n } else {\n console.log('#chReportData hide');\n\n $(\"#ReportDataStatusOptions, #reportDataOptions\").hide();\n setCheckboxValue('#chkReportPermission, #chReportDataStatus, #chReportDataCummulative, .allowedUpload, .allowedDelete', false);\n }\n});\n\n$(\"#chReportDataStatus,#chReportDataCummulative\").click(function() {\n if ($(\"#chReportDataStatus\").is(':checked') ) {\n console.log('#ReportDataStatusOptions show');\n $(\"#ReportDataStatusOptions\").show();\n } else { \n console.log('#ReportDataStatusOptions hide');\n $(\"#ReportDataStatusOptions\").hide();\n setCheckboxValue('.allowedUpload, .allowedDelete', false);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:17:37.943", "Id": "79337", "Score": "0", "body": "http://jsfiddle.net/EjBW7/ doesn't work!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:33:39.623", "Id": "79341", "Score": "0", "body": "oops sorry had not saved it!, http://jsfiddle.net/EjBW7/1/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:25:52.043", "Id": "79527", "Score": "0", "body": "Great...! This works perfectly... I'm impressed...!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:05:22.657", "Id": "45481", "ParentId": "45475", "Score": "2" } }, { "body": "<p>Here is how I did mine (Using Pratik Joshi's methods):</p>\n\n<pre><code> $(\"#chReportData\").click(function(){\n if($(this)[0].checked){\n $(\"#reportDataOptions\").show();\n } else {\n $(\"#ReportDataStatusOptions , #reportDataOptions\").hide();\n $('#chkReportPermission , #chReportDataStatus , #chReportDataCummulative , .allowedUpload , .allowedDelete').attr('checked', false);\n }\n });\n\n $(\"#chReportDataStatus\").click(function() {\n $(\"#ReportDataStatusOptions\").show();\n });\n\n $(\"#chReportDataCummulative\").click(function() {\n $(\"#ReportDataStatusOptions\").hide();\n $('.allowedUpload , .allowedDelete').attr('checked', false);\n });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:29:23.540", "Id": "45580", "ParentId": "45475", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:12:37.690", "Id": "45475", "Score": "4", "Tags": [ "javascript", "jquery", "html" ], "Title": "Simpler way of showing, hiding & disabling elements" }
45475
<p>Since my project is getting bigger every day and I am just a starter in the wonderful world of makefiles, I need some help improving mine because, although it works (almost) as I wish, it really started looking like a mess. So it would be nice if someone could help me with it (and of course, advice is welcome).</p> <p>Basically this is the structure of my C++ project:</p> <pre class="lang-none prettyprint-override"><code>myProject | doc/ (nothing to do here) | obj/ (where all *.o go) | src/ (where I have all my *.h and *.cpp) | tests/ (where all my tests are) </code></pre> <p>I have to say, in my Makefile I have some <em>normal</em> stuff, but also some <em>really ugly</em> stuff, so I hope you do not panic:</p> <pre class="lang-bsh prettyprint-override"><code>define \n endef EXECUTABLE = main # compiler CC = g++ CFLAGS = -g -std=gnu++0x -Wall -Wno-reorder -I. $(SYSTEMC_INCLUDE_DIRS) LFLAGS = $(SYSTEMC_LIBRARY_DIRS) FINAL = -o $(EXECUTABLE) LIBS = -lsystemc-ams -lsystemc | c++filt # directory names SRCDIR = src OBJDIR = obj TSTDIR = tests SOURCES := $(wildcard $(SRCDIR)/*.cpp) INCLUDES := $(wildcard $(SRCDIR)/*.h) TEST_SRC := $(wildcard $(TSTDIR)/*.cpp) OBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o) TESTS := $(TEST_SRC:$(TSTDIR)/%.cpp=$(TSTDIR)/%.o) rm = rm -rf all: $(EXECUTABLE) check: testbenches run_test_script debug: CC += -O0 -fno-inline debug: all main: createdir maincpp $(OBJECTS) $(CC) $(CFLAGS) $(LFLAGS) $(FINAL) $(OBJDIR)/$@.o $(OBJECTS) $(LIBS) TBS = $(basename $(TEST_SRC)) testbenches: createdir $(OBJECTS) $(TESTS) $(foreach tb, $(TBS), $(CC) $(CFLAGS) $(LFLAGS) -o $(tb).tst $(tb).o $(OBJECTS) $(LIBS) ${\n}) run_test_script: @cd $(TSTDIR); \ ./run_tests.sh createdir: @mkdir -p obj maincpp: $(CC) $(CFLAGS) -c -o $(OBJDIR)/main.o main.cpp $(TESTS): $(TSTDIR)/%.o : $(TSTDIR)/%.cpp $(CC) $(CFLAGS) -c -o $@ $&lt; $(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.cpp $(CC) $(CFLAGS) -c -o $@ $&lt; .PHONY: clean clean: $(rm) $(OBJDIR) $(rm) $(TSTDIR)/*.o $(rm) $(TSTDIR)/*.out $(rm) $(subst .cpp,.tst, $(TEST_SRC)) $(rm) $(EXECUTABLE) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:50:44.517", "Id": "79332", "Score": "2", "body": "If it is not for training purposes I would advice you to use a Makefile generator like autotools, cmake, ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:55:05.957", "Id": "79333", "Score": "0", "body": "Well, when I started this project I chose to do Makefiles manually to learn, so in some way it is. Anyway, I'll take a look at Autotools, because at this point, I certainly need a more organized and less dependent (on me) build system." } ]
[ { "body": "<p>You have many more <code>.PHONY</code> targets than just <code>clean</code>: <code>all</code>, <code>check</code>, <code>debug</code>, <code>testbenches</code>, <code>run_test_script</code>, <code>createdir</code>, <code>maincpp</code>.</p>\n\n<p>The <code>maincpp</code> rule should be:</p>\n\n<pre><code>$(OBJDIR)/main.o: main.cpp\n $(CC) $(CFLAGS) -c -o $@ $&lt;\n</code></pre>\n\n<p>The <code>createdir</code> action is <code>@mkdir -p obj</code>, but should be written as <code>@mkdir -p $(OBJDIR)</code>.</p>\n\n<p><code>main: createdir $(OBJECTS)</code> has an improper prerequisite <code>createdir</code>. There is no guarantee that <code>createdir</code> will be made before <code>$(OBJECTS)</code>. I would eliminate <code>createdir</code> altogether and write instead:</p>\n\n<pre><code>$(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.cpp\n @mkdir -p $(@D)\n $(CC) $(CFLAGS) -c -o $@ $&lt;\n</code></pre>\n\n<p>I would rewrite the <code>main</code> rule as:</p>\n\n<pre><code>$(EXECUTABLE): $(OBJDIR)/main.o $(OBJECTS)\n $(CC) $(CFLAGS) $(LFLAGS) -o $@ $+ $(LIBS)\n</code></pre>\n\n<p>The variable for the C++ compiler is typically <code>$(CXX)</code> instead of <code>$(CC)</code>. (You might not even need to define it.)</p>\n\n<hr>\n\n<p>All together, with a few similar cleanups for the tests…</p>\n\n<pre><code>EXECUTABLE = main\n\n# compiler\nCXX = g++\nCFLAGS = -g -std=gnu++0x -Wall -Wno-reorder -I. $(SYSTEMC_INCLUDE_DIRS)\nLFLAGS = $(SYSTEMC_LIBRARY_DIRS)\nLIBS = -lsystemc-ams -lsystemc | c++filt\n\n# directory names\nSRCDIR = src\nOBJDIR = obj\nTSTDIR = tests\n\nSOURCES := $(wildcard $(SRCDIR)/*.cpp)\nINCLUDES := $(wildcard $(SRCDIR)/*.h)\nOBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)\nTEST_SRC := $(wildcard $(TSTDIR)/*.cpp)\nTESTS := $(TEST_SRC:$(TSTDIR)/%.cpp=$(TSTDIR)/%.o)\nTEST_EXES = $(TESTS:$(TSTDIR)/%.o=%.tst)\nrm = rm -rf\n\nall: $(EXECUTABLE)\n\ncheck: $(TEST_EXES)\n @cd $(TSTDIR); \\\n ./run_tests.sh\n\ndebug: CXX += -O0 -fno-inline\ndebug: all\n\n$(EXECUTABLE): $(OBJDIR)/main.o $(OBJECTS)\n $(CXX) $(CFLAGS) $(LFLAGS) -o $@ $+ $(LIBS)\n\n$(TEST_EXES): %.tst : $(TSTDIR)/%.o\n $(CXX) $(CFLAGS) $(LFLAGS) -o $@ $&lt; $(OBJECTS) $(LIBS)\n\n$(TESTS): $(TSTDIR)/%.o : $(TSTDIR)/%.cpp\n $(CXX) $(CFLAGS) -c -o $@ $&lt;\n\n$(OBJDIR)/main.o: main.cpp\n @mkdir -p $(@D)\n $(CXX) $(CFLAGS) -c -o $@ $&lt;\n\n$(OBJECTS): $(OBJDIR)/%.o : $(SRCDIR)/%.cpp\n @mkdir -p $(@D)\n $(CXX) $(CFLAGS) -c -o $@ $&lt;\n\nclean:\n $(rm) $(OBJDIR)\n $(rm) $(TSTDIR)/*.out\n $(rm) $(TESTS) $(TEST_EXES)\n $(rm) $(EXECUTABLE)\n\n.PHONY: all check debug clean\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:54:05.023", "Id": "45486", "ParentId": "45478", "Score": "2" } }, { "body": "<p>A couple of things I dislike about your set up.</p>\n\n<ol>\n<li>Your low level make file in the top level directory.</li>\n<li>You only have one object directory (so you can only have one type of build)<br>\nI have four types of build debug/release/coverage/size(built with size optimization)</li>\n<li>You use explicit commands where the makefile internal rules will work just as well.</li>\n</ol>\n\n<h3>1: At the top level your make file should just call the makefile in the source directory(s).</h3>\n\n<pre><code> # (you can have a target for all the commands you support)\n # (I use the following as my starting base)\n all:\n $(MAKE) -C src\n clean:\n $(MAKE) -C src clean\n debug:\n $(MAKE) -C src debug\n release: \n $(MAKE) -C src release\n size:\n $(MAKE) -C src size\n test:\n $(MAKE) -c src test\n veryclean:\n $(MAKE) -C src veryclean\n install:\n $(MAKE) -C src install\n</code></pre>\n\n<p>Some other things I define in my make file:</p>\n\n<pre><code> #\n # Basic block for building.\n # ?= define if not set on command line.\n ROOT ?= $(shell dirname `pwd`)\n BUILD ?= debug\n\n #\n # Set up SRC and OBJ directories.\n # Build debug/release/size and coverage into different directories.\n SRC_DIR = $(ROOT)/src\n OBJ_DIR = $(ROOT)/$(BUILD)\n\n #\n # Install by default done locally\n # but you do want to be able to install into the standard locations.\n PREFIX ?= $(ROOT)\n PREFIX_BIN ?= $(PREFIX)/bin\n PREFIX_INC ?= $(PREFIX)/include\n PREFIX_LIB ?= $(PREFIX)/lib\n</code></pre>\n\n<p>So</p>\n\n<pre><code> sudo make install PREFIX=/usr\n</code></pre>\n\n<p>will install the code into standard locations in the OS (or /usr/local if you prefer).</p>\n\n<h3>2: Object files of different types can not be linked together.</h3>\n\n<p>You must use the exact same set of flags on every object file to guarantee they are binary compatible. So I build <code>debug</code> and <code>release</code> versions of the executables into different object directories. That way when linking there is no possibility of accidentally mixing objects of different types.</p>\n\n<h3>3: Default rules</h3>\n\n<p>The default rule for C++ code (source to object is)</p>\n\n<pre><code>%.o: %.cpp\n $(CXX) -c $^ $(CPPFLAGS) $(CXXFLAGS) \n</code></pre>\n\n<p>The default rule for linking is </p>\n\n<pre><code>%: %.o\n $(CC) $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS)\n</code></pre>\n\n<p>I would adapt these rather than making your own set of variable names.</p>\n\n<h3>4: Commands</h3>\n\n<p>Standard conventions means that variables should be in all caps.</p>\n\n<pre><code>rm = rm -rf\n</code></pre>\n\n<p>I would change that too:</p>\n\n<pre><code>RM = rm -rf\n</code></pre>\n\n<p>Also defining the C compiler to g++ may not always do what you want.</p>\n\n<pre><code>CC = g++\n</code></pre>\n\n<p>I would prefer to re-define the C compiler as the C++ compiler and if need be then be explicit about the C++ compiler.</p>\n\n<pre><code># CXX = Define if needed. Defaults to the correct system compiler.\nCC = $(CXX)\n</code></pre>\n\n<h3>5: COMPILER flags.</h3>\n\n<p>Here you have a fixed set.</p>\n\n<pre><code>CFLAGS = -g -std=gnu++0x -Wall -Wno-reorder -I. $(SYSTEMC_INCLUDE_DIRS)\n</code></pre>\n\n<p>These look fine but I would not explicitly set them I would append to the ones defined by the makefile system:</p>\n\n<pre><code>CFLAGS += -g -std=gnu++0x -Wall -Wno-reorder -I. $(SYSTEMC_INCLUDE_DIRS)\n ## ^^^^^ Add my flags onto the default ones.\n</code></pre>\n\n<p>Also your flags include all things all the time. I would divide this up to define the flags based on the type of build you are doing.</p>\n\n<pre><code>CFLAGS += $(CFLAGS_$(BUILD)) -std=gnu++0x -Wall -Wno-reorder -I. $(SYSTEMC_INCLUDE_DIRS)\nCFLAGS_debug = -g\nCFLAGS_release = -O3\n</code></pre>\n\n<p>The <code>-Wall</code> is a good starting point. But it is by no way <code>All</code> the warning flags (just a small subset). I personally use a few more:</p>\n\n<pre><code>-Wall -Wextra -Wstrict-aliasing -ansi -pedantic -Werror -Wunreachable-code\n</code></pre>\n\n<h3>6: The last thing I do is encapsulate all my rules in a generic makefile.</h3>\n\n<p>Thus each project makefile only defines exactly what I need (and then includes the generic makefile). That way it is easy to see what I am actually building (and mistakes only need to be corrected in one place).</p>\n\n<p>Example of Generic <a href=\"https://github.com/Loki-Astari/ThorsSerializer/blob/master/Serialize/Makefile\" rel=\"nofollow\">makefile</a></p>\n\n<pre><code># My generic make file depends on this environment variable\nTHORSANVIL_ROOT = $(realpath ../)\n\n# This is what I want to build.\n# My tools support a couple of extensions\n# app: An executable.\n# slib: A shared lib\n# a: A static lib\n# dir: calls make -C &lt;sub dir&gt;\n# head: A header only C++ library\nTARGET = Serialize.slib\n\n#\n# Generic extension applied to all files. extensions.\nLINK_LIBS = Json\nUNITTEST_LINK_LIBS = Json\nFILE_WARNING_FLAGS += -Wno-overloaded-virtual\n\n#\n# Specific extensions applied to all this source file\nJsonSerilizeVardacTest_CXXFLAGS += -pedantic -Werror\n\n#\n# Now include the generic make file\n# With all the rules I have built up.\ninclude ${THORSANVIL_ROOT}/build/tools/Makefile\n</code></pre>\n\n<p>My generic build file can be found <a href=\"https://github.com/Loki-Astari/ThorMaker/blob/master/tools/Makefile\" rel=\"nofollow\">here</a>. Have a look and take what you find useful.</p>\n\n<h3>7: Plug for things I do but thats because I am ecentric.</h3>\n\n<p>The one thing I hate about make fils is the long lines it prints when building. These are useless and just confuse the output.</p>\n\n<pre><code>g++ -c URILexer.cpp -o debug/URILexer.o -fPIC -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code -Wno-long-long -Wno-unreachable-code -I/Users/myork/Repository/ThorWeb/build/include -isystem /Users/myork/Repository/ThorWeb/build/include3rd -DBOOST_FILESYSTEM_VERSION=3 -g -std=c++1y\ng++ -c URIParser.cpp -o debug/URIParser.o -fPIC -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code -Wno-long-long -Wno-unreachable-code -I/Users/myork/Repository/ThorWeb/build/include -isystem /Users/myork/Repository/ThorWeb/build/include3rd -DBOOST_FILESYSTEM_VERSION=3 -g -std=c++1y\ng++ -c URITail.cpp -o debug/URITail.o -fPIC -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code -Wno-long-long -Wno-unreachable-code -I/Users/myork/Repository/ThorWeb/build/include -isystem /Users/myork/Repository/ThorWeb/build/include3rd -DBOOST_FILESYSTEM_VERSION=3 -g -std=c++1y\n</code></pre>\n\n<p>So I make my makefile only print out the interesting stuff. If there are no errors all you get is the basics info you need (and a <code>GREEN OK</code>). You will get the full command line if there is an error.</p>\n\n<pre><code>Building debug\ng++ -c URILexer.cpp -g OK\ng++ -c URIParser.cpp -g OK\ng++ -c URITail.cpp -g OK\ng++ -c Fail.cpp -g\nERROR\ng++ -c Fail.cpp -o debug/Fail.o -fPIC -Wall -Wextra -Wstrict-aliasing -pedantic -Werror -Wunreachable-code -Wno-long-long -Wno-unreachable-code -I/Users/myork/Repository/ThorWeb/build/include -isystem /Users/myork/Repository/ThorWeb/build/include3rd -DBOOST_FILESYSTEM_VERSION=3 -g -std=c++1y\n========================================\n&lt; All the error messages.&gt;\n</code></pre>\n\n<p>I like to keep my unit test separate from my source. So I put all my unit tests in a sub directory under the source. The makefile detects its presence and forces a build of the unit tests if you try and install the code. The unit tests also automatically do code coverage and fail if you don't get an average of 85% across all the files:</p>\n\n<pre><code>&gt; make test\nBuilding Objects for Testing and Coverage\nflex URILexer.l OK\nbison URIParser.y OK\ng++ -c HostName.cpp -DCOVERAGE_ThorURI OK\ng++ -c URIParserInterface.cpp -DCOVERAGE_ThorURI OK\ng++ -c URILexer.cpp -DCOVERAGE_ThorURI OK\ng++ -c URI.cpp -DCOVERAGE_ThorURI OK\ng++ -c URILexer.lex.cpp -DCOVERAGE_ThorURI OK\ng++ -c URINormalize.cpp -DCOVERAGE_ThorURI OK\ng++ -c URIParser.tab.cpp -DCOVERAGE_ThorURI OK\ng++ -c HostNamePublicSuffixData.cpp -DCOVERAGE_ThorURI OK\na - coverage/URIParser.tab.o\na - coverage/URILexer.lex.o\na - coverage/HostName.o\na - coverage/HostNamePublicSuffixData.o\na - coverage/URI.o\na - coverage/URILexer.o\na - coverage/URINormalize.o\na - coverage/URIParserInterface.o\nDone\nBuilding Unit Tests\nBuilding coverage\ng++ -c unittest.cpp -DCOVERAGE_ThorURI OK\ng++ -c HostNameTest.cpp -DCOVERAGE_ThorURI OK\ng++ -c URIParserTest.cpp -DCOVERAGE_ThorURI OK\ng++ -c URITest.cpp -DCOVERAGE_ThorURI OK\ng++ -c URILexerTest.cpp -DCOVERAGE_ThorURI OK\ng++ -c URISortableTest.cpp -DCOVERAGE_ThorURI OK\ng++ -o coverage/unittest.app -DCOVERAGE_ThorURI OK\n Done Building coverage/unittest\nDone\nrm coverage/unittest.o\nRunning Unit Tests\nRunning main() from gtest_main.cc\n[==========] Running 53 tests from 5 test cases.\n[----------] Global test environment set-up.\n[----------] 2 tests from HostName\n[ RUN ] HostName.StandardTest\n[ OK ] HostName.StandardTest (0 ms)\n[ RUN ] HostName.BasicCom\n[ OK ] HostName.BasicCom (0 ms)\n[----------] 2 tests from HostName (0 ms total)\n\n[----------] 23 tests from URILexer\n[ RUN ] URILexer.Schema\n[ OK ] URILexer.Schema (0 ms)\n[ RUN ] URILexer.SchemaValidChar\n[ OK ] URILexer.SchemaValidChar (0 ms)\n[ RUN ] URILexer.SchemaFail\n[ OK ] URILexer.SchemaFail (0 ms)\n[ RUN ] URILexer.RegName\n[ OK ] URILexer.RegName (0 ms)\n[ RUN ] URILexer.RegNameValidChar\n[ OK ] URILexer.RegNameValidChar (0 ms)\n[ RUN ] URILexer.RegNameFail\n[ OK ] URILexer.RegNameFail (0 ms)\n[ RUN ] URILexer.HostIPV4\n[ OK ] URILexer.HostIPV4 (1 ms)\n[ RUN ] URILexer.HostIPV4Fail\n[ OK ] URILexer.HostIPV4Fail (0 ms)\n[ RUN ] URILexer.HostUserName\n[ OK ] URILexer.HostUserName (0 ms)\n[ RUN ] URILexer.HostUserNameFail\n[ OK ] URILexer.HostUserNameFail (0 ms)\n[ RUN ] URILexer.IPv6Future\n[ OK ] URILexer.IPv6Future (1 ms)\n[ RUN ] URILexer.IPv6FutureFail\n[ OK ] URILexer.IPv6FutureFail (0 ms)\n[ RUN ] URILexer.IPv6addressPrefix\n[ OK ] URILexer.IPv6addressPrefix (0 ms)\n[ RUN ] URILexer.IPv6addressMain\n[ OK ] URILexer.IPv6addressMain (1 ms)\n[ RUN ] URILexer.WordSegmentInFullPath\n[ OK ] URILexer.WordSegmentInFullPath (0 ms)\n[ RUN ] URILexer.WordSegmentAbsolutePath\n[ OK ] URILexer.WordSegmentAbsolutePath (0 ms)\n[ RUN ] URILexer.WordSegmentRelativePath\n[ OK ] URILexer.WordSegmentRelativePath (0 ms)\n[ RUN ] URILexer.SegmentValidChar\n[ OK ] URILexer.SegmentValidChar (0 ms)\n[ RUN ] URILexer.SegmentInvalid\n[ OK ] URILexer.SegmentInvalid (0 ms)\n[ RUN ] URILexer.Query\n[ OK ] URILexer.Query (0 ms)\n[ RUN ] URILexer.QueryInvalid\n[ OK ] URILexer.QueryInvalid (0 ms)\n[ RUN ] URILexer.Fragment\n[ OK ] URILexer.Fragment (0 ms)\n[ RUN ] URILexer.FragmentInvalid\n[ OK ] URILexer.FragmentInvalid (0 ms)\n[----------] 23 tests from URILexer (3 ms total)\n\n[----------] 8 tests from URIParser\n[ RUN ] URIParser.SchemaHostEmptyPath\n[ OK ] URIParser.SchemaHostEmptyPath (2 ms)\n[ RUN ] URIParser.SchemaHostPortEmptyPath\n[ OK ] URIParser.SchemaHostPortEmptyPath (1 ms)\n[ RUN ] URIParser.SchemaHostRoot\n[ OK ] URIParser.SchemaHostRoot (0 ms)\n[ RUN ] URIParser.SchemaHostPath\n[ OK ] URIParser.SchemaHostPath (1 ms)\n[ RUN ] URIParser.SchemaHostFile\n[ OK ] URIParser.SchemaHostFile (0 ms)\n[ RUN ] URIParser.SchemaHostFileQuery\n[ OK ] URIParser.SchemaHostFileQuery (0 ms)\n[ RUN ] URIParser.SchemaHostFileFrag\n[ OK ] URIParser.SchemaHostFileFrag (0 ms)\n[ RUN ] URIParser.SchemaHostFileQueryFrag\n[ OK ] URIParser.SchemaHostFileQueryFrag (0 ms)\n[----------] 8 tests from URIParser (4 ms total)\n\n[----------] 1 test from URISortable\n[ RUN ] URISortable.comparable\n[ OK ] URISortable.comparable (4 ms)\n[----------] 1 test from URISortable (4 ms total)\n\n[----------] 19 tests from URI\n[ RUN ] URI.allURI\n[ OK ] URI.allURI (0 ms)\n[ RUN ] URI.InvalidURL\n[ OK ] URI.InvalidURL (1 ms)\n[ RUN ] URI.clone\n[ OK ] URI.clone (0 ms)\n[ RUN ] URI.mainParts\n[ OK ] URI.mainParts (1 ms)\n[ RUN ] URI.DomainParts\n[ OK ] URI.DomainParts (0 ms)\n[ RUN ] URI.Normalize\n[ OK ] URI.Normalize (0 ms)\n[ RUN ] URI.NormalizeLowerCase\n[ OK ] URI.NormalizeLowerCase (0 ms)\n[ RUN ] URI.NormalizeEncode\n[ OK ] URI.NormalizeEncode (0 ms)\n[ RUN ] URI.NormalizeDecodeALPHA\n[ OK ] URI.NormalizeDecodeALPHA (1 ms)\n[ RUN ] URI.NormalizeDecodeHyphen\n[ OK ] URI.NormalizeDecodeHyphen (0 ms)\n[ RUN ] URI.NormalizeDecodeHyphon\n[ OK ] URI.NormalizeDecodeHyphon (0 ms)\n[ RUN ] URI.NormalizeDecodePeriod\n[ OK ] URI.NormalizeDecodePeriod (0 ms)\n[ RUN ] URI.NormalizeDecodeTilda\n[ OK ] URI.NormalizeDecodeTilda (0 ms)\n[ RUN ] URI.NormalizeRemoveDefaultPort\n[ OK ] URI.NormalizeRemoveDefaultPort (1 ms)\n[ RUN ] URI.NormalizePath\n[ OK ] URI.NormalizePath (0 ms)\n[ RUN ] URI.NormalizePathEndsSlash\n[ OK ] URI.NormalizePathEndsSlash (0 ms)\n[ RUN ] URI.NormalizePathRelative\n[ OK ] URI.NormalizePathRelative (0 ms)\n[ RUN ] URI.NormalizeQueryCombine\n[ OK ] URI.NormalizeQueryCombine (1 ms)\n[ RUN ] URI.NormalizeQuerySort\n[ OK ] URI.NormalizeQuerySort (0 ms)\n[----------] 19 tests from URI (5 ms total)\n\n[----------] Global test environment tear-down\n[==========] 53 tests from 5 test cases ran. (16 ms total)\n[ PASSED ] 53 tests.\n\n\n/Applications/Xcode.app/Contents/Developer/usr/bin/make VERBOSE=NONE PREFIX=/Users/myork/Repository/ThorWeb/build CXXSTDVER=14 TARGET_MODE=coverage report_coverage COVERAGE=\n\n\n\nGenerating Coverage for HostName.cpp\nGenerating Coverage for HostNamePublicSuffixData.cpp\nGenerating Coverage for URI.cpp\nGenerating Coverage for URILexer.cpp\nGenerating Coverage for URINormalize.cpp\nGenerating Coverage for URIParserInterface.cpp\nHostName.cpp 100%\nHostNamePublicSuffixData.cpp 100%\nURI.cpp 96%\nURILexer.cpp 81%\nURINormalize.cpp 0%\nURIParserInterface.cpp 100%\nOK Code Coverage Passed\n</code></pre>\n\n<p>Checking coverage for a particular file:\nNote: This line is printed out above as part of the test (I just add a specific file name).</p>\n\n<pre><code>&gt; make VERBOSE=NONE PREFIX=/Users/myork/Repository/ThorWeb/build CXXSTDVER=14 TARGET_MODE=coverage report_coverage COVERAGE=URILexer.cpp\nURILexer.cpp 81%\n -: 0:Source:URILexer.cpp\n -: 0:Graph:coverage/URILexer.gcno\n -: 0:Data:coverage/URILexer.gcda\n -: 0:Runs:1\n -: 0:Programs:1\n -: 1:\n -: 2:#include \"URILexer.h\"\n -: 3:#include &lt;stdexcept&gt;\n -: 4:\n -: 5:using namespace ThorsAnvil::Web;\n -: 6:\n 178: 7:URILexer::URILexer(std::istream&amp; input)\n -: 8: : URIBaseFlexLexer(&amp;input, &amp;std::cerr)\n -: 9: , tokenStart(0)\n -: 10: , tokenEnd(0)\n 178: 11:{}\n -: 12:\n 881: 13:int URILexer::yylex(URIParserInterface&amp; pi)\n -: 14:{\n 881: 15: tokenStart = tokenEnd;\n 881: 16: int result = URIBaseFlexLexer::yylex();\n 881: 17: tokenEnd = tokenStart + yyleng;\n 881: 18: pi.parsedCharacters(yyleng);\n 881: 19: return result;\n #####: 20:}\n -: 21:\n #####: 22:void URILexer::LexerError(const char* msg) {throw std::runtime_error(std::string(\"URI parsing error: \") + msg);}\n -: 23:\n -: 24:TokenMarker URILexer::tokenMark() const\n -: 25:{\n -: 26: // See URIUtils.h\n -: 27: //std::cerr &lt;&lt; \"Token Mark: \" &lt;&lt; tokenStart &lt;&lt; \" : \" &lt;&lt; tokenEnd &lt;&lt; \"\\n\";\n 523: 28: return (tokenEnd &lt;&lt; 16) | tokenStart;\n -: 29:}\n -: 30:\n -: 31:\n</code></pre>\n\n<h3>8: Learn to use the tools for building makefiles.</h3>\n\n<p>I like my tools because they build stuff the way I want.\n<strong>BUT</strong> they are <strong>very brittle</strong> to changes in the environment. They need to be plugged into a <code>automake</code> or some other tool for creating makefiles so that they become more cross platform.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:00:19.667", "Id": "79395", "Score": "1", "body": "Really interesting! I found it really useful. I have started reading about `automake` and `autoconf`. I'll give it a try, but your instructions look pretty neat. Thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:07:53.103", "Id": "45511", "ParentId": "45478", "Score": "4" } } ]
{ "AcceptedAnswerId": "45486", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:39:57.063", "Id": "45478", "Score": "3", "Tags": [ "c++", "optimization", "makefile", "make" ], "Title": "Optimize a Makefile" }
45478
<p>I currenctly have a class which does several requests to a database with several methods (called from main method) sharing this pattern :</p> <pre><code>public int getSomething(String id, File file) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; int lines = 0; try { conn = openConnection(); ps = conn.prepareStatement(SQL_QUERY.replace("?", id)); ps.setFetchSize(1500); rs = ps.executeQuery(); lines += nnpw.writeInFile(file, rs); } catch (Exception e) { e.printStackTrace(); } finally { close(rs, ps, conn); } return lines; } </code></pre> <p>The method <code>openConnection()</code> is in the main class and looks like this :</p> <pre><code>protected Connection openConnection() throws SQLException, ClassNotFoundException { Class.forName(jdbcParams.getString("jdbc.driver")); Connection connect; connect = DriverManager.getConnection(jdbcParams.getString("jdbc.url"), //$NON-NLS-1$ jdbcParams.getString("jdbc.username"), //$NON-NLS-1$ jdbcParams.getString("jdbc.password")); //$NON-NLS-1$ return connect; } </code></pre> <p>Would it be better if I had a <code>Connection</code> parameter in the main class, which I would open and close like this, and modify the <code>close(rs, ps, conn)</code> from above to <code>close(rs, ps)</code> ?</p> <pre><code>public MainClass { Connection conn; public static void main(String[] args) { try { int lines = 0; DBExtract ex = new DBExtract(); ... conn = openConnection() lines += ex.getSomething("1", file, conn); lines += ex.getSomethingElse("1", file, conn); lines += ex.getSomethingDifferent("1", file, conn); conn.close() } catch(Exception e) { e.printStackTrace(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:49:20.683", "Id": "79343", "Score": "2", "body": "ASIK, create one connection and open it when needed and close it once your DB operations are completed. **There is no need to create new one**." } ]
[ { "body": "<p>I have to agree with Praveen's comment that you should open a connection when you need it and close it when your are done with the Database operations.</p>\n\n<p>But first I have to make a <strong>serious objection</strong> to this statement:</p>\n\n<pre><code>ps = conn.prepareStatement(SQL_QUERY.replace(\"?\", id));\n</code></pre>\n\n<h1>That is not the way you should use prepared statements!</h1>\n\n<p>By using that, you are opening yourself to <strong>SQL Injection</strong>. Consider what would happen if an id something like <code>'random-useless-name' OR 1 == 1; DROP TABLE sometablename; --</code> was given. Catastrophic failure! </p>\n\n<p><strong>Instead, use this:</strong></p>\n\n<pre><code>ps = conn.prepareStatement(SQL_QUERY);\nps.setString(1, id);\n</code></pre>\n\n<p>You might want to take a look at the <a href=\"http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html\">PreparedStatement tutorial</a> to see how PreparedStatements are normally used. If you are using parameters in the query, <strong>use the <code>setXXX</code> methods!</strong></p>\n\n<hr>\n\n<p>I would say that <strong>yes</strong>, it is better if you extract the Connection parameter to the main method and provide it to your <code>getSomething</code> method(s). I would use it as a local variable if possible though. Also make sure to put the <code>conn.close();</code> inside a <strong>finally</strong> statement and not at the end of the <code>try</code>.</p>\n\n<pre><code>public static void main(String[] args) {\n Connection conn = null;\n try {\n int lines = 0;\n DBExtract ex = new DBExtract();\n ...\n conn = openConnection();\n lines += ex.getSomething(\"1\", file, conn);\n lines += ex.getSomethingElse(\"1\", file, conn);\n lines += ex.getSomethingDifferent(\"1\", file, conn);\n } catch(Exception e) {\n e.printStackTrace();\n } finally {\n if (conn != null)\n conn.close();\n }\n}\n</code></pre>\n\n<p>In this way the caller could also control the transactional state of bulk operations, that is it can decide if and when to commit or to rollback.</p>\n\n<p>Finally, using local variables in place of member variables reduces the chance of having connection leaks, because you really need to be sure to call the \"close\" method.</p>\n\n<hr>\n\n<p>Future suggestions:</p>\n\n<p>If you have an application that requires several database connections that should be able to be open simultaneously I recommend using <a href=\"http://sourceforge.net/projects/c3p0/\">c3p0 Connection Pooling</a></p>\n\n<p>If you are working on a mid-size to large-size project and want some assistance with the database stuff, I recommend <a href=\"http://hibernate.org/orm/documentation/getting-started/\">learning Hibernate</a></p>\n\n<p>C3P0 and Hibernate can be used at the same time, but they <a href=\"http://www.mkyong.com/hibernate/how-to-configure-the-c3p0-connection-pool-in-hibernate/\">require some configuration</a>. They take a while to configure for the first time, but once you got it running they do a lot of things for you. (They're just suggestions though, you should prioritize the other things first!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:08:40.710", "Id": "79357", "Score": "2", "body": "If OP use Java 7, he should use try-with-resources as `Connection` implements `AutoCloseable`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:18:22.087", "Id": "45489", "ParentId": "45479", "Score": "9" } } ]
{ "AcceptedAnswerId": "45489", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T10:46:32.880", "Id": "45479", "Score": "5", "Tags": [ "java", "jdbc" ], "Title": "Connection to a database, do I need to create a new one and close it everytime?" }
45479
<p>I'm sharing C# code with a fellow programmer who is more use to writing C++. He uses <code>#if</code> and <code>#endif</code> directives (which I do not tend to use) and when they occur they have no indentation, for example </p> <pre><code> private void dumpToDisplay() { #if false ushort[] ScanStatus = new ushort[6]; for (int ch = 0; ch &lt; 6; ch++) ScanStatus[ch] = mySteppers.GetStatus(ch); return; #endif string dumpString = stepDump(); Debug.Print(dumpString); } </code></pre> <p>It is interesting that the code sample in <a href="http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx" rel="nofollow">the <code>#if</code> C# documentation</a> adopts the same convention and has no indentation for the <code>#if</code> and <code>#endif</code> directives. Is this important? It certainly makes them stand out, but is that good?</p>
[]
[ { "body": "<blockquote>\n <p>Is indentation of #if &amp; #endif directives an important readability convention?</p>\n</blockquote>\n\n<p>I think you mean outdentation (i.e. the <code>#if</code> is at the start of the line).</p>\n\n<p>I'd say 'yes' because:</p>\n\n<ul>\n<li>It's conventional</li>\n<li>Unlike <code>if</code> statements, <code>#if ... #endif</code> statements don't use braces (<code>{</code> and <code>}</code>)</li>\n<li>The contents of (i.e. lines between) a <code>#if ... #endif</code> don't have an extra indent (as they would inside an <code>if { ... }</code> statement)</li>\n</ul>\n\n<p>It's also/more important for readability to have a language-aware IDE which:</p>\n\n<ul>\n<li>Knows what preprocessor symbols are defined/redefined</li>\n<li>Therefore knows whether each <code>#if</code> is true or false</li>\n<li>And colorizes the text accordingly (e.g. grey for disabled text)</li>\n</ul>\n\n<hr>\n\n<p>The Visual Studio IDE automatically moves <code>#if</code> statements to the left-most column. Any formatting which the IDE does automatically is, I assume, the best way to do it (if only because otherwise you're fighting with the IDE reformatting your code).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:54:52.537", "Id": "45487", "ParentId": "45482", "Score": "10" } }, { "body": "<p>I think it makes sense this way, because the <code>#if</code> directives are pretty much outside of the normal syntax. For example, you can write something like:</p>\n\n<pre><code>#if DEBUG\n if (CheckConditionDebug())\n {\n DoADebug();\n#else\n if (CheckCondition())\n {\n DoA();\n#endif\n DoB();\n }\n</code></pre>\n\n<p>This is valid code in both states (<code>DEBUG</code> defined or not), but there is no good way to indent the directives.</p>\n\n<p>Note: I'm not saying that this is a good use of <code>#if</code>, just that it is a possible use and that it makes sense to take this into account.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:41:57.500", "Id": "45496", "ParentId": "45482", "Score": "14" } } ]
{ "AcceptedAnswerId": "45487", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:29:30.943", "Id": "45482", "Score": "12", "Tags": [ "c#" ], "Title": "Is indentation of #if & #endif directives an important readability convention?" }
45482
<p>I have been trying various formats of namespaces and modules patterns, however I have not come across a solution that I would use for all my projects.</p> <p>I've been developing the following, that would allow me to separate my application through applications, modules, functions and global variables. Possibly I'm going to add the possibility to have public and private variables and methods.</p> <pre><code>/*-------------------------------------------------------------------------- * Project name * * Created : 01/01/2014 * Modified : 01/01/2014 * Version : 0.1 * Developer : Developer Name * ---------------------------------------------------------------------------*/ /** * @class mainClassName * @constructor */ window.APP_NAME = window.APP_NAME || {}; window.APP_NAME.moduleName = window.APP_NAME.moduleName || {}; window.APP_NAME.deepExtend = window.APP_NAME.deepExtend || {}; window.APP_NAME.moduleName.globalVariableAvailableForEveryModuleFunctions = 0; window.APP_NAME.moduleName.functionInsideModule1 = function (options) { "use strict"; /*jslint nomen: true*/ /*global $, jQuery*/ // Check for arguments here. if (arguments.length !== 1) { throw new Error('[ClassName here] Please provide your options.'); } // if // Increase global variable. window.APP_NAME.moduleName.globalVariableAvailableForEveryModuleFunctions += 1; // Store module defaults. window.APP_NAME.moduleName.config = { name: 'John', age: 29 }; // Parse incoming object that stores config files. window.APP_NAME.deepExtend(window.APP_NAME.moduleName.config, options); // Rest of the application here. alert(window.APP_NAME.moduleName.config.name); // Call function in same module, to alert the age window.APP_NAME.moduleName.functionInsideModule2(); }; window.APP_NAME.moduleName.functionInsideModule2 = function () { "use strict"; /*jslint nomen: true*/ /*global $, jQuery*/ // Store global in local var. var age = window.APP_NAME.moduleName.config.age; // Alert age stored in Module config. alert(age); }; // Helper function to change config defaults. window.APP_NAME.deepExtend = function (destination, source) { for (var property in source) { if (source[property] &amp;&amp; source[property].constructor &amp;&amp; source[property].constructor === Object) { destination[property] = destination[property] || {}; arguments.callee(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; // Let's run the application! (function () { new window.APP_NAME.moduleName.functionInsideModule1({ name: 'Mary' }); }()); </code></pre> <p>I would like to receive some feedback on this kind of approach, and what you would change.</p> <p>Variable and method names are long to provide a better understand of context.</p>
[]
[ { "body": "<p>I don't like this approach.</p>\n\n<p>The biggest issue I have with this code is the fact that namespaces are attached to every lookup. Beyond being a bit long and awkward, it's hard to see the difference between two very similar looking symbol names when they start in exactly the same fashion. This is especially important when dealing with constructors, which are typically capitalized to distinguish them from ordinary functions. Confusing a function and a constructor is dangerous in JavaScript because it will typically generate lots of bugs, but few exceptions.</p>\n\n<p>The other problem is access. Your code is heavily namespaced, but doesn't seem to provide much protection of access. Lots of variables in different namespaces seem to be visible to one another, and that's going to make life very difficult for you if you need to make this code testable. Cross-dependency should be handled by explicit dependency injection.</p>\n\n<p>Rather than using long namespaces, I would instead break my modules into files that each execute in an instantly invoked function expression (these are sometimes called 'modules', which might make your nomenclature a little confusing). Within each, I would use non-namespaced symbol names, before finally mapping the interface to these symbols onto a global object.</p>\n\n<p>This approach works well at varying scales, because the inner bodies of module files are still very simple, but there's still proper encapsulation of module-specific logic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:15:52.633", "Id": "79549", "Score": "0", "body": "Hello @JimmyBreck-McKye, thanks for answering. Ok, the namespaces may be a little more organized, by saving the namespace in a unique var, that I would use for the preceding scopes. Thanks for the note about constructors and capitalized names.\n\nI have not worked over private variables in this example. Do you have any good example on dependency injection?\n\nI was thinking about breaking my modules into files, and this example I've posted it is a module.\n\nDo you have any other suggestions on how to make it a better \"module\"? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T20:11:35.500", "Id": "80218", "Score": "1", "body": "`instantly invoked function expression` I think you'll find that `immediately invoked function expression` has become the more standardized expansion, though usually written as `IIFE`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T08:57:37.983", "Id": "80276", "Score": "0", "body": "@JeremyJStarcher I have already used an IIFE in to call new instances." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:12:14.903", "Id": "45531", "ParentId": "45483", "Score": "4" } }, { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p>In the below block, you can assume that if <code>window.APP_NAME</code> exists, that deepExtend is assigned, and if it did not exist, then obviously <code>deepExtend</code> is not assigned.</p>\n\n<p>So I would do this:</p>\n\n<pre><code>window.APP_NAME = window.APP_NAME || {\n\n deepExtend : deepExtend = function (destination, source) {\n for (var property in source) {\n if (source[property] &amp;&amp; source[property].constructor &amp;&amp;\n source[property].constructor === Object) {\n destination[property] = destination[property] || {};\n arguments.callee(destination[property], source[property]);\n } else {\n destination[property] = source[property];\n }\n }\n return destination;\n }\n}\n</code></pre>\n\n<p>Wrapped inside an IIFE which would then have the <code>\"use strict\";</code></p></li>\n<li><p>On second thought, I don't like window.APP_NAME, just go for var APP_NAME, there is no good reason to attach straight to <code>window</code>, if you insist on doing this, then you should pass <code>window</code> to the IFFE I mentioned above.</p></li>\n<li><p><code>deepExtend</code> seems fine, though I would advise to see how jQuery does this, there are many corner cases in JavaScript</p></li>\n<li><p>This is wrong :</p>\n\n<pre><code>new window.APP_NAME.moduleName.functionInsideModule1({\n name: 'Mary'\n});\n</code></pre>\n\n<ul>\n<li>no reason to use window there</li>\n<li>namespacing takes up horizontal space ( bad ) for no discernible benefit</li>\n<li><p>if it is a constructor it should start with an uppercase F<br>\nI would expect</p>\n\n<pre><code>new moduleName.FunctionInsideModule1({\n name: 'Mary'\n});\n</code></pre>\n\n<p>And even this seems ugly (your example function name is long..)</p></li>\n</ul></li>\n<li><p>All in all, I am not a big fan of your approach, too hard to type, too hard to read, not a lot of benefits.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:25:28.750", "Id": "79550", "Score": "0", "body": "Thanks for answering @konijin. 1 - Seems good, but you would include all the functions inside that APP_NAME object? 2 - Imagine I have got APP_NAME inside an IIFE, other modules will not be able to access this one if I don't pass it to outside. 3 - I've looked exactly because of that. I didn't want to import all the library everytime I wanted to do some import. 4 - How would I get the namespace that is inside an IFFE? 5 - Do you have any good approach you would suggest me?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:14:54.640", "Id": "45536", "ParentId": "45483", "Score": "4" } }, { "body": "<p>Lets look at a couple of improvements:</p>\n\n<p><code>new</code> is creating an object that you aren't using. <em>read edit for clarification</em></p>\n\n<pre><code>new window.APP_NAME.moduleName.functionInsideModule1({\n name: 'Mary'\n});\n</code></pre>\n\n<p>The function <code>functionInsideModule1</code> doesn't return an object and doesn't assign anything to <code>this</code>. So there is no need for the <code>new</code>. \nYou're referencing the whole namespace <code>window.APP_NAME.moduleName</code> every time. Instead try putting it in a variable. Or maybe on the inside of the module refer to <code>this</code> instead.</p>\n\n<pre><code>(function () {\n\n var moduleName = window.APP_NAME.moduleName;\n\n moduleName.functionInsideModule1 = function (options) {\n /* snip ... */\n\n moduleName.globalVariableAvailableForEveryModuleFunctions += 1;\n // OR\n this.globalVariableAvailableForEveryModuleFunctions += 1;\n };\n\n moduleName.functionInsideModule1({\n name: 'Mary'\n });\n\n}());\n</code></pre>\n\n<p><strong>Edit:-</strong></p>\n\n<p>To create a new instance of <code>moduleName</code> you need to do this:</p>\n\n<pre><code>(function () {\n // private variables go here\n var globalPrivateCount = 0;\n\n var moduleName = window.APP_NAME.moduleName = window.APP_NAME.moduleName || function moduleName(initialval) {\n globalPrivateCount ++;\n\n this.globallyAccessible = 'unique for each instance';\n\n this.functionInsideModule1 = function (options) { ... };\n this.functionInsideModule2 = function (options) { ... };\n\n var instancePrivateVariable = initialVal;\n\n this.incr = function () { instancePrivateVariable++; };\n\n return this;\n };\n moduleName.nonUniqueGloballyAccessible = 0;\n}());\n</code></pre>\n\n<p>and the usage is something like:</p>\n\n<pre><code>var moduleName = window.APP_NAME.moduleName;\nvar firstInstance = new moduleName(10);\n// OR\nvar anotherInstance = new window.APP_NAME.moduleName(20);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:28:36.327", "Id": "79551", "Score": "0", "body": "Thanks for answering @JamesKhoury. Regarding 'new', imagine I do need various instances of the function. In this example I don't, but possibly I would need them. Isn't it the right way to do it? Only calling the function would retrieve me the same instance, causing the variables to be overwritten by the last function call values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T23:10:15.540", "Id": "79906", "Score": "0", "body": "@IvoPereira Depends if you want an instance of `moduleName` or `functionInsideModule1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T10:54:05.493", "Id": "80126", "Score": "0", "body": "Sorry I mispelled it. I was talking about instancing the moduleName itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T12:44:01.897", "Id": "80133", "Score": "0", "body": "@IvoPereira then it is wrong. A new instance of `moduleName` needs you to do `APP_NAME.moduleName = function () { ... }` and `var myinstance = new moduleName()`. Would you like a specific example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T14:37:49.330", "Id": "80150", "Score": "0", "body": "That is what I meant to, a new instance of moduleName. You said there was no need for new. But would I do it if I don't instantiate various moduleNames?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T02:01:33.147", "Id": "80260", "Score": "0", "body": "@IvoPereira I've added an explanation to show how it should be done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T11:12:59.843", "Id": "80297", "Score": "0", "body": "thanks, that example clear things a lot. But why would you not wrap the instantiations with an IIFE? I'm going to test some stuff on your approach, thanks a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T11:19:19.517", "Id": "80302", "Score": "0", "body": "EDIT: Running that code would return me the error: \"Cannot read property 'moduleName' of undefined\", I guess that it cannot read moduleName as it is inside an IIFE. Any ideas?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T22:44:21.183", "Id": "80453", "Score": "0", "body": "@IvoPereira obviously I missed a `var moduleName = window.APP_NAME.moduleName;`" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:57:59.937", "Id": "45592", "ParentId": "45483", "Score": "5" } }, { "body": "<p>I don't like your <code>deepExtend</code> for the following reasons:</p>\n\n<ul>\n<li>You're not handling arrays which may contain nested objects no?</li>\n<li>You don't handle the case where the destination property is an object but source property is a primitive. So for instance <code>deepClone({x: {a: []}}, {x: \"abc\"});</code> will produce some fun results ;)</li>\n<li><code>arguments.callee</code> can not be used in strict mode <a href=\"https://stackoverflow.com/a/235760/1517919\">(with good reason)</a> and should be avoided. I would rather you recursively deep extend using an explicit function call. </li>\n</ul>\n\n<p>Note, declaring your function as below only exposes the <code>deepExtend</code> variable name only inside of the function (because of a JavaScript oddity).</p>\n\n<pre><code> window.APP_NAME.deepExtend = function deepExtend(destination, source) {\n /* ... */\n deepExtend(destination[property], source[property]);\n };\n</code></pre>\n\n<ul>\n<li><p>Your is object check is clever and prevents the function from extending classes like a <code>RegExp</code>. I'm pretty sure this line is redundant as any non null/undefined object will have a constructor AFAIK.</p>\n\n<p>source[property] &amp;&amp; source[property].constructor &amp;&amp; source[property].constructor === Object</p></li>\n</ul>\n\n<p>Regardless, I would recommend you rewrite your is object check to use <code>toString</code> on the object. This is more reliable in case the user decides to give you some weird object like <code>{ x: {constructor: false}}</code></p>\n\n<pre><code>var toString = Object.prototype.toString;\n\n/* .... */\ntoString.call(obj) === \"[object Object]\";\n</code></pre>\n\n<p>That said, I would recommend you investigate some of the more reputable <code>deepClone</code> or <code>merge</code> functions such as <a href=\"https://github.com/lodash/lodash/blob/master/dist/lodash.compat.js#L1759-1822\" rel=\"nofollow noreferrer\"><code>lodash</code></a>, <a href=\"https://github.com/mootools/mootools-core/blob/89167e8da2c4e24b379e2621089ea859591b15f6/Source/Core/Core.js#L348-369\" rel=\"nofollow noreferrer\"><code>Mootools</code></a> or this <a href=\"https://gist.github.com/ElliotChong/3861963\" rel=\"nofollow noreferrer\">simple underscore implementation</a>.</p>\n\n<p>Personally, I think your function is probably fine after a few as below. Note I'm still not handling arrays which you may or not decide to include.</p>\n\n<pre><code>var toString = Object.prototype.toString;\n\n// Helper function to change config defaults.\nwindow.APP_NAME.deepExtend = function deepExtend(destination, source) {\n var destType, sourceType;\n for (var property in source) {\n destType = toString.call(destination[property]);\n sourceType = toString.call(source[property]);\n\n if (destType === sourceType &amp;&amp; destType === \"[object Object]\") { //both must be objects otherwise choose source\n destination[property] = destination[property] || {};\n deepExtend(destination[property], source[property]);\n } else {\n destination[property] = source[property];\n }\n\n }\n return destination;\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-03T05:03:34.260", "Id": "46144", "ParentId": "45483", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:31:03.617", "Id": "45483", "Score": "10", "Tags": [ "javascript", "design-patterns", "namespaces" ], "Title": "JavaScript Good Patterns - Is this a good example?" }
45483
<p>Here's the first functional version of my Python 2 script for processing comments in C++ source files. It's a personal project, I expect to expand it later with more advanced options (mainly about replacing comments with whitespace or marking their original positions in the comment-only output).</p> <p>It's also intended as a learning excercise. I am self-learned in Python, my primary language is C++. So the core of my question is whether the code is "Pythonic" and if not, how to improve on that. I don't want to "write C++ with a different syntax," I want to (learn to) write proper Python.</p> <p>I will of course also welcome any other comments (general style, efficiency, safety).</p> <pre><code>#! /usr/bin/env python # Copyright Petr Kmoch 2014 """Script for processing comments and non-comment code in C++ files. The goal of this script to extract comments from C++ files and output only the comments, only the non-comment code, or both. For a quick usage summary, pass '-h' or '--help' as a command-line argument. """ import argparse import os import re import sys class Progress(object): """This class stores intermediary data when processing a single line of input. It is used as a means of communicating data between the processFile() function and State_* objects. It contains the following members: line: The tail part of the input line which has not been processed yet. finished: Boolean flag indicating that the entire line has been processed. stateChange: If not None, this member holds a callable which takes the state stack as argument and will modify it according to the results of processing the line. noncomments: String of non-comments extracted from the line during processing. comments: String of comments extracted from the line during processing. """ def __init__(self, line): object.__init__(self) self.line = line self.resetProcessing() def resetProcessing(self): """Clear the results of previously processing a piece of the line. """ self.finished = False self.stateChange = None self.noncomments = '' self.comments = '' def extractNoncomment(self, length = None): """Move a part of the current line to the `noncomments` member. Removes the first `length` characters from `line` and appends them to `noncomments`. If `length` is not specified, the entire line is moved. """ self.noncomments += self.extract(length) def extractComment(self, length = None): """Move a part of the current line to the `comments` member. Removes the first `length` characters from `line` and appends them to `noncomments`. If `length` is not specified, the entire line is moved. """ self.comments += self.extract(length) def extract(self, length): """Extract a part of the current line and return it. Removes the first `length` characters from `line` and returns them. If `length` is not specified, the entire line is used. """ if length is None: val = self.line self.line = '' return val else: val = self.line[0 : length] self.line = self.line[length:] return val class State_Normal(object): """State class representing normal C++ code. This state represents processing normal C++ code. It is also the initial state in which a file starts. """ regex = re.compile('["\'/]') def process(self, progress): """Process `progress.line` as normal C++ code. When this funciton encounters a start of a character literal, string literal or comment, it switches state accordingly. Otherwise, it just treats the text it processes as non-comments. """ progress.resetProcessing() while progress.line: match = self.regex.search(progress.line) if not match: progress.extractNoncomment() elif match.group() == '/': nextChar = progress.line[match.start() + 1] if nextChar == '/' or nextChar == '*': progress.extractNoncomment(match.start()) progress.extractComment(2) if nextChar == '/': progress.stateChange = lambda stack: stack.append(State_LineComment()) else: progress.stateChange = lambda stack: stack.append(State_BlockComment()) return else: progress.extractNoncomment(match.end()) else: progress.extractNoncomment(match.end()) progress.stateChange = lambda stack: stack.append(State_Literal(match.group())) return progress.finished = True class State_Literal(object): """State class representing a character or string literal. This state represents processing a character or string literal. """ regexes = { '"' : re.compile('["\\\\]') , "'" : re.compile("['\\\\]") } def __init__(self, delim): """Initialise for a particular literal type (string or character). delim: A string containing just the opening delimiter: either a single quote (') or double quote (") """ object.__init__(self) self.delim = delim self.regex = self.regexes[delim] def process(self, progress): """Process `progress.line` as the contents of a character or string literal. This function processes the line until a non-escaped literal-closing character (' or ") is encoutered, at which point it pops this state from the stack. Text processed is treated as a non-comment. """ progress.resetProcessing() while progress.line: match = self.regex.search(progress.line) if not match: progress.extractNoncomment() elif match.group() == '\\': progress.extractNoncomment(match.end() + 1) # Extract the backslash and the following character else: progress.extractNoncomment(match.end()) progress.stateChange = lambda stack: stack.pop() return progress.finished = True class State_LineComment(object): """State class representing a //-style comment. This state represents processing a comment introduced by // """ regex = re.compile('(\\\\*)\n$') def process(self, progress): """Process `progress.line` as the contents of a //-style comment. The entire line is processed as a comment. Unless it ends with a backslash-escaped newline, this state is popped from the stack. """ progress.resetProcessing() match = self.regex.search(progress.line) if len(match.group(1)) % 2 == 0: progress.extractComment() progress.noncomments += '\n' progress.stateChange = lambda stack: stack.pop() else: progress.extractComment() progress.finished = True class State_BlockComment(object): """State class representing a /* */-style comment. This state represents processing a comment delimited by /* and */ """ regex = re.compile('\\*/') def process(self, progress): """Process `progress.line` as the contents of a //-style comment. This function processes the line until */ is encountered, at which point it pops this state from the stack. Text processed is treated as a comment. """ progress.resetProcessing() match = self.regex.search(progress.line) if not match: progress.extractComment() progress.finished = True else: progress.extractComment(match.end()) progress.comments += '\n' progress.stateChange = lambda stack: stack.pop() def createArgParser(progName): """Create and initialise an argparse.ArgumentParser object. This function returns a argument parsing object initialised for parsing ccp arguments. progName: String to use as the program's name in the command-line usage help. """ parser = argparse.ArgumentParser( description = 'C and C++ comment processor' , prog = progName ) parser.add_argument( '-c', '--comments' , nargs = '?' , type = argparse.FileType('w') , const = sys.stdout , help = '\ Output comments, optionally specifying a destination file. \ If -c is used and -o is not, non-comment output will be suppressed. \ When COMMENT_FILE is not specified, standard output is used.\ ' , metavar = 'COMMENT_FILE' , dest = 'commentFile' ) parser.add_argument( '-o', '--output' , nargs = '?' , type = argparse.FileType('w') , const = sys.stdout , help = '\ Output non-comments, optionally specifying a destination file. \ This is the default action if none of -o and -c is specified. \ When OUTPUT_FILE is not specified, standard output is used.\ ' , metavar = 'OUTPUT_FILE' , dest = 'outputFile' ) parser.add_argument( 'inputFile' , nargs = '?' , type = argparse.FileType('r') , default = sys.stdin , help = '\ Input file to process. If not specified, standard input is used.\ ' , metavar = 'INPUT_FILE' ) return parser def parseArguments(args): """Parse the command line `args` and return the resulting options. args: Sequence of command-line arguments, including the program being invoked. Typical use is passing `sys.argv`. """ parser = createArgParser(os.path.basename(args[0])) return parser.parse_args(args[1:]) def validate(options): """Validate options retrieved from commandline. This function detects invalid settings in `options` (which are assumed to come from parsing command-line arguments), if any. It also does general post-processing of the options beyond what can be expressed in `argparse`. """ if not options.outputFile and not options.commentFile: options.outputFile = sys.stdout def process(options): """Act on valid `options`. This function processes the inputs specified in `options`. Each input file is fed to processFile(). """ processFile(options.inputFile, options) def processFile(inputFile, options): """Process `inputFile` according to `options`. This function parses `inputFile`, spits it into the comment and non-comment parts, and outputs one or both of them based on the settings in `options`. """ stateStack = [State_Normal()] for line in inputFile: progress = Progress(line) while not progress.finished: stateStack[-1].process(progress) if progress.stateChange: progress.stateChange(stateStack) if options.outputFile and progress.noncomments: options.outputFile.write(progress.noncomments) if options.commentFile and progress.comments: options.commentFile.write(progress.comments) def main(args): options = parseArguments(args) validate(options) process(options) if __name__ == '__main__': main(sys.argv) </code></pre> <p>One thing I am aware of is that the code does not handle trigraphs; they are somewhere near the end of the to-do list.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:00:56.360", "Id": "79365", "Score": "0", "body": "Did you take '\\' and `//?` into account? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:02:05.317", "Id": "79366", "Score": "0", "body": "@Morwenn How are these special? I don't handle trigraphs, though, and I should have mentioned that in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:39:17.040", "Id": "79370", "Score": "0", "body": "These are special for EOL comments since they can \"invalidate\" a line break." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:43:11.897", "Id": "79371", "Score": "0", "body": "@Morwenn A `//` comment continuation caused by a backslash is accounted for. With `//?`, did you perhaps mean the `??/` trigraph?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:47:18.063", "Id": "79372", "Score": "1", "body": "Yes, totally `??/`. My bad." } ]
[ { "body": "<p>A few brief comments from an initial read through:</p>\n\n<ul>\n<li><p>A lot of your method names are mixed case, but the Python convention is lowercase with underscores. The Python style guide is <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>:</p>\n\n<blockquote>\n <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>\n \n <p>mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.</p>\n</blockquote>\n\n<p>PEP 8 also recommends 4 spaces for indentation, rather than the 2 space which you’ve used, but that’s not worth getting too worked up about.</p></li>\n<li><p>Why do the docstrings for <code>extractNonComment</code> and <code>extractComment</code> both say they append to <code>noncomments</code>, when this doesn’t seem to match what they’re actually doing?</p></li>\n<li><p>Within the <code>extract</code> method: if in an initial bound in a string slice isn’t set, it defaults to 0, so you can replace <code>val = self.line[0 : length]</code> by <code>val=self.line[:length]</code>.</p>\n\n<p>Next, string slices that start or end in <code>None</code> return the whole string. For example:</p>\n\n<pre><code>&gt;&gt;&gt; my_string = \"12345\\n\"\n&gt;&gt;&gt; my_string[:None]\n\"12345\\n\"\n</code></pre>\n\n<p>So you don’t need to check for <code>length is None</code> explicitly: just set <code>val = self.line[:length]</code>. Then you could just trim <code>self.line</code> by the length of <code>val</code>. Something like:</p>\n\n\n\n<pre><code>def extract(self, length = None):\n val = self.line[:length]\n self.line = self.line[len(val):]\n return val\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:56:57.393", "Id": "79364", "Score": "0", "body": "Thanks for the review. `lowercase_underscores` will be painful for me, but I guess I'll have to adapt :-( The `noncomments` is just silly C&P. Regarding the `None` indexing: I didn't know that, great tip. But is it known well enough not to induce a \"wtf\" from someone reading the code? I wouldn't like to sacrifice clarity to tersity with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:30:35.277", "Id": "79438", "Score": "0", "body": "@Angew when you're using slice notation, you're calling the `__getitem__(self, key)` operator.. Key can either be an int, or a slice containing `key.start`, `key.stop` and `key.step`. If you use slice notation and leave any of them out they get sent as None. `if start is None: start = 0`, `if stop is None: stop = len(self)`, `if step is None: step = 1`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:17:36.220", "Id": "45494", "ParentId": "45484", "Score": "4" } } ]
{ "AcceptedAnswerId": "45494", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T11:34:52.753", "Id": "45484", "Score": "12", "Tags": [ "python", "parsing" ], "Title": "Processing C++ comments" }
45484
<blockquote> <p>You are given a polynomial of degree n. The polynomial is of the form</p> <blockquote> <p>P(x) = a<sub>n</sub> · x<sup>n</sup> + a<sub>n-1</sub> · x<sup>n-1</sup> + … + a<sub>0</sub></p> </blockquote> <p>where the <em>a<sub>i</sub></em>‘s are the coefficients. Given an integer <em>x</em>, write a program that will evaluate <em>P(x)</em>. </p> <p>You are provided with a function named <code>power( )</code> that takes two positive integers <em>x</em> and <em>y</em> and returns <em>x<sup>y</sup></em>. If <em>y</em> is 0, the function returns 1. </p> <p>The prototype of this function is</p> <pre><code>int power(int x, int y); </code></pre> <p><strong>INPUT:</strong></p> <ul> <li>Line 1 contains the integers <em>n</em> and <em>x</em> separated by whitespace. </li> <li>Line 2 contains the coefficients <em>a<sub>n</sub></em>, <em>a<sub>n-1</sub></em>, …, <em>a<sub>0</sub></em> separated by whitespace.</li> </ul> <p><strong>OUTPUT:</strong> </p> <p>A single integer which is <em>P(x)</em>.</p> <p><strong>CONSTRAINTS:</strong></p> <p>The inputs will satisfy the following properties. It is not necessary to validate the inputs.</p> <pre><code>1 &lt;= n &lt;= 10 1 &lt;= x &lt;= 10 0 &lt;= ai &lt;=10 </code></pre> </blockquote> <p>My code</p> <pre><code>#include&lt;stdio.h&gt; int power(int x, int y); int main() { int n,x,a[11],i; unsigned long long int sum=1; scanf("%d%d",&amp;n,&amp;x); if(n&lt;1 || n&gt;10) return 0; if(x&lt;1 || x&gt;10) return 0; for(i=0;i&lt;=n;i++) { scanf("%d",&amp;a[i]); if(a[i]&lt; 0 || a[i]&gt;10) return 0; } for(i=0;i&lt;n;i++) { sum+=power(x,n-i)*a[i]; } printf("%llu",sum); return 0; } int power(int x, int y) { int result = x,i; if(y == 0) return 1; if(x &lt; 0 || y &lt; 0) return 0; for(i = 1; i &lt; y; ++i) result *= x; return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:11:18.860", "Id": "79421", "Score": "5", "body": "Do you know about [Horner's method](http://en.wikipedia.org/wiki/Horner%27s_method)?" } ]
[ { "body": "<ol>\n<li><p>Recommend a uniform and more indented style. E.g.</p>\n\n<pre><code>for(i=0;i&lt;n;i++)\n{\n sum+=power(x,n-i)*a[i];\n}\n</code></pre></li>\n<li><p>Both <code>a[11]</code> and <code>if(... n&gt;10)</code> rely on the same value. Also to avoid undocumented magic numbers, consider the following (also the same for <code>x</code> and <code>a[]</code>):</p>\n\n<pre><code>#define n_MAX (10)\n#define n_MIN (0)\nint a[n_MAX + 1];\nif(n&lt;n_MIN || n&gt;n_MAX) return 0;\n</code></pre></li>\n<li><p><code>unsigned long long int sum</code> serves little value in protecting against numbers larger than <code>INT_MAX</code> as <code>power()</code> is the most likely candidate to overflow. (Strictly speaking, it is not even known that <code>LLONG_MAX</code> is greater than <code>INT_MAX</code>.) So if you want a larger range, re-write <code>power()</code> as <code>unsigned long long power(int x, int y)</code>, otherwise leaving <code>sum</code> as <code>int</code> is OK.</p>\n\n<p>Else suggest for marginal range improvement:</p>\n\n<pre><code>sum += (unsigned long long) power(x,n-i) * a[i];\n</code></pre></li>\n<li><p>BTW: should not it be:</p>\n\n<pre><code>unsigned long long int sum = 0; //( 0 not 1)\n</code></pre></li>\n<li><p>Note: Stated objective says \"It is not necessary to validate the inputs.\". Still I like the testing you have done. Possible that the final reviewer (teacher?) may object to unneeded code. <em>Could</em> wrap in an <code>#if DEBUG</code> macro...</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int\">Faster way to do <code>power()</code></a></p></li>\n<li><p>See no reason for <code>x&lt;0</code> test in <code>if(x &lt; 0 || y &lt; 0) return 0;</code>. Could be </p>\n\n<pre><code>if (y &lt; 0) return 0;\n</code></pre></li>\n<li><p>Do <code>power()</code> with <code>unsigned</code> rather than <code>int</code> as \" function named power( ) that takes two positive integers x and y\".</p></li>\n<li><p>@Constructor comment leads to an excellent suggestion. Calculate <code>sum</code> with a loop that does the below. No need for a power function. Running <code>sum</code> can be <code>unsigned long long</code> and code gets great range. Its faster &amp; simple.</p>\n\n<pre><code>// sum = (((a[n]*x + a[n-1])*x + a[n-2])*x + .... )*x + a[0];\n\n// Something like\nunsigned long long sum = 0;\nfor (int i=n; i&gt;=0; i--) {\n sum *= x;\n sum += a[i];\n}\n</code></pre></li>\n<li><p>Lastly, even the array <code>a</code> is not needed:</p>\n\n<pre><code>#include&lt;stdio.h&gt;\nint main() {\n int n;\n unsigned x, a;\n unsigned long long sum = 0;\n scanf(\"%d%u\", &amp;n, &amp;x);\n while (n-- &gt;= 0) {\n scanf(\"%u\", &amp;a);\n sum *= x;\n sum += a;\n }\n printf(\"%llu\", sum);\n return 0;\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:37:16.783", "Id": "45529", "ParentId": "45488", "Score": "4" } }, { "body": "<p>You can solve this problem without using a power function. However, you can optimize your POW(x,y) to O(logn) using Divide and conquer approach, </p>\n\n<blockquote>\n<pre><code> A^n = A^(n/2) * A^(n/2) if n is even\n = A^(n/2) * A^(n/2) * A if n is odd\n</code></pre>\n</blockquote>\n\n<pre><code>int power(int x, unsigned int y)\n{\n int temp;\n if( y == 0)\n return 1;\n temp = power(x, y/2);\n if (y%2 == 0)\n return temp*temp;\n else\n return x*temp*temp;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:07:56.073", "Id": "45545", "ParentId": "45488", "Score": "2" } }, { "body": "<p>A few suggestions:</p>\n\n<ul>\n<li>Whitespace (formatting) makes the code more readable: be especially careful with indentation; and don't waste vertical space with too many empty lines because you want to see the whole function on your limited-size screen)</li>\n<li>Don't declare variables before you assign a value to them. Declaring all your variables at the top of the function was necessary in old-style C but is <a href=\"https://stackoverflow.com/a/2321622/49942\">no longer required</a>.</li>\n<li>You don't need the <code>a[11]</code> array.</li>\n<li>You don't need to write the <code>power</code> function because the specifications say, \"<strong>You are provided with</strong> a function ...\"</li>\n<li>You don't need to validate your input (normally you should; but the specifications which you quoted for this problem say that you needn't: and you should usually read and obey the specifications).</li>\n<li>The biggest possible value of x<sup>n</sup> is 10<sup>10</sup> for which you'll need a more-than-32-bit integer:\n\n<ul>\n<li>Is this is a trick question, or an mistake by whoever wrote the specs?</li>\n<li>Is the <code>power</code> function (which returns <code>int</code>) implicitly working with 64-bit integers?</li>\n<li>Do you need to define your own version of the <code>power</code> function using <code>int64_t</code>?</li>\n</ul></li>\n<li>If you want to declare an explicitly-64-bit integer it's called <a href=\"https://stackoverflow.com/a/6013417/49942\"><code>int64_t</code></a>.</li>\n</ul>\n\n<p>If your compiler doesn't support 64-bit arithmetic you can implement it yourself but that makes the code a bit more complicated.</p>\n\n<p>The following is FYI my attempt to do this problem in minimum/cleanest lines of code:</p>\n\n<pre><code>int main()\n{\n // Line 1 contains the integers n and x separated by whitespace.\n int n, x;\n scanf(\"%d%d\", &amp;n, &amp;x);\n\n int64_t sum = 0;\n for (int i = 0; i &lt;= n; ++i) {\n // Line 2 contains the coefficients an, an-1, ..., a0 separated by whitespace.\n int a;\n scanf(\"%d\", &amp;a);\n sum += a * power(x, n - i);\n }\n\n // Use PRId64 defined in &lt;inttypes.h&gt; to print int64_t\n // https://stackoverflow.com/a/9225648/49942\n printf(\"%\" PRId64, sum);\n return 0;\n}\n</code></pre>\n\n<p>You may agree that my version is more readable than yours; partly because it's shorter.</p>\n\n<p>I added comments which <a href=\"https://stackoverflow.com/a/400436/49942\">describe the problem being solved</a> (by copying them from the specification).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:39:49.037", "Id": "45552", "ParentId": "45488", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:13:46.277", "Id": "45488", "Score": "6", "Tags": [ "c", "mathematics" ], "Title": "Evaluating a polynomial" }
45488
<p>I'm the maintainer of the following library on github: <a href="https://github.com/edi9999/docxtemplater/blob/master/coffee/docxgen.coffee" rel="nofollow">https://github.com/edi9999/docxtemplater/blob/master/coffee/docxgen.coffee</a></p> <p>I want to maintain a library that works on node and in the browser, however I don't want to have to update two separate repositories.</p> <p>The ugliest code looks like this:</p> <pre><code>root= global ? window env= if global? then 'node' else 'browser' if env=='node' global.http= require('http') global.https= require('https') global.fs= require('fs') global.vm = require('vm') global.DOMParser = require('xmldom').DOMParser global.XMLSerializer= require('xmldom').XMLSerializer global.PNG= require('../vendor/pngjs/png-node') global.url= require('url') ["grid.js","version.js","detector.js","formatinf.js","errorlevel.js","bitmat.js","datablock.js","bmparser.js","datamask.js","rsdecoder.js","gf256poly.js","gf256.js","decoder.js","qrcode.js","findpat.js","alignpat.js","databr.js"].forEach (file) -&gt; vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jsqrcode/' + file), file) ['jszip.js'].forEach (file) -&gt; vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jszip2.0/dist/' + file), file) output: (options={}) -&gt; if !options.download? then options.download=true if !options.name? then options.name="output.docx" if !options.type? then options.type="base64" result= @zip.generate({type:options.type}) if options.download if env=='node' fs.writeFile process.cwd()+'/'+options.name, result, 'base64', (err) -&gt; if err then throw err else #Be aware that data-uri doesn't work for too big files: More Info http://stackoverflow.com/questions/17082286/getting-max-data-uri-size-in-javascript document.location.href= "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,#{result}" result </code></pre> <p>As you can see, they is a lot of specific node/browser js code, and I would like to remove that from the main code, however, I can't find an easy way to do this.</p> <p>Any idea ?</p>
[]
[ { "body": "<p>Yeah..</p>\n\n<p>Are you against maintaining 2 repositories or maintaining 2 main files? Honestly I would have 2 main files with a third file ( or more ) containing routines that are host agnostic.</p>\n\n<p><code>docxgen_node.coffee</code> , <code>docxgen_www.coffee</code> and <code>docxgen_common.coffee</code></p>\n\n<p>It sounds uncool, but I think in the end, this should be easiest on the eyes.</p>\n\n<p>Other, than that, I would take the opportunity to use that massive ( ugly ) string array to document why you need each library and maybe which versions are usable for your repository:</p>\n\n<pre><code>var requiredLibraries = [\n \"grid.js\", //Use xyz version, uses abc features\n \"version.js\", //...\n \"detector.js\", //..\n ...\n]\n\nrequiredLibraries.forEach (file) -&gt;\n vm.runInThisContext(global.fs.readFileSync(__dirname + '/../vendor/jsqrcode/' + file), file)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:24:42.733", "Id": "79380", "Score": "0", "body": "Maintaning two specific files and one host agnostic is ok I think" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:16:39.013", "Id": "45513", "ParentId": "45491", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:44:22.463", "Id": "45491", "Score": "1", "Tags": [ "node.js", "coffeescript" ], "Title": "Remove nodejs/browser specific code in library" }
45491
<p>I have always suffered with too many conditionals in some of my methods. The following is a pseudocode/skeleton of one of my method like that:</p> <pre><code>private List&lt;ReturnType&gt; DoSth(string name = null) { List&lt;ReturnType&gt; names = new List&lt;ReturnType&gt;(); for (int i = 0; i &lt; somearray.Length; i++) { if (somecondition) { if (name == null) { //'Add' to list } else { if (someothercondition) { //'Add' to list } } } } return names; } </code></pre> <p>Actual Code which returns an object filled with Controller and corresponding Action names:</p> <pre><code>private List&lt;AppController&gt; GetControllerActions(string ControllerName = null) { Type[] typelist = Assembly.GetExecutingAssembly().GetTypes().Where(t =&gt; String.Equals(t.Namespace, "Project.Web.Controllers", StringComparison.Ordinal)).ToArray(); List&lt;AppController&gt; names = new List&lt;AppController&gt;(); for (int i = 0; i &lt; typelist.Length; i++) { if (typelist[i].BaseType.Name == "Controller") { if (ControllerName == null) { names.Add(new AppController { ControllerName = typelist[i].Name, ActionName = typelist[i].GetMethods() .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult")) .Select(s =&gt; s.Name).ToList() }); } else { if (typelist[i].Name == ControllerName) { names.Add(new AppController { ControllerName = typelist[i].Name, ActionName = typelist[i].GetMethods() .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == "ActionResult" || w.ReturnType.Name == "ActionResult")) .Select(s =&gt; s.Name).ToList() }); } } } } return names; } </code></pre> <p>As you can see the same <code>Add</code> code is being repeated twice and the 'Add' code is not an external method and I would prefer not making it one also. I can also provide the actual code if required.</p> <p><em>Is there any scope of making this code more concise and compact like you can do with ternary operators for example?</em></p>
[]
[ { "body": "<p>You could just combine the logic into one statement, assuming there is not other things occurring during your if-else blocks and stuff.\nIf there is, then this won't necessarily work for you, and you should post the real code, because a lot of times these problems are subjective to the code. </p>\n\n<p>I guess one lesson to possibly learn from this is just to realize the end result, and build a condition that matches the necessary conditions to do something.</p>\n\n<pre><code>if (somecondition &amp;&amp; (name == null || someothercondition))\n{\n //'Add' to list\n}\n</code></pre>\n\n<p><strong>Edit</strong>: To expand upon the OPs full code being posted.</p>\n\n<p>My original answer is still valid you would write it like this:</p>\n\n<pre><code>for (int i = 0; i &lt; typelist.Length; i++)\n{\n if (typelist[i].BaseType.Name == \"Controller\" &amp;&amp; (ControllerName == null || typelist[i].Name == ControllerName))\n names.Add(new AppController\n {\n ControllerName = typelist[i].Name,\n ActionName = typelist[i].GetMethods()\n .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\"))\n .Select(s =&gt; s.Name).ToList()\n }); \n}\n</code></pre>\n\n<p>However, now that you have actual code to review, I will also point out that there is no reason to be using a <code>for</code> loop vs a <code>foreach</code> loop. I would write that as follows.</p>\n\n<pre><code>foreach (var t in typelist)\n{\n if (t.BaseType.Name == \"Controller\" &amp;&amp; (ControllerName == null || t.Name == ControllerName))\n names.Add(new AppController\n {\n ControllerName = t.Name,\n ActionName = t.GetMethods()\n .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\"))\n .Select(s =&gt; s.Name).ToList()\n }); \n}\n</code></pre>\n\n<p>At this point I am recognizing that we are iterating through a list, and conditionally doing one thing. This appears to be the perfect candidate for using some linq.</p>\n\n<p>using Where and some lambda we can make this statement to return an <code>IEnumerable&lt;Type&gt;</code> which only contains Types we need to add.</p>\n\n<pre><code>typelist.Where(t =&gt; t.BaseType.Name == \"Controller\" &amp;&amp; (ControllerName == null || t.Name == ControllerName))\n</code></pre>\n\n<p>On our newly created <code>IEnumerable&lt;Type&gt;</code> we can Select what we want to add to the names list.</p>\n\n<pre><code>.Select(t =&gt; new AppController\n{\n ControllerName = t.Name,\n ActionName = t.GetMethods()\n .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\"))\n .Select(s =&gt; s.Name).ToList()\n});\n</code></pre>\n\n<p>Now if this was a time where names was an existing list we only needed to append to we could use <code>names.AddRange()</code> but because this list was created here for this purpose (I think).\nwe can just ToList() our results and save them as the list.</p>\n\n<p>At this point you could have a few different variables, or you could make your code look awesome and confusing and one-line it all. because I see now that typelist is only being referenced once. (Btw it should probably named typeList, with a capital L, but we're getting rid of it anyway). </p>\n\n<p>So in the very end you can have this beautiful chunk of code. Note: I am also going to use <code>string.IsNullOrWhiteSpace</code> instead of just checking if it is null.</p>\n\n<pre><code>private List&lt;AppController&gt; GetControllerActions(string ControllerName = null)\n{\n return\n System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t =&gt; String.Equals(t.Namespace, \"Project.Web.Controllers\", StringComparison.Ordinal))\n .Where(t =&gt; t.BaseType.Name == \"Controller\" &amp;&amp; (string.IsNullOrWhiteSpace(ControllerName) || t.Name == ControllerName))\n .Select(t =&gt; new AppController\n {\n ControllerName = t.Name,\n ActionName = t.GetMethods()\n .Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\"))\n .Select(s =&gt; s.Name).ToList()\n })\n .ToList();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:04:50.103", "Id": "79353", "Score": "0", "body": "Thanks for your comment. I have posted the actual code above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:06:43.967", "Id": "79355", "Score": "0", "body": "@Md.lbrahim with your updated code it looks like my answer still stands as valid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:46:19.173", "Id": "79359", "Score": "1", "body": "@Md.lbrahim I have updated my post again to use linq and one-line the entire method" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:00:07.827", "Id": "45493", "ParentId": "45492", "Score": "11" } }, { "body": "<p>As far as I can guess you are trying to test whether some method returns a subclass of <code>System.Web.Mvc.ActionResult</code> repeated snippet here:</p>\n\n<pre><code>w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\")\n</code></pre>\n\n<p>But this snippet fails in three cases:</p>\n\n<ol>\n<li><p>If a class inherits from a <code>ActionResult</code> indirectly. e.g. </p>\n\n<pre><code>class Y: System.Web.Mvc.ActionResult {}\nclass X: Y {}\ntypeof(X).BaseType.Name != \"ActionResult\"\n</code></pre></li>\n<li><p>If a class is not a subclass of <code>System.Web.Mvc.ActionResult</code> but happens to be named <code>ActionResult</code> e.g. <code>Some.Unrelated.Name.Space.ActionResult</code>. e.g. </p>\n\n<pre><code>var t1 = typeof(Some.Unrelated.Name.Space.ActionResult);\nvar t2 = typeof(System.Web.Mvc.ActionResult);\nt1.Name == t2.Name;\nt1 != t2;\n</code></pre></li>\n<li><p>If a class is not a subclass of <code>System.Web.Mvc.ActionResult</code> but happens to directly inherit from a class named <code>ActionResult</code> e.g. </p>\n\n<pre><code>class X:Some.Unrelated.Name.Space.ActionResult {}\ntypeof(X).BaseType.Name == \"ActionResult\"\n// but \ntypeof(X).BaseType != typeof(System.Web.Mvc.ActionResult)\n</code></pre></li>\n</ol>\n\n<p>What you actually want is <a href=\"http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx\"><code>Type.IsAssignable</code></a>. So:</p>\n\n<pre><code>.Where(w =&gt; w.ReturnType.BaseType != null &amp;&amp; (w.ReturnType.BaseType.Name == \"ActionResult\" || w.ReturnType.Name == \"ActionResult\")) \n</code></pre>\n\n<p>should become:</p>\n\n<pre><code>.Where(method =&gt; typeof(System.Web.Mvc.ActionResult).IsAssignable(method.ReturnType)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:20:17.707", "Id": "79526", "Score": "0", "body": "Thanks for your insight. Actually I was trying to detect only methods with return type as `ActionResult` or any type **directly** inheriting from `ActionResult`. Your point no. 2 and 3 is definitely correct in my case though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:13:30.677", "Id": "45500", "ParentId": "45492", "Score": "6" } } ]
{ "AcceptedAnswerId": "45493", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T12:54:47.303", "Id": "45492", "Score": "7", "Tags": [ "c#", "asp.net-mvc" ], "Title": "Refactoring Methods With Conditionals" }
45492
<p>I've got a Python script which is meant to launch several other shell scripts with the appropriate setup and parameters. I construct the file paths from other variables so that it's easier to change one setting and have it apply everywhere, rather than hardcoding everything.</p> <p>So, for example:</p> <pre><code>HOME_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) ONHAND_ACC_NAME = 'onhand_accuracy' SHRINK_NAME = 'shrink' SHELL_SCRIPT_EXTENSION = '.ksh' CONFIG_FILE_EXTENSION = '.conf' ONHAND_ACC_SHELL_SCRIPT = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + SHELL_SCRIPT_EXTENSION SHRINK_SHELL_SCRIPT = HOME_DIRECTORY + '/' + SHRINK_NAME + SHELL_SCRIPT_EXTENSION ONHAND_ACC_CONFIG_FILE = HOME_DIRECTORY + '/' + ONHAND_ACC_NAME + CONFIG_FILE_EXTENSION SHRINK_CONFIG_FILE = HOME_DIRECTORY + '/' + SHRINK_NAME + CONFIG_FILE_EXTENSION </code></pre> <p>These are all constants defined at the top of the script. (Feel free to tell me a more Pythonic way to do this than constants, as well. I've heard before that "Python should have no constants at all", though I'm not sure how accurate or purist that is.)</p> <p>In Java, I would do something much cleaner, like use an <code>enum</code> to generate appropriate file paths as needed:</p> <pre><code>public enum FileType { SHELL_SCRIPT (".ksh"), CONFIGURATION (".conf"); private static final String HOME_DIRECTORY = "/path/to/scripts"; private static final String FILE_SEPARATOR = FileSystems.getDefault().getSeparator(); private final String extension; private FileType(String extension) { this.extension = extension; } public String getFilePath(String name) { return HOME_DIRECTORY + FILE_SEPARATOR + name + extension; } } </code></pre> <p>Then I could simply invoke this whenever I wanted to and get a file path, rather than hardcoding them as constants, like so:</p> <pre><code>FileType.SHELL_SCRIPT.getFilePath("onhand_accuracy"); </code></pre> <p>Any similar tips on how I can improve this practice/technique in Python? I know I could have a similar function in Python that uses a lot of <code>if/elif</code> on a <code>string</code> input, but that still seems much dirtier than an <code>enum</code>, since the calling code can pass in whatever it wants for that <code>string</code>.</p> <p>(In the Java, I would probably also have an <code>enum</code> for the associated <code>Script</code>, but that would clutter up my example.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:54:04.060", "Id": "79362", "Score": "4", "body": "Probably not worth an answer but maybe you should use http://docs.python.org/3/library/os.path.html#os.path.join" } ]
[ { "body": "<p>You could make a module with two global variables and a class\nthe globals starting as:</p>\n\n<pre><code>HOME_DIRECTORY = None\nEXTENSIONS = dict(\n SHELL_SCRIPT = '.ksh',\n CONFIG_FILE = '.conf',\n STORE_FILE = '.someextension'\n)\n</code></pre>\n\n<p>And a class that has one static method to set the home directory</p>\n\n<p>If you make a class and there is no set home directory you get an error.\nYou also get an error if the file type is unknown</p>\n\n<pre><code>class CustomPath(object):\n __file_name = str()\n __file_type = str()\n file_name = str()\n file_type = str()\n file_extension = str()\n def __init__(self, file_name, file_type):\n if HOME_DIRECTORY is None:\n raise Exception(\"Please set the Home Directory\")\n self.file_name = self.__file_name = file_name\n if not file_type in EXTENSIONS.keys():\n raise Exception(\"Unsupported file type\")\n self.file_type = self.__file_type = file_type\n self.file_extension = EXTENSIONS[self.__file_type]\n\n def __repr__(self):\n return HOME_DIRECTORY + '/' + self.__file_name + EXTENSIONS[self.__file_type]\n def __str__(self):\n return self.__repr__()\n @staticmethod\n def SetHomeDirectory( new_path):\n global HOME_DIRECTORY\n HOME_DIRECTORY = new_path\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>&gt;&gt;&gt; CustomPath.SetHomeDirectory(\"C/scripts\")\n&gt;&gt;&gt; my_file = CustomPath(\"script_a\",\"SHELL_SCRIPT\")\n&gt;&gt;&gt; my_file\nC/scripts/script_a.ksh\n&gt;&gt;&gt; str(my_file)\n'C/scripts/script_a.ksh'\n&gt;&gt;&gt; my_file.file_name\n'script_a'\n&gt;&gt;&gt; my_file.file_type\n'SHELL_SCRIPT'\n&gt;&gt;&gt; my_file.file_extension\n'.ksh'\n&gt;&gt;&gt; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:57:05.123", "Id": "45508", "ParentId": "45495", "Score": "3" } }, { "body": "<p>For something similar to your Java solution, you could have this in <code>filetype.py</code>:</p>\n\n<pre><code>import os.path\n\nclass FileType(object):\n HOME_DIRECTORY = \"/path/to/scripts\"\n\n def __init__(self, extension):\n self.extension = extension\n\n def file_path(self, name):\n return os.path.join(self.HOME_DIRECTORY, name + self.extension)\n\nSHELL_SCRIPT = FileType(\".ksh\")\nCONFIGURATION = FileType(\".conf\")\n</code></pre>\n\n<p>Then the usage would be</p>\n\n<pre><code>import filetype\nfiletype.SHELL_SCRIPT.file_path(\"onhand_accuracy\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:54:33.410", "Id": "79420", "Score": "0", "body": "That's awesome. Is this a \"Pythonic\" way to do it, though, or just an analogy to my Java implementation? I like it, either way, but I'd like to also learn how a normal/expert Python developer would go about tackling the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:24:42.420", "Id": "79437", "Score": "0", "body": "@JeffGohlke You didn't give much context in your question. I would probably start by using `os.path.join` where the path is needed, and if I find repeating myself, look for the proper place to store it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:11:58.910", "Id": "45512", "ParentId": "45495", "Score": "5" } } ]
{ "AcceptedAnswerId": "45512", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:32:01.853", "Id": "45495", "Score": "7", "Tags": [ "python", "python-3.x", "constants" ], "Title": "Dynamically generating Strings (or other variables)" }
45495
<p>I was asked the following interview question over the phone:</p> <blockquote> <p>Given an array of integers, produce an array whose values are the product of every other integer excluding the current index.</p> <p>Example: </p> <pre><code>[4, 3, 2, 8] -&gt; [3*2*8, 4*2*8, 4*3*8, 4*3*2] -&gt; [48, 64, 96, 24] </code></pre> </blockquote> <p>and I gave the following answer</p> <pre><code>import java.math.BigInteger; import java.util.Arrays; public class ProductOfAnArray { public static void main(String[] args) { try { System.out.println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4, 3, 2, 8 }))); System.out.println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4, 0, 2, 8 }))); System.out.println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4, 0, 2, 0 }))); System.out.println(Arrays.toString(ProductOfAnArray .calcArray(new int[] {}))); System.out .println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4 }))); System.out .println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4 }))); System.out.println(Arrays.toString(ProductOfAnArray .calcArray(new int[] { 4432432, 23423423, 34234, 23423428, 4324243, 24232, 2342344, 64234234, 4324247, 4234233, 234422, 234244 }))); } catch (Exception e) { // debug exception here and log. } } /* * Problem: Given an array of integers, produce an array whose values are * the product of every other integer excluding the current index. * * Assumptions. Input array cannot be modified. input is an integer array * "produce an array" - type not specified for output array * * Logic explanation: * * Assume we have array [a,b,c,d] Let multiple be multiple of each element * in array. Hence multiple = 0 if one of the element is 0; To produce the * output. Ans at i -&gt; multiple divided by the value at i. if 2 numbers are * 0 then entire output will be 0 because atleast one 0 will be a multiple * if 1 number is 0 then every thing else will be 0 except that index whole * value is to be determined * */ public static BigInteger[] calcArray(final int[] inp) throws Exception { if (inp == null) throw new Exception("input is null"); int cnt = 0; BigInteger multiple = new BigInteger("1"); boolean foundZero = false; for (int i : inp) { if (i == 0) { cnt++; foundZero = true; if (cnt &lt; 2) continue; else break; } multiple = multiple.multiply(BigInteger.valueOf(i)); } BigInteger ans[] = new BigInteger[inp.length]; for (int i = 0; i &lt; inp.length; i++) { if (foundZero) { if (cnt &lt; 2) { ans[i] = (inp[i] == 0) ? multiple : new BigInteger("0"); } else { ans[i] = new BigInteger("0"); } } else { ans[i] = multiple.divide(BigInteger.valueOf(inp[i])); } } return ans; } } </code></pre> <p>But I was not selected. I would like to get feedback on my answer and see what's wrong.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:33:26.080", "Id": "79406", "Score": "0", "body": "Thanks everyone for your feedback. I will take all this into account the next time I write any code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:13:43.777", "Id": "79443", "Score": "3", "body": "here's a hint for the algorithm itself: the result on index i is `product of all elements/inp[i]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:15:54.297", "Id": "79453", "Score": "0", "body": "Seems like the question was too easy, if they don't have time to interview everyone who did at least this good then better make something harder and get some meaty quality difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:21:12.930", "Id": "79456", "Score": "0", "body": "When you are asked Interview over the phone and you give them code, that isn't what they are looking for. they want you to explain what you would do, in English." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:36:54.550", "Id": "79503", "Score": "0", "body": "bad algorithm, the better way is to multiply all number in array, then divide the number in current index to calculate the result. This is a algorithm question, and I don't think the interviewer will really focus on your coding style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:21:55.527", "Id": "79521", "Score": "0", "body": "@zdd did u read my program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:22:11.330", "Id": "79522", "Score": "0", "body": "@ratchetfreak did u read my program>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:50:20.043", "Id": "79524", "Score": "0", "body": "@footy, I apologies, and I didn't realize the fact that some numbers might be zero, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:05:41.290", "Id": "79618", "Score": "0", "body": "@zdd no problem." } ]
[ { "body": "<p>Honestly..... that looks good.</p>\n\n<p>it is pretty much what I would have done. It is <em>O(n)</em> which is smarter than the naive <em>O(n<sup>2</sup>)</em> solution of nested loops, it manages overflow well with the BigInteger... it is good.</p>\n\n<p>The only concern is that the interviewer may have expected an <code>int[]</code> return type, and the assumption that overflow won't happen.</p>\n\n<p>If it were me, I would have probably done an <code>int[]</code> solution and qualified the result with: </p>\n\n<blockquote>\n <p>you know this is at risk of overflow, and depending on the real-world requirements I would code it with <code>BigInteger</code> if needed.</p>\n</blockquote>\n\n<p>Still, I imagine there is some other reason you didn't get the job.... not this code.... and, if it was the code, then you may not want to work there anyway ;-)</p>\n\n<p>All the best.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:25:38.767", "Id": "45502", "ParentId": "45498", "Score": "6" } }, { "body": "<p>For starters, you have very weird line breaks:</p>\n\n<pre><code>System.out\n .println(Arrays.toString(ProductOfAnArray\n .calcArray(new int[] { 4, 3, 2, 8, 3, 2, 4, 6, 7,\n 3, 2, 4 })));\n</code></pre>\n\n<p>That's not layout, that's obfuscation! When dealing with long method chains, it may be preferable to break before each method invocation:</p>\n\n<pre><code>someObject\n .thisIs()\n .aFluid()\n .interface();\n</code></pre>\n\n<p>but that's not the case here, and this layout does not increase readability. Instead, break after the opening paren of the argument list:</p>\n\n<pre><code>System.out.println(\n Arrays.toString(ProductOfAnArray.calcArray(new int[] {\n 4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4\n }))\n);\n</code></pre>\n\n<p>or something like that. Note that you could have written this as</p>\n\n<pre><code>System.out.println(\n Arrays.toString(ProductOfAnArray.calcArray(\n 4, 3, 2, 8, 3, 2, 4, 6, 7, 3, 2, 4\n ))\n);\n</code></pre>\n\n<p>(i.e. without the explicit array) when declaring your function with varargs: <code>calcArray(int... inp)</code>.</p>\n\n<p>The next question is why you are returning an array – a <code>List&lt;BigInteger&gt;</code> would be more flexible – arrays have little use in modern Java (the usage of varargs implies arrays, and high-performance code may need them. But in all other cases, they are too inflexible – e.g. arrays and generics don't work together).</p>\n\n<p>But why <code>BigInteger</code>? Yes, you don't want to overflow, but we can assume that your interviewers would be content with an <code>int</code>. If you want to allow larger numbers, the first step would be <code>long</code>. Big Integers are truly awkward to use and necessarily less performant that native types, so I would avoid them wherever possible.</p>\n\n<p>Your code inside <code>calcArray</code> is unnecessarily clever. Let's look at this loop:</p>\n\n<pre><code>for (int i : inp) {\n if (i == 0) {\n cnt++;\n foundZero = true;\n if (cnt &lt; 2)\n continue;\n else\n break;\n }\n multiple = multiple.multiply(BigInteger.valueOf(i));\n}\n</code></pre>\n\n<p>Notice that <code>foundZero</code> is equivalent to <code>cnt &gt; 0</code>, and that you aren't using braces around the bodies of the inner <code>if/else</code>. Your <code>continue</code> is rather confusing, and the following expresses the control flow much better:</p>\n\n<pre><code>for (int i : inp) {\n if (i != 0) {\n multiple = multiple.multiply(BigInteger.valueOf(i));\n }\n else {\n cnt++;\n if (cnt &gt;= 2) {\n break;\n }\n }\n}\n</code></pre>\n\n<p>This conditional in the next loop is also too complex, and could be simplified to</p>\n\n<pre><code>if (cnt &lt; 2 &amp;&amp; inp[i] == 0) {\n ans[i] = multiple;\n} else {\n ans[i] = new BigInteger(\"0\");\n}\n</code></pre>\n\n<p>When applying these criticisms, the Simplest Thing That Could Work might be this:</p>\n\n<pre><code>public static List&lt;Long&gt; specialProduct(int... numbers) {\n long product = 1;\n int zeroesCount = 0;\n for (int n : numbers) {\n if (n != 0) {\n product *= n;\n }\n else {\n zeroesCount++;\n }\n }\n\n List&lt;Long&gt; output = new ArrayList&lt;&gt;(numbers.length);\n\n switch (zeroesCount) {\n case 0:\n // with no zeroes, we don't have to perform any checks\n for (int n : numbers) {\n output.add(product / n);\n }\n break;\n case 1:\n // with one zero, the all others will become zero too\n for (int n : numbers) {\n if (n == 0) {\n output.add(product);\n }\n else {\n output.add(0L);\n }\n }\n break;\n default:\n // two or more zeroes make everything zero\n for (int i = 0; i &lt; numbers.length; i++) {\n output.add(0L);\n }\n break;\n }\n\n return output;\n}\n</code></pre>\n\n<p>Oh, and naming! Have vocals become so precious that we must write <code>cnt</code> instead of <code>count</code>? Must we write <code>ans</code> instead of <code>answer</code> if you can actually write a long word like <code>multiple</code>? And what the heck is <code>inp</code>?</p>\n\n<p>Your code is not <em>bad</em>, but it isn't good, and could certainly have been written better. The next time, maybe :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:25:18.043", "Id": "79381", "Score": "1", "body": "I agree that the special treatment of zero is unnecessary and I like the general idea to compute the total product first and then factor out the current input, but your simplified solution yields zero for all elements if at least one zero in the input, e.g., [0,1,2,3] -> [0,0,0,0], but the correct result should be [6,0,0,0]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:31:05.530", "Id": "79382", "Score": "0", "body": "Maybe I misunderstand the original problem, but after reading the OP solution, I think it contains the same error, which might very well be a reason why it was rejected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:41:12.777", "Id": "79389", "Score": "2", "body": "@SimonLehmann You should maybe post that as an answer: because it may be the most important reason why the solution was rejected, i.e. \"incorrect output\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:47:53.617", "Id": "79390", "Score": "2", "body": "@ChrisW: The OP's code returns `[6,0,0,0]` for `[0,1,2,3]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:48:40.200", "Id": "79392", "Score": "2", "body": "Well, ok, I should have probably taken more time to read that code (and actually try it). The OP's programm does NOT have this error, as it uses a continue in the loop where the total product is calculated whenever it encounters a zero. Now I guess, the real reason why it was rejected might be that it is to complicated..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:33:04.063", "Id": "45504", "ParentId": "45498", "Score": "17" } }, { "body": "<p>As @rolfl said your code look good to me too. I just wanted to add some very very minor notes about your code. </p>\n\n<p><strong>Style</strong></p>\n\n<blockquote>\n<pre><code>if (inp == null)\n throw new Exception(\"input is null\");\n</code></pre>\n</blockquote>\n\n<p>This particular way of formatting <code>if</code> could be seen as a problem. Not using brackets for an single line can sometimes be seen as something bad. It's really a minor point that should not influence the outcome for a job interview, but if they are very very fanatic, it could have an influence. </p>\n\n<p><strong>Tests</strong></p>\n\n<p>Your main looks like a bunch of tests to me. I don't know the time you had to produce the code, but do know that test are important for a lot of companies. You could transform those homemade \"tests\" into a full suite of JUnit tests. I think that could give you an edge over other candidates. It would help show what you understand of the requirements and predict how your code should behave. It can help understand why are you doing certain things the way you did. </p>\n\n<p><strong>Constant</strong></p>\n\n<p>Other minor point, you should use constant when they are available. </p>\n\n<blockquote>\n<pre><code>BigInteger multiple = new BigInteger(\"1\");\nnew BigInteger(\"0\");\n</code></pre>\n</blockquote>\n\n<p>should be </p>\n\n<blockquote>\n<pre><code>BigInteger multiple = BigInteger.ONE;\nBigInteger.ZERO;\n</code></pre>\n</blockquote>\n\n<p>There will be less <code>new</code> in your code, so it could help if the function is called a lot!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T14:42:39.473", "Id": "45507", "ParentId": "45498", "Score": "8" } }, { "body": "<p>What <a href=\"https://codereview.stackexchange.com/a/45502/34757\">rolfl's answer</a> called \"the naive O(n<sup>2</sup>) solution of nested loops\" might be better:</p>\n\n<ul>\n<li>It's slower, but that doesn't matter for small/infrequent arrays</li>\n<li>If your solution had used <code>int</code> instead of <code>BigInteger</code> then the naive solution would have handled slightly more/bigger input numbers, which is a slight bonus (and, deciding to use BigInteger because you haven't clarified how big the input might be will have performance consequences of its own)</li>\n<li>It's more obvious (mapping from problem to solution) and easier to read (because it's more obvious), which might be more important than being optimized for speed</li>\n</ul>\n\n<p>During the phone interview, did you ask questions like:</p>\n\n<ul>\n<li>Are the arrays very long?</li>\n<li>Should I optimize for maximum speed, or for minimum memory, or for maximum readability?</li>\n</ul>\n\n<p>Asking questions may be part of an interview process: \"Does the candidate ask questions to clarify ambiguous requirements before coding?\"</p>\n\n<p>I didn't find it easy to verify by inspection whether your <code>calcArray</code> is correct. Maybe I'm not as clever as you.</p>\n\n<hr>\n\n<p>The code in your <code>main</code> has a lot of repeated <code>System.out.println(Arrays.toString(ProductOfAnArray.calcArray</code> statements.</p>\n\n<p>Instead it might be better to have a collection of input arrays, which you iterate (passing each in turn to calcArray).</p>\n\n<p>Even better if the test data is a collection of input arrays <strong>and expected output</strong> so that the code can assert whether actual output matches expected output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:12:03.777", "Id": "79378", "Score": "0", "body": "Agree with everything you say, except *\"It's correct in a wider range of conditions (less likely to overflow), which might be important\"* ... that implies that being wrong `X` times is bad, but `X-1` times is OK..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:34:52.367", "Id": "79384", "Score": "2", "body": "+1 asking questions for the requirements is very important! It prove that you're trying to understand what you're doing and do not take details for granted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:20:59.383", "Id": "79405", "Score": "0", "body": "@ChrisW I did ask to the interviewer those questions. He said you can assume anything. He just wanted me to start writing code and not do any talking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:15:48.797", "Id": "79452", "Score": "0", "body": "it is possible to build a O(n) solution that handles big numbers just as well as the O(n^2) solution, it's just the OP didn't do it. Calculate out[0] as product(in[1..n]), then out[n] = out[n-1] / in[n] * in[n-1]. This way you never hold the product of the entire array, which is the main performance concern in OP's solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:29:19.950", "Id": "79703", "Score": "0", "body": "@RedAlert This won't work when there is exactly one zero in the input at any other position than the first, e.g. in = [1,0,2,3] -> out[0] = 0 * 2 * 3 = 0, out[1] = 0 / 0 * 1 = NaN, out[2] = NaN / 2 * 0 = NaN, out[3] = NaN / 3 * 2 = NaN. Even if you check for division by zero, you would incorrectly set out[1] = 0! And saying \"you never hold the product of the entire array\" when in fact you hold the product of the entire array but the first element is kind of a strange, especially as a \"performance\" argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T22:18:40.410", "Id": "79904", "Score": "0", "body": "@SimonLehmann Obviously, the OP would have to incorporate the zero checks he has in his current code - my comment was a general algorithm, not a complete implementation. I'm not really sure what you mean by \"strange\", since I was just responding to ChrisW's second bullet." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:01:33.517", "Id": "45509", "ParentId": "45498", "Score": "11" } }, { "body": "<ol>\n<li><p>It might not because of the code. Maybe you were unlucky and there was a better candidate or a candidate with more experience in their industry.</p></li>\n<li><p>If it's not a bottleneck in an application (or a library function) don't do <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimization</a>. The naive solution is much easier to understand, faster to develop and <strong>easier to maintain</strong> since it's not so complex:</p>\n\n<pre><code>public static BigInteger[] calcArray2(int[] input) throws Exception {\n if (input == null) {\n throw new NullPointerException(\"input is null\");\n }\n\n BigInteger result[] = new BigInteger[input.length];\n for (int i = 0; i &lt; input.length; i++) {\n result[i] = calculateProductExcept(input, i);\n }\n return result;\n}\n\nprivate static BigInteger calculateProductExcept(int[] input, int exceptIndex) {\n BigInteger result = BigInteger.ONE;\n for (int i = 0; i &lt; input.length; i++) {\n if (i == exceptIndex) {\n continue;\n }\n result = result.multiply(BigInteger.valueOf(input[i]));\n }\n return result;\n}\n</code></pre>\n\n<p>Anyway, is <code>n</code> division faster than <code>n*n</code> multiplications?</p>\n\n<p>More or less related: <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>, <em>Simplicity -- the art of maximizing the amount of work not done -- is essential</em> from the <a href=\"http://agilemanifesto.org/principles.html\" rel=\"nofollow noreferrer\">Agile Manifesto</a></p></li>\n<li><p>You have a lot of copy pasted code here:</p>\n\n<blockquote>\n<pre><code>System.out.println(Arrays.toString(ProductOfAnArray\n .calcArray(new int[] { 4, 3, 2, 8 })));\nSystem.out.println(Arrays.toString(ProductOfAnArray\n .calcArray(new int[] { 4, 0, 2, 8 })));\n</code></pre>\n</blockquote>\n\n<p>You could extract out a method:</p>\n\n<pre><code>private static void printProductOfArray(int... input) throws Exception {\n System.out.println(Arrays.toString(ProductOfAnArray.calcArray(input)));\n}\n</code></pre></li>\n<li><p>Swallowing exceptions is not a good practice, even in an exercise:</p>\n\n<blockquote>\n<pre><code>} catch (Exception e) {\n // debug exception here and log.\n}\n</code></pre>\n</blockquote>\n\n<p>If something throws an exception you'll miss it. You could modify the <code>main</code> method to throw exceptions and remove the try-catch block instead:</p>\n\n<pre><code>public static void main(String[] args) throws Exception {\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><p>You could throw a more specific exception here, like an <code>IllegalArgumentException</code> or a <code>NullPointerException</code>:</p>\n\n<blockquote>\n<pre><code>if (inp == null)\n throw new Exception(\"input is null\");\n</code></pre>\n</blockquote>\n\n<p>Calling the method with null input array is rather a programming error, so unchecked exceptions are better here. (It would make the <code>throw Exception</code> on the <code>main</code> unnecessary.)</p></li>\n<li><p>I guess <code>result</code> (as variable name) would be easier to understand here:</p>\n\n<blockquote>\n<pre><code>BigInteger ans[] = new BigInteger[inp.length];\n</code></pre>\n</blockquote>\n\n<p>I'd also avoid abbreviations. I've found that they undermine autocomplete. (When you type <code>co</code> and press Ctrl+Space in Eclipse it founds nothing but it could found <code>count</code>.) Furthermore, they require mental mapping (readers/maintainers have to decode them every time.</p>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Use Intention-Revealing Names</em>, p18; <em>Use Pronounceable Names</em>, p21; <em>Avoid Mental Mapping</em>, p25</p></li>\n<li><p>I'd rename this variable to <code>fullProduct</code> or something more descriptive to express its purpose:</p>\n\n<blockquote>\n<pre><code>BigInteger multiple = new BigInteger(\"1\");\n</code></pre>\n</blockquote></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:00:21.923", "Id": "45522", "ParentId": "45498", "Score": "15" } }, { "body": "<p>What about something like this ?</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class ArrayCalc {\n\n public static void main(String[] args){\n\n Integer[] exparray = {2,3,4};\n\n Integer[] resultarray = new Integer[exparray.length]; \n\n for (int i = 0; i&lt; exparray.length; i++){\n\n if(!exparray[i].equals(0)){\n Integer result = 1;\n for (int j = 0; j&lt;exparray.length; j++)\n result = result * exparray[j];\n result = result/exparray[i];\n resultarray[i] = result;\n }\n }\n System.out.println(Arrays.toString(resultarray));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:16:04.540", "Id": "79454", "Score": "3", "body": "can you explain the reasoning behind why you would do it like this, please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:58:47.603", "Id": "79467", "Score": "2", "body": "The OP stated: *I would like to get feedback on my answer and see what's wrong*. This in no way addresses the OP's code and is just a code dump. Please review the OP's code (you can even *explain* how this would make for a better solution), otherwise this answer may be deleted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:42:39.030", "Id": "45532", "ParentId": "45498", "Score": "1" } } ]
{ "AcceptedAnswerId": "45522", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:58:45.157", "Id": "45498", "Score": "24", "Tags": [ "java", "array", "interview-questions" ], "Title": "Array whose values are the product of every other integer" }
45498
<p>I made this bit of code that uses jQuery in a simple HTML file to see if my son would think it is fun/interesting and to help me with my jQuery skills. The thing that was hard was the selectors towards the bottom of the script block. I am wondering if there is a better way to do this. Warning: it auto-refreshes to 're-pixel' the screen (for lack of a better word).</p> <p>Also I am building tables but I am sure they are not right, it was my intention to grab the <code>innerwidth</code> and <code>innerheight</code> and create a table that is divided into fractional squares that perfectly fill the view-able browser screen. I had trouble getting the logic right.</p> <p>Also, I had to place a span tag in side the <code>&lt;td&gt;</code> blocks so the wouldn't collapse on me. I wanted to do this in divs but I wasn't sure how to get the same effect.</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>$(document).ready(function () { // find random colors function colorMe() { var newColor = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6); return newColor; } // not sure about this but i got it to work in some wierd way. var wb = Math.floor(window.innerWidth / 200); var hb = Math.floor(window.innerHeight / 200); // table buildout append cells and rows to the table. // Note the yucky span tag to prevent td collapse var table = $('&lt;table border=1 bordercolor=white cellpadding=0 cellspacing=0 width="100%" height="100%"&gt;&lt;/table&gt;'); for (i = 0; i &lt; 100; i++) { row = $('&lt;tr&gt;&lt;/tr&gt;'); for (j = 0; j &lt; 200; j++) { var row1 = $('&lt;td bgcolor="' + colorMe() + '" width="' + wb + '"&gt;&lt;/td&gt;').html('&lt;div style="display:inline-block;height:' + hb + 'px;"&gt;&lt;/div&gt;'); table.append(row); row.append(row1); } } // table to body append $('body').append(table); // mouse event to emulate a pen commenting out the last two give it a fun calligraphy look $("td").hover(function () { var whoIsMe = $(this).index(); $(this).stop() .animate({ "opacity": "0" }, "fast"); $(this).next("td") .stop() .animate({ "opacity": "0" }, "fast"); $(this).prev("td") .stop() .animate({ "opacity": "0" }, "fast"); $(this).parent() .next() .children("td") .eq(whoIsMe) .stop() .animate({ "opacity": "0" }, "fast"); $(this).parent() .prev() .children("td") .eq(whoIsMe) .stop() .animate({ "opacity": "0" }, "fast"); }); // eventually reload for a fresh palette of colored squares setTimeout(function () { window.location.reload(1); }, 50000); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Here is a link to a <a href="http://jsfiddle.net/ch7MW/" rel="nofollow">jsfiddle</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:14:11.077", "Id": "79403", "Score": "0", "body": "What your code is suppose to do ? Could you make a jsfiddle and link to it ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:19:54.613", "Id": "79404", "Score": "0", "body": "Sure thing... http://jsfiddle.net/ch7MW/" } ]
[ { "body": "<p>To make them square: </p>\n\n<pre><code>var size = Math.max(window.innerWidth,window.innerHeight)/200;\nvar xbound = Math.floor(window.innerWidth/size);\nvar ybound = Math.floor(window.innerHeight/size);\n</code></pre>\n\n<p>Simply use <code>xbound</code> and <code>ybound</code> as the upper limits in the <code>for</code> loops.</p>\n\n<p>Try to use CSS where you can.</p>\n\n<p>Additionally, your script loads very slowly because of the excessive DOM manipulation. Rather than adding each element to the page one by one, create a single object and then paste that in one go. Just add up the html code with the <code>+=</code> operator before inserting it into the page.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T02:26:35.213", "Id": "79505", "Score": "0", "body": "That gets my for loops working perfect. But the heavy lifting on the DOM? Ok, I have a few ideas maybe simplifying it and do a document write while I am looping (unless that is doing the same thing). Hmmm. I will have to consider that. Thank you for answering my question. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T02:27:34.447", "Id": "79506", "Score": "0", "body": "@FrankTudor Your `for` loop only iterates one time, right? Or am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T02:44:11.417", "Id": "79508", "Score": "0", "body": "I have two for loops one for the <TR> 'i' that is called once and spins for my innerheight about 95 times. Then there is 'j' for <TD> my innerwidth (on my screen) it spins about 200 times. That makes 'j' being called 95 times. So with 'i' and 'j' that is 19,000 iterations to build the table for my particular screen width and height." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T02:48:43.327", "Id": "79509", "Score": "1", "body": "+= yes I know what you are talking about here. Build a variable appending it as I loop. Instead of the almost reverse <tr> spins out a bunch of <td> cells and then appends back the empty tr and appends that back to the table. That is fancy but not practical nor would it make any sense to an 11 year old mind." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:11:40.707", "Id": "45572", "ParentId": "45518", "Score": "3" } }, { "body": "<p>Some quick advice since this already has an accepted answer - you will make things quickly less confusing if you use a few other javascript libraries.</p>\n\n<ul>\n<li>At the very least you should always be using <a href=\"http://lodash.com/\" rel=\"nofollow\">lodash</a>, <a href=\"http://underscorejs.org/\" rel=\"nofollow\">underscore</a>, or <a href=\"http://sugarjs.com/\" rel=\"nofollow\">surgarjs</a>. Either one of these brings so much to the table as far as making loops and the idioms of javascript make actual sense.</li>\n<li>If you want to stick with outputting html, at least use a template system like <a href=\"http://handlebarsjs.com/\" rel=\"nofollow\">handlebars</a>. It will clear all that javascript-mixed-with-html mess right up.</li>\n<li>Beyond that you get into mvvm and routing libraries like knockout or sammyjs.</li>\n<li>And if you want some real structure, a full-on framework like AngularJs or EmeberJs is almost certainly overkill for such a project but many novices find that it makes their learning javascript significantly easier.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T21:58:59.120", "Id": "79903", "Score": "0", "body": "Hey thanks! I will look into those. Lo-Dash looks interesting. I have heard of _Underscore.js but I have not used either. I will make a list of these tool-kits you suggest and start looking at how I can leverage them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T23:34:00.620", "Id": "79907", "Score": "0", "body": "@FrankTudor lodash and underscore are virtually identical just with a slightly different approach" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T16:38:59.473", "Id": "45762", "ParentId": "45518", "Score": "1" } } ]
{ "AcceptedAnswerId": "45572", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:40:50.990", "Id": "45518", "Score": "7", "Tags": [ "javascript", "jquery", "html" ], "Title": "Father-son project: Drawing on a grid" }
45518
<p>So I am trying to make a Object oriented Node.js class for store information about riddles. Please feel free to be harsh as possible. Would love to hear your ideas about how to make this class better!</p> <pre><code>function RiddleInfo(riddle, answer, hint1, hint2, hint3, ohFactor, difficulty) { this.riddle = riddle || null; this.answer = answer || null; this.hint1 = hint1 || null; this.hint2 = hint2 || null; this.hint3 = hint3 || null; this.ohFactor = ohFactor || null; this.difficulty = difficulty || null; } RiddleInfo.prototype.getRiddle = function() { return this.riddle; } RiddleInfo.prototype.setRiddle = function(riddle) { this.riddle = riddle; } RiddleInfo.prototype.getAnswer = function() { return this.answer; } RiddleInfo.prototype.setAnswer = function(answer) { this.answer = answer; } RiddleInfo.prototype.getHint = function(hintNumber) { switch(hintNumber) { case 1: return this.hint1; break; case 2: return this.hint2; break; case 3: return this.hint3; break; default: return 'InvalidArgumentException line 25 in RiddleInfo.js: ' + 'hintNumber must be 1, 2, or 3 but instead was ' + hintNumber; } } RiddleInfo.prototype.getOhFactor = function() { return this.ohFactor; } RiddleInfo.prototype.setOhFactor = function(ohFactor) { this.ohFactor = ohFactor; } RiddleInfo.prototype.getDifficulty = function() { return this.difficulty; } RiddleInfo.prototype.setDifficulty = function(difficulty) { this.difficulty = difficulty; } RiddleInfo.prototype.isSimilarTo = function(otherRiddle) { if (this.getRiddle() === otherRiddle.getRiddle() || this.getAnswer() === otherRiddle.getAnswer() ) { return true; } else { return false; } } RiddleInfo.prototype.fill = function(newFields) { for (var field in newFields) { if (this.hasOwnProperty(field) &amp;&amp; newFields.hasOwnProperty(field)) { if (this[field] !== 'undefined') { this[field] = newFields[field]; } } } }; module.exports = RiddleInfo; </code></pre>
[]
[ { "body": "<p>From the outset, I'm not sure how useful/necessary this constructor (\"class\") is, to be honest. Everything could seemingly be stored in a simple object literal:</p>\n\n<pre><code>var aRiddle = {\n riddle: \"What gets wetter and wetter the more it dries?\",\n answer: \"A towel\",\n difficulty: \"meh\",\n ohFactor: \"so-so\",\n hints: [\n \"Galactic hitchhikers should always bring one\",\n \"Look in the bathroom\",\n \"Everyone has several of the things\"\n ]\n};\n</code></pre>\n\n<p>Point is, your class doesn't do any input checking, and most of its methods are getters and setters - which don't necessarily make much sense in JavaScript. For instance. I can do this:</p>\n\n<pre><code>var aRiddle = new RiddleInfo(); // no arguments at all: no errors\naRiddle.riddle = \"This statement is false\"; // bypasses setter completely\naRiddle.foo = 23; // arbitrary property assignment\naRiddle.setAnswer(new Date()); // using setter, but passing in nonsense\n</code></pre>\n\n<p>The only methods left are <code>getHint</code> and <code>isSimilarTo</code>. Both of these could be handled by functions outside the object. Yes, it defies encapsulation, but... 'eh, I'd choose that over a lot of \"pointless\" code.</p>\n\n<p><em>But</em>, let's give the code a once-over. Again, I'd suggest a very different approach, but that's not the same as reviewing the code you posted.</p>\n\n<p>First off, your constructor takes an awful lot of arguments. This creates very tight coupling to any other code: All that other code must know the correct order of all those arguments to use the constructor, which makes it harder to change this constructor in the future without breaking everything.<br>\nNow, I'm not sure what arguments you consider <em>required</em> and which ones might be optional, but at the very least, I'd say a riddle consists of a question, and an answer. I'd consider the other arguments optional for now. And to avoid having to order the arguments correctly, I'd use an object literal (like the one above) for all the optional arguments:</p>\n\n<pre><code>function RiddleInfo(question, answer, options) {\n // ... see below ...\n}\n</code></pre>\n\n<p>As mentioned, I'd skip getters and setters <em>unless</em> they actually contributing in some way. For instance, they could (<em>should</em>) check their input, to prevent nonsense values being set. And if you're going to have them, <em>you might as well use them yourself</em>. </p>\n\n<pre><code>function RiddleInfo(question, answer, options) {\n this.setQuestion(question);\n // ...\n}\n\nRiddleInfo.prototype.setQuestion = function (question) {\n if( typeof question !== \"string\" ) {\n throw new TypeError(\"Question must be a string\");\n }\n this.question = question;\n};\n</code></pre>\n\n<p>Now the constructor will use the setter, meaning it's guaranteed to throw a <code>TypeError</code> if you're using it wrong. You can do something similar for the other arguments, as well as the optional ones.</p>\n\n<p>Speaking of: Don't return a string that looks like an exception like you do in <code>getHint</code>. It's basically lying: It's not an \"InvalidArgumentException\" - it's just a string. And hardcoding the line number in there is crazy - you'll have to change it constantly, even if you've only been adding comments or just whitespace. Just throw a real exception. It'll contain a stack trace, and give you the line number.</p>\n\n<p>Anyway, the above neglects one thing: You can still completely bypass the setter by just writing <code>riddle.question = ...</code>. Now, as mentioned, getters and setters are probably more trouble than their worth in JavaScript, but if you want a more \"secure\" way of doing things, you'll have to change things up a bit:</p>\n\n<pre><code>function RiddleInfo(question, answer, options) {\n // define the setter here\n this.setQuestion = function (newQuestion) {\n if( typeof question !== \"string\" ) {\n throw new TypeError(\"Question must be a string\");\n }\n question = newQuestion;\n };\n\n // define the getter here too\n this.getQuestion = function () {\n return question;\n };\n\n this.setQuestion(question);\n\n // ... similar thing for other arguments ...\n}\n</code></pre>\n\n<p>The point in the above is that <code>question</code> remains a local variable inside the constructor function. Instead of setting it on the instance (<code>this.question = question</code>), we set the getter/setter functions instead. Thanks to closures, they can access the local <code>question</code> variable. What you get is something like</p>\n\n<pre><code>var aRiddle = RiddleInfo(\"...\", \"Darkness\");\n\naRiddle.setQuestion(\"The more there is, the less you see. What could I be?\");\naRiddle.getQuestion(); // =&gt; \"The more there is [...]\"\naRiddle.question = \"this won't have any effect\";\naRiddle.getQuestion(); // =&gt; \"The more there is [...]\"\n</code></pre>\n\n<p>Lastly, if you've got more than 1 of something, you should probably use an array: i.e. use an array for the hints. You may want more than 3 or fewer, so don't have named variables for exactly 3.</p>\n\n<p>Phew, I think I'll stop here. Hopefully you've got something to chew on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T02:46:05.463", "Id": "45576", "ParentId": "45519", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:48:19.663", "Id": "45519", "Score": "1", "Tags": [ "javascript", "object-oriented", "node.js" ], "Title": "object oriented Node.js class RiddleInfo.js" }
45519
<p>I was unable to find how to get current URL so here's what I've made. Brief tests didn't reveal anything bad. Your thoughts, educated opinions, suggestions, and comment on potential bugs or improvements is highly appreciated! </p> <p>Especially take a look at <code>$_SERVER['HTTPS']</code> marked with <code>// ???</code>. I have found many different ways to test for HTTPS and this is the least ugly in my opinion. But still, I'm not sure this is the right way. off/on vs. 0/1 vs. false/true... </p> <blockquote> <p><code>HTTPS</code> Set to a non-empty value if the script was queried through the HTTPS protocol. Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.</p> </blockquote> <p>If you can, please don't comment at function or variable names. Feel free to rename them to whatever you want, how ever you want. </p> <pre><code>/* default return current url+ruri from $_SERVER on false return current url */ function current_url ($with_ruri=true) { $protocol = isset($_SERVER['HTTPS']) &amp;&amp; strtolower($_SERVER['HTTPS']) != 'off' ? 'https' : 'http'; // ??? $host = trim(filter_var(strip_tags($_SERVER['HTTP_HOST']), FILTER_SANITIZE_URL)); $uri = $_SERVER['REQUEST_URI']; // full_uri?with=ruri $uri = trim(filter_var(strip_tags($uri), FILTER_SANITIZE_URL)); if (!$with_ruri) { $result = strstr($uri, '?', true); // trim ?with=ruri $uri = $result === FALSE ? $uri : $result; // if no ? in uri } $uri = $uri ? urldecode($uri) : $uri; $url = $protocol.'://'.$host.$uri; return $url; } </code></pre>
[]
[ { "body": "<p>I think this might not be a coincidence:</p>\n\n<blockquote>\n <p>I was unable to find how to get current url so here's what I've made. </p>\n</blockquote>\n\n<p>The webserver could be behind an SSL endpoint or a load balancer, so <code>$_SERVER</code> values might be modified during the request. I have seen a few web applications where the administrator have to set up the <em>base URL</em> in a config file or configuration page.</p>\n\n<p>Consider the following:</p>\n\n<pre><code>browser -----------&gt; SSL endpoint ----------&gt; HTTP/PHP server\n (https) (http)\n</code></pre>\n\n<p>The browser sends a HTTPS requrest (<code>https://example.com</code>) and it lands at the SSL endpoint which decrypts the request and forwards it to the PHP server which is in an internal network and available at <code>http://internal.example.com/</code>. Note that it's plain HTTP, not HTTPS. The PHP sees it as <code>http://internal.example.com/</code> but the browser requests another URL: <code>https://example.com</code>.</p>\n\n<p>I've seen some similar infrastructures where the SSL encryption/decryption was moved to another machine for better performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:39:05.613", "Id": "79426", "Score": "0", "body": "Would you be kind to explain your answer in more detail. Why and how could $_SERVER be modified? When my function (potentially) starts to fail? Is this good example of `$base_url=\"http://www.example.com/\";` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:01:47.207", "Id": "79430", "Score": "1", "body": "@CoR: See the update please. Let me know if it's not clear and I look for a few more examples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:38:55.947", "Id": "79440", "Score": "0", "body": "It's excellent, clear and to the point! If I understand it correctly, there is no automatic cure for this. I must know both servers configuration and architecture... Or I must provide redundant data via get, post or masked somehow in url. And REALLY important question: Is this only setting where $_SERVER might fail?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:23:57.083", "Id": "79457", "Score": "1", "body": "@CoR: At least I can't come up with any other corner-case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:39:23.430", "Id": "79461", "Score": "1", "body": "Well this is a clear case when I ask a question and get an excellent answer that completely surprise me. Today I've learned something new! Thanks man :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:41:24.123", "Id": "79462", "Score": "0", "body": "@CoR: You're welcome. Actually, I've also learned that, I've never thought about why some webapps need this configuration." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:26:23.790", "Id": "45525", "ParentId": "45520", "Score": "1" } } ]
{ "AcceptedAnswerId": "45525", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T15:52:06.030", "Id": "45520", "Score": "3", "Tags": [ "php", "php5", "url", "https" ], "Title": "Return current URL" }
45520
<p>I've overridden Backbone.Collection.add for my Collection to ensure that the Collection never has two PlaylistItems who share a Song ID. My implementation seems incredibly verbose and I was curious if there's a better way to express my desires:</p> <pre><code>var PlaylistItems = MultiSelectCollection.extend(_.extend({}, SequencedCollectionMixin, { model: PlaylistItem, // Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID. add: function (items, options) { if (items instanceof Backbone.Collection) { items.each(function (item) { trySetDuplicateSongId.call(this, item); }.bind(this)); } else if (_.isArray(items)) { _.each(items, function (item) { trySetDuplicateSongId.call(this, item); }.bind(this)); } else { trySetDuplicateSongId.call(this, items); } return MultiSelectCollection.prototype.add.call(this, items, options); } })); function trySetDuplicateSongId(playlistItemToAdd) { var duplicatePlaylistItem = this.find(function (playlistItem) { return playlistItem.get('song').get('id') === playlistItemToAdd.get('song').get('id'); }); var duplicateFound = !_.isUndefined(duplicatePlaylistItem); if (duplicateFound) { // Make their IDs match to prevent adding to the collection. if (duplicatePlaylistItem.has('id')) { playlistItemToAdd.set('id', duplicatePlaylistItem.get('id')); } else { playlistItemToAdd.cid = duplicatePlaylistItem.cid; } } } </code></pre>
[]
[ { "body": "<p>I've been looking at this since a while, it seems mostly verbose because you want to handle Backbone collections, and arrays, and single songs..</p>\n\n<p>It seems simpler to normalize in all 3 scenario's <code>items</code> to something that you then process once. I am not 100% this works, but you should get the gist:</p>\n\n<pre><code>// Don't allow duplicate PlaylistItems, determined by the PlaylistItem's Song's ID. \nadd: function (items, options) {\n\n if( !items.length ){ \n //Anti duck typing, it's not an array or collection\n items = [items];\n }\n else if ( items instanceof Backbone.Collection ){\n //Provide direct access to the array\n items = items.models;\n }\n _.each(items, function (item) { \n trySetDuplicateSongId.call(this, item);\n }.bind(this));\n\n return MultiSelectCollection.prototype.add.call(this, items, options);\n}\n</code></pre>\n\n<p>For <code>trySetDuplicateSongId</code> I would extract <code>playlistItemToAdd.get('song').get('id')</code> and cache it into a variable. This should make your search twice as fast. Also I would clean up the whole duplication finding, I find the code a bit verbose. Again, I am making some assumptions here with regards to what you set as defaults, but I would do this:</p>\n\n<pre><code>function trySetDuplicateSongId(playlistItemToAdd) {\n\n var songId = playlistItemToAdd.get('song').get('id'),\n duplicate = this.find(function (playlistItem) {\n return playlistItem.get('song').get('id') === songId;\n });\n\n if (duplicate) {\n // Make their IDs match to prevent adding to the collection.\n if (duplicatePlaylistItem.has('id')) {\n playlistItemToAdd.set('id', duplicatePlaylistItem.get('id'));\n } else {\n playlistItemToAdd.cid = duplicatePlaylistItem.cid;\n }\n }\n}\n</code></pre>\n\n<p>Furthermore, if you have to add lots of songs, then you will run into increasingly bad performance. I would probably have a separate list/object with just the song id's pointing to an object with item id or cid.</p>\n\n<p>Finally, I am curious as to why you would not allow a playlist item to be shared by song lists ;P</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-15T20:06:57.917", "Id": "47283", "ParentId": "45523", "Score": "1" } } ]
{ "AcceptedAnswerId": "47283", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T16:01:45.147", "Id": "45523", "Score": "2", "Tags": [ "javascript", "backbone.js" ], "Title": "Overriding Backbone.Collection.add to enforce uniqueness on non-id property" }
45523
<p><strong>Background</strong>: I'm designing a system (VB/WinForms) that uses a database(MS SQL Server 2008 R2) to track people, their stock account #'s, which stocks they are investing in, and the payout of those stocks. </p> <p>Basically, just reading/writing to the database and some time-elapsed functionality. (One payout per year, etc.) I have forms where users are entering employees to the database, adding accounts, etc.</p> <p><strong>My issue</strong>: I never truly understood OOP, however I am getting more involved with it now, and while my program works, I want the code to be better (look better, be more flexible, utilize classes/objects more, etc.)</p> <p>That being said, how can I make this code more <em>Objected-Oriented</em>?</p> <p><strong>Note</strong>: I am also utilizing ReSharper, however that can only do so much and I don't want to have to rely on a tool for the rest of my career.</p> <p><strong>Note</strong>: This project utilizes an encryption class.</p> <pre><code>Imports System.Data.SqlClient Public Class EmployeeUpdateFrm Private _id As String Dim _seqId As Integer Private Sub Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim conn1 As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True") Dim qry As String = "SELECT CMPNY_SEQ_ID, CMPNY_NM FROM CMPNY" Dim ds1 As New DataSet() Using da As New SqlDataAdapter(qry, conn1) 'fill data set 1 for combobox da.Fill(ds1) End Using With CompanyCbx 'what the user sees .DisplayMember = "CMPNY_NM" 'value behind each display member .ValueMember = "CMPNY_SEQ_ID" .DataSource = ds1.Tables(0) .SelectedIndex = 0 End With 'close connection conn1.Close() Dim index As Integer = 1 'The vertical spacing between rows of controls relative to the textboxes. Dim yMargin As Integer = 10 Dim query As String 'Create a new instance of the encryption class. Dim strKey As String = "Key1" Dim Crypto As ClsCrypt Crypto = New ClsCrypt(strKey) Dim eID As String = Crypto.EncryptData(_id) query = "SELECT EMPL_SEQ_ID, EMPL_ID, EMPL_LAST_NM, EMPL_FIRST_NM, EMPL_PREFRD_NM, EMPL_BIRTH_DT, EMPL_MAIL_STN_CD," query &amp;= " EMPL_ADDR1_TXT, EMPL_ADDR2_TXT, EMPL_CITY_NM, EMPL_STATE_CD, EMPL_POSTL_CD, EMPL_PYRL_CD, " query &amp;= " EMPL_FILE_NO, EMPL_SPRTN_DT, CMPNY_SEQ_ID, EMPL_ACTV_IND, BEG_DT, END_DT " query &amp;= " FROM EMPL" query &amp;= " WHERE EMPL_ID = @ID; " 'New DataSet object to hold employee records. Using ds As New DataSet() Using conn As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True") Using da As New SqlDataAdapter() da.SelectCommand = New SqlCommand(query, conn) da.SelectCommand.Parameters.Add(New SqlParameter("@ID", eID)) da.Fill(ds) End Using End Using If CompanyCbx.Items.Count &gt; 0 Then CompanyCbx.SelectedIndex = ds.Tables(0).Rows(0).Item(15).ToString End If Try For i As Integer = 0 To ds.Tables(0).Rows.Count - 1 For z As Integer = 0 To ds.Tables(0).Columns.Count - 1 If z &lt;&gt; 0 Then 'Decrypt all rows and columns ds.Tables(0).Rows(i)(z) = Crypto.DecryptData(ds.Tables(0).Rows(i)(z)) End If Next Next Catch ex As Exception MsgBox(ex.ToString) End Try </code></pre> <p>I also ask (without being opinionated), with programs like this (fairly small, read/write to database with no extraordinary functionality) how flexible is the coding? By that I mean, <strong>I don't really see how</strong> I could use something like:</p> <pre><code>Dim Person as New Person() Class Person Public firstName as String Public lastName as String </code></pre> <p>etc.</p> <p>Especially because I utilize DataSets so heavily.</p>
[]
[ { "body": "<p>If you want to learn how to use classes, the best approach is to use them while building a small program. I suggest you do create a Person class and that you stop using dataset. This will be a great learnign experience.</p>\n\n<p>Using numbers instead of const or strings can create a mantenance problem. At a glance, it's not easy to know what 15 mean.</p>\n\n<pre><code>ds.Tables(0).Rows(0).Item(15)\n</code></pre>\n\n<p>Remove all the database query from the UI. It'll also make the code more readable and you'll be able to reuse the functions if needed. You should have the connection string at one place.</p>\n\n<pre><code>Public Class EmployeeUpdateFrm\n\n Private Sub Load(sender As Object, e As EventArgs) Handles MyBase.Load\n\n LoadDropDown()\n\n ' ...\n\n End Sub\n\n Sub LoadDropDown()\n\n Dim companies As List(Of Company)\n\n companies = DAL.GetCompanies()\n\n With CompanyCbx\n 'what the user sees\n .DisplayMember = \"Name\"\n 'value behind each display member\n .ValueMember = \"Id\"\n .DataSource = companies\n .SelectedIndex = 0\n End With\n\n End Sub\n\nEnd Class\n\nPublic Class DAL\n\n Private Shared _connectionString As String = \"Data Source=SQLTEST_HR,4000\\SQLEXPRESS;Integrated Security=True\"\n\n Public Shared Function GetCompanies() As List(Of Company)\n ' ...\n End Function\n\nEnd Class\n\nPublic Class Company\n\n Public Property Id As Integer\n Public Property Name As String\n\nEnd Class\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T14:44:22.157", "Id": "81330", "Score": "0", "body": "Yes, this is exactly the type of answer I was looking for. Please understand that when you say \"stop using datasets\" I do not know what else to use. What you're seeing is the only way I have been able to do this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T14:56:02.377", "Id": "81334", "Score": "0", "body": "@MarkLaREZZA Note that there is nothing wrong in using dataset. But you have the ability to slowly change each dataset to a class and learn along the way how to use them. In the small example I gave, instead of using the dataset ds1 I used a List(Of Company)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T15:00:13.787", "Id": "81335", "Score": "0", "body": "Ah, okay. I see it a little bit clearer now. I agree 100% that the dataset index usage is unreadable and unclear. That's what truly prompted me to want to learn how to code better. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T14:40:25.943", "Id": "46558", "ParentId": "45527", "Score": "2" } } ]
{ "AcceptedAnswerId": "46558", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T17:02:32.760", "Id": "45527", "Score": "4", "Tags": [ "object-oriented", "vb.net" ], "Title": "System for tracking stock information" }
45527
<p>I have the following 3 different versions of code. Version 1 is overly verbose and contains redundancy but on the other hand seems easier to read. Version 2 is somewhere in the middle, and Version 3 is shortened and straight to the point.</p> <p>Their all equivalent in terms of functionality. I am not sure about readability. According to best practices which is the best? Please add actual pros-cons based on theory. Is there a chance situations like these are also determined by programming style and hence are opinion based as opposed to having black/white clear guidelines?</p> <h2>Version 1:</h2> <pre><code>for (int i = 0; i &lt; resultsSize; i++) { bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD); app = DataStore.applicationsCache.get(bundle); if (app!=null) { if(catalogRequest.filter.query_pub==null) { addApp(DataStore.applicationsCache.get(bundle),preparedApps); continue; } if(app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub)) addApp(DataStore.applicationsCache.get(bundle),preparedApps); } } </code></pre> <h2>Version 2:</h2> <pre><code>for (int i = 0; i &lt; resultsSize; i++) { bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD); app = DataStore.applicationsCache.get(bundle); if (app!=null) { if(catalogRequest.filter.query_pub==null || app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub)) addApp(DataStore.applicationsCache.get(bundle),preparedApps); } } </code></pre> <h2>Version 3:</h2> <pre><code>for (int i = 0; i &lt; resultsSize; i++) { if ((app = DataStore.applicationsCache.get(ja.getJSONObject(i) .getString(SOLR_BUNDLEID_FIELD))) != null &amp;&amp; (catalogRequest.filter.query_pub == null || app.vendor .equalsIgnoreCase(catalogRequest.filter.query_pub))) addApp(app, preparedApps); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:58:53.617", "Id": "79427", "Score": "3", "body": "Asking which version is better is not a good question as it is asking directly for opinion. You could choose one and see the review of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:00:29.740", "Id": "79428", "Score": "0", "body": "@ Marc-Andre Ok..will change it to ask which is better according to coding / readability standards and why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:13:10.517", "Id": "79433", "Score": "2", "body": "This type of question (A vs B [vs C]) isn't very likely to give you a useful code review, why don't you just post the version you're using, and let reviewers tell you how it would be best written? Please see our [help/on-topic] to see what we're all about - we're looking for code to be peer reviewed, not for snippets to be compared and discussed. As it stands, this question is still opinion-based." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:52:03.943", "Id": "79465", "Score": "0", "body": "This is still an issue of opinion. IMO, if code is *valid* then it is also *readable* but that's my opinion, and it's a pretty strong statement really. I'm basically saying \"you should be able to read anything that isn't a syntax error\" and we all know that within that realm some things are easier to understand than others. I personally use ternary operators and coalesce operator (??) in C#, but I've been told it's not very readable. Well, it's valid code, and to me it's *more* readable than a long IF that won't fit on my screen. I prefer example 3, but I know a lot of people who wouldn't" } ]
[ { "body": "<blockquote>\n <p>Version 1 is overly verbose and contains redundancy but on the other hand seems easier to read.</p>\n</blockquote>\n\n<p>I'd go with the first one with some modifications. The second one need horizontal scrolling which is hard to read. The third one was made for a computer, for humans it's too hard to follow, the condition is too complex.</p>\n\n<blockquote>\n <p>Any fool can write code that a computer can understand. Good programmers write code that humans can understand. (<a href=\"http://en.wikiquote.org/wiki/Martin_Fowler\" rel=\"nofollow\">Martin Fowler</a>)</p>\n</blockquote>\n\n<p>A few whitespace (around operators, method parameters etc.), curly braces and indentation would help:</p>\n\n<pre><code>for (int i = 0; i &lt; resultsSize; i++) { \n bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);\n app = DataStore.applicationsCache.get(bundle);\n if (app != null) {\n if (catalogRequest.filter.query_pub == null) {\n addApp(DataStore.applicationsCache.get(bundle),preparedApps);\n continue;\n }\n\n if (app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub)) {\n addApp(DataStore.applicationsCache.get(bundle), preparedApps); \n } \n }\n}\n</code></pre>\n\n<p>The you could use some explanatory variables to explain the purpose of the conditions:</p>\n\n<pre><code>for (int i = 0; i &lt; resultsSize; i++) { \n bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);\n app = DataStore.applicationsCache.get(bundle);\n if (app == null) {\n continue;\n }\n\n String queryPub = catalogRequest.filter.query_pub; // TODO: use better name\n boolean emptyQueryPub = queryPub == null; // TODO: use better name\n boolean vendorSame = app.vendor.equalsIgnoreCase(queryPub); // TODO: use better name\n if (emptyQueryPub || sameVendor) {\n addApp(app, preparedApps);\n }\n}\n</code></pre>\n\n<p>Note that <code>addApp</code> uses <code>app</code> instead of <code>DataStore.applicationsCache.get(bundle)</code> (as version 3 does) and the inverted <code>app != null</code> condition. I guess the latter is a typo in the question.</p>\n\n<p>See also: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:31:11.153", "Id": "79447", "Score": "0", "body": "Ugly code ... needs to have `{` at line-end, not new-line ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:46:15.307", "Id": "79463", "Score": "0", "body": "@rolfl: Yeah, I also prefer that (code changed now) but I don't have hard facts for that. *Steve McConnell* has some, rather hard to follow ones in *Code Complete 2nd Edition* (p746) and the Java Code Conventions from 1999 also suggests that. The latter is rather a mess nowadays, sometimes I find it embarrassing to quote. Do you have any good resource?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:07:02.743", "Id": "79468", "Score": "0", "body": "Code Conventions for the Java Programming Language [See 7.2, second bullet-point](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#15395)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:16:17.740", "Id": "79470", "Score": "1", "body": "Also see the [Google Java style guide](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.1.2-blocks-k-r-style)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:16:48.950", "Id": "45537", "ParentId": "45534", "Score": "3" } }, { "body": "<p>Version 1 has <strong>code duplication</strong> for one seemingly very important line:</p>\n\n<pre><code>addApp(DataStore.applicationsCache.get(bundle), preparedApps);\n</code></pre>\n\n<p>Duplicating this line is not a good idea if it can be easily avoided.</p>\n\n<hr>\n\n<p>Version 3 is using <code>&amp;&amp;</code> and <code>||</code> <strong>mixed</strong> in the same condition which makes it a lot harder to understand. Try to avoid mixing those two together, instead <em>extract conditions</em> into variables, as palacsint has done with <code>boolean emptyQueryPub</code>.</p>\n\n<hr>\n\n<p>Version 2 is the one I like the best, but with some modifications.</p>\n\n<p>Java Coding Conventions about braces is that they should be on the same line as the condition/loop and not on it's own line.</p>\n\n<p>Adding a few spaces makes the code more readable.</p>\n\n<p>Most IDEs has an Auto-format key-shortcut. Ctrl + Shift + F in Eclipse and Alt + Shift + F in NetBeans. I recommend using it.</p>\n\n<p>The results of the above mentioned fixes:</p>\n\n<pre><code>for (int i = 0; i &lt; resultsSize; i++) {\n bundle = ja.getJSONObject(i).getString(SOLR_BUNDLEID_FIELD);\n app = DataStore.applicationsCache.get(bundle);\n if (app != null) {\n if (catalogRequest.filter.query_pub == null ||\n app.vendor.equalsIgnoreCase(catalogRequest.filter.query_pub)) {\n addApp(DataStore.applicationsCache.get(bundle), preparedApps);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:28:47.470", "Id": "45539", "ParentId": "45534", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:56:14.087", "Id": "45534", "Score": "1", "Tags": [ "java" ], "Title": "Coding standard and Readability: Verbose/Redundant statements vs Short/Compressed" }
45534
<p>Now that we have the nice new <code>foreach</code> loop in Java, the old-style loop looks ugly be comparison.</p> <p>I like the way Python has a <code>range()</code> generator that allows the foreach construct to iterate over a range of integers.</p> <p>I have written a <code>Range</code> class which allows this. Please provide comments. </p> <pre><code>package highland.mark; import java.util.Iterator; /** * A class to enable java's 'foreach' loop to accept a range. * &lt;p&gt; * This allows replacing the C style: * * &lt;pre&gt; * &lt;code&gt; * for (int i = 0; i &lt; 10; i++) {...} * &lt;/code&gt; * &lt;/pre&gt; * * with: * * &lt;pre&gt; * &lt;code&gt; * for (int i : range(10)) {...} * &lt;/code&gt; * &lt;/pre&gt; * * Three versions of range() are provided allowing combinations of start, end, * and step. * * @author Mark Thomas * @version 1.0 */ public final class Range implements Iterator&lt;Integer&gt;, Iterable&lt;Integer&gt; { /** * The next integer to be returned by the iterator. * */ private int next; /** * The last integer to be returned will be (next - 1). */ private final int to; /** * The increment added to the value of next after each iteration. */ private final int step; /** * A Method to be used with the java 'foreach' loop. * &lt;p&gt; * Usage: * * &lt;pre&gt; * &lt;code&gt; * import static highland.mark.Range.range; * ... * for (int i : range(from, to, step)) {...} * &lt;/code&gt; * &lt;/pre&gt; * * @param from * : int, first value returned. * @param to * : int, one more than last value returned. * @param step * : int, increment for each iteration (may be negative so long * as &lt;code&gt;(to &lt; step)&lt;/code&gt;. * @return An Iterable&lt;Integer&gt; which supplies an Iterator&lt;Integer&gt; which, * on each iteration, returns integers from &lt;code&gt;from&lt;/code&gt; to * &lt;code&gt;(to - 1)&lt;/code&gt; incrementing by &lt;code&gt;step&lt;/code&gt; each * time. * @throws IllegalArgumentException * if &lt;code&gt;step == 0&lt;/code&gt; or &lt;code&gt;step&lt;/code&gt; is the wrong * sign. */ public static Iterable&lt;Integer&gt; range(int from, int to, int step) throws IllegalArgumentException { return new Range(from, to, step); } /** * A Method to be used with the java 'foreach' loop. * &lt;p&gt; * Usage: * * &lt;pre&gt; * &lt;code&gt; * import static highland.mark.Range.range; * ... * for (int i : range(from, to)) {...} * &lt;/code&gt; * &lt;/pre&gt; * * @param from * : int, first value returned. * @param to * : int, one more than last value returned. * @return An Iterable&lt;Integer&gt; which supplies an Iterator&lt;Integer&gt; which, * on each iteration, returns integers from &lt;code&gt;from&lt;/code&gt; to * &lt;code&gt;(to - 1)&lt;/code&gt; incrementing by 1 each time. * @throws IllegalArgumentException * if &lt;code&gt;(to &amp;lt; from)&lt;code&gt;. */ public static Iterable&lt;Integer&gt; range(int from, int to) throws IllegalArgumentException { return Range.range(from, to, 1); } /** * A Method to be used with the java 'foreach' loop. * &lt;p&gt; * Usage: * * &lt;pre&gt; * &lt;code&gt; * import static highland.mark.Range.range; * ... * for (int i : range(to)) {...} * &lt;/code&gt; * &lt;/pre&gt; * * @param to * : int, one more than last value returned. * @return An Iterable&lt;Integer&gt; which supplies an Iterator&lt;Integer&gt; which, * on each iteration, returns integers from 0 to * &lt;code&gt;(to - 1)&lt;/code&gt; incrementing by 1 each time. */ public static Iterable&lt;Integer&gt; range(int to) { return Range.range(0, to, 1); } /* * (non-Javadoc) private constructor only used by the static range() * methods. * * @param from : int, first value returned. * * @param to : int, one more than last value returned. * * @param step : int, increment for each iteration (may be negative so long * as (to &lt; step). * * @throws IllegalArgumentException if step == 0 or step is the wrong sign. */ private Range(int from, int to, int step) throws IllegalArgumentException { if (step == 0) { throw new IllegalArgumentException( "The step argument cannot be zero"); } if ((to - from) / step &lt; 0) { throw new IllegalArgumentException( "The step argument has the wrong sign"); } this.next = from; this.to = to; this.step = step; } /* * (non-Javadoc) * * @see java.lang.Iterable#iterator() */ @Override public Iterator&lt;Integer&gt; iterator() { return this; } /* * (non-Javadoc) * * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { return this.step &lt; 0 ? this.to &lt; this.next : this.next &lt; this.to; } /* * (non-Javadoc) * * @see java.util.Iterator#next() */ @Override public Integer next() { int value = this.next; this.next += this.step; return value; } /* * (non-Javadoc) * * @see java.util.Iterator#remove() */ @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException( "The iterator returned from range() does not support remove()"); } } </code></pre> <p><strong>Test code (testng):</strong></p> <pre><code>package highland.mark; import static highland.mark.Range.range; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class RangeTest { @Test public void testRangeFullySpecified() { String result = ""; for (int i : range(2, 19, 3)) { result += i + " "; } assertEquals(result, "2 5 8 11 14 17 "); } @Test public void testRangeBackWards() { String result = ""; for (int i : range(19, 2, -3)) { result += i + " "; } assertEquals(result, "19 16 13 10 7 4 "); } @Test public void testRangeDefaultStep() { String result = ""; for (int i : range(2, 9)) { result += i + " "; } assertEquals(result, "2 3 4 5 6 7 8 "); } @Test public void testRangeDefaultStepAndStart() { String result = ""; for (int i : range(7)) { result += i + " "; } assertEquals(result, "0 1 2 3 4 5 6 "); } @Test(expectedExceptions=IllegalArgumentException.class) public void testwrongWay1() { for (@SuppressWarnings("unused") int i : range(2, 19, -3)) { // No-op; } } @Test(expectedExceptions=IllegalArgumentException.class) public void testwrongWay2() { for (@SuppressWarnings("unused") int i : range(2, -19, 3)) { // No-op; } } @Test(expectedExceptions=IllegalArgumentException.class) public void testZeroStep1() { for (@SuppressWarnings("unused") int i : range(2, 19, 0)) { // No-op; } } @Test(expectedExceptions=IllegalArgumentException.class) public void testZeroStep2() { for (@SuppressWarnings("unused") int i : range(2, -19, 0)) { // No-op; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:08:32.460", "Id": "79450", "Score": "4", "body": "While it is tempting to edit and improve your question, it also makes the existing answers look wrong - it invalidates them. [There is a meta post about this here...](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers). I have rolled-back your edits, but feel free to create a new question with the revised code, or one of the other alternatives suggested in that link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:33:05.467", "Id": "79473", "Score": "0", "body": "The edits contained clear comments indicating the changes and acknowledging the answer that prompted them. I feel it is a shame that you felt it necessary to remove them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:44:31.120", "Id": "79474", "Score": "1", "body": "@HighlandMark: Here is good explanation about the drawbacks (and guides about the suggested ways): http://meta.codereview.stackexchange.com/q/1482/7076" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:58:44.107", "Id": "79478", "Score": "1", "body": "You don't need to name your test methods `testFoo` when you use the `@Test` annotation. Also, given that all tests are for the `Range` class, I'd remove it from their names." } ]
[ { "body": "<p>For the most part, this appears to be neat, and well structured.</p>\n\n<p>There is a significant bug, though:</p>\n\n<ul>\n<li><code>Iterable&lt;Integer&gt;</code> implies an <code>iterator()</code> method. Each time you call that <code>iterator()</code> method you should get a new instance of an interator, not an 'expired' instance.</li>\n</ul>\n\n<p>For example, the following code should print the numbers 1 to 10 twice....</p>\n\n<pre><code>Range onetoten = Range.range(1, 10, 1);\n\nfor (Integer i : onetoten) {\n System.out.println(i);\n}\n\nfor (Integer i : onetoten) {\n System.out.println(i);\n}\n</code></pre>\n\n<p>Your code will only print them once.</p>\n\n<p>The fix for this is to store the <code>from</code> value as well as the <code>to</code> and the <code>step</code>, and to then return a duplicate <code>Range</code> in the <code>iterator()</code> method.</p>\n\n<hr>\n\n<p>EDIT: I should point out this: <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#rangeClosed-int-int-\"><code>IntStream.rangeClosed()</code></a> (Java8)</p>\n\n<pre><code>IntStream.rangeClosed(1, 10).forEach(i -&gt; System.out.println(i));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:45:39.173", "Id": "79441", "Score": "0", "body": "Thanks very much for that. I'll make the change you suggest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:18:27.080", "Id": "79444", "Score": "0", "body": "Thanks for pointing me to the new java.util.stream package." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:22:00.930", "Id": "45538", "ParentId": "45535", "Score": "8" } }, { "body": "<p>+1 to <em>@rolfl</em> and some other notes:</p>\n\n<ol>\n<li><p>I like your <code>final</code>s and the self-checking unit tests. It's good that they test only one thing, it helps debugging and <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a>. Keep it up!</p></li>\n<li><p>The code violates the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next%28%29\" rel=\"nofollow\"><code>Iterator.next()</code>'s contract</a>:</p>\n\n<blockquote>\n <p>Throws:</p>\n \n <p><code>NoSuchElementException</code> - if the iteration has no more elements</p>\n</blockquote>\n\n<p>Consider this:</p>\n\n<pre><code>final Iterable&lt;Integer&gt; range = range(1, 3, 1);\nfinal Iterator&lt;Integer&gt; iterator = range.iterator();\nSystem.out.println(iterator.next()); // 1\nSystem.out.println(iterator.next()); // 2\nSystem.out.println(iterator.next()); // 3, but should throw NoSuchElementException\n</code></pre>\n\n<p>The third <code>next()</code> prints <code>3</code> instead of <code>NoSuchElementException</code>.</p></li>\n<li><p>I'd move some duplication from the test method to a <a href=\"http://xunitpatterns.com/Custom%20Assertion.html#Verification%20Method\" rel=\"nofollow\">custom verification method</a>:</p>\n\n<pre><code>private &lt;T&gt; void verifyRange(final Iterable&lt;T&gt; range, final T... expectedValues) {\n final List&lt;T&gt; result = new ArrayList&lt;&gt;();\n for (T value: range) {\n result.add(value);\n }\n assertEquals(Arrays.asList(expectedValues), result);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>verifyRange(range(2, 19, 3), 2, 5, 8, 11, 14, 17);\n</code></pre></li>\n<li><blockquote>\n<pre><code>@Test(expected = IllegalArgumentException.class)\npublic void testwrongWay1() {\n for (@SuppressWarnings(\"unused\")\n int i: range(2, 19, -3)) {\n // No-op;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You don't need the loop nor the <code>@SuppressWarnings</code> here, the following is the same:</p>\n\n<pre><code>@Test(expected = IllegalArgumentException.class)\npublic void testwrongWay1() {\n range(2, 19, -3);\n}\n</code></pre></li>\n<li><p>You could use a better package name than this:</p>\n\n<blockquote>\n<pre><code>package highland.mark;\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://c2.com/ppr/wiki/JavaIdioms/JavaPackageNames.html\" rel=\"nofollow\">Java Package Names on c2.com</a></p></li>\n<li><p>This comment is rather unnecessary, I'd remove it:</p>\n\n<blockquote>\n<pre><code>/*\n * (non-Javadoc)\n * \n * @see java.lang.Iterable#iterator()\n */\n@Override\npublic Iterator&lt;Integer&gt; iterator() {\n return this;\n}\n</code></pre>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>This is definitely hard to read/understand:</p>\n\n<blockquote>\n<pre><code>return this.step &lt; 0 ? this.to &lt; this.next : this.next &lt; this.to;\n</code></pre>\n</blockquote>\n\n<p>Consider this:</p>\n\n<pre><code>if (this.step &lt; 0) {\n return this.to &lt; this.next;\n} else {\n return this.next &lt; this.to;\n}\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>@Override\npublic boolean hasNext() {\n if (step &lt; 0) {\n return to &lt; next;\n } else {\n return next &lt; to;\n }\n}\n</code></pre>\n\n<p>Modern IDEs use highlighting to separate local variables from fields, so you don't have to use <code>this.</code> here.</p></li>\n<li><blockquote>\n<pre><code>/**\n * The next integer to be returned by the iterator.\n * \n */\nprivate int next;\n/**\n * The last integer to be returned will be (next - 1).\n */\nprivate final int to;\n/**\n * The increment added to the value of next after each iteration.\n */\nprivate final int step;\n</code></pre>\n</blockquote>\n\n<p>A few empty lines between the fields would be readable:</p>\n\n<pre><code>/**\n * The next integer to be returned by the iterator.\n */\nprivate int next;\n\n/**\n * The last integer to be returned will be (next - 1).\n */\nprivate final int to;\n\n/**\n * The increment added to the value of next after each iteration.\n */\nprivate final int step;\n</code></pre>\n\n<p>Anyway, these comments doesn't say anything which is not already in the code, I'd remove this ones too.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T16:21:52.667", "Id": "79650", "Score": "1", "body": "Thank you for the time you spent on this, and your very helpful feedback.\n3. Great refactoring - I'll put that in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T16:44:20.107", "Id": "79652", "Score": "0", "body": "2. Lesson learned - when implementing an interface to check for implied contracts. Fixed. \n4. Yes - much better.\n5. Noted, but I don't have a domain name, and my email is prone to change. \n6. I agree about noise comments, however, as I am implementing an API these methods become part of the public API for my class - should I have a javadoc comment referring to the interface? \n7. Agreed. The ternary operator does not make for readable code (what possessed me?). Spaces too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T17:58:42.230", "Id": "79671", "Score": "1", "body": "5. I see that the recommendation to use the reverse domain name idiom for package names (7.7 Unique Package Names) was moved in the Java Language Specification at Java 7 (to 6.1 Declarations)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T19:38:07.820", "Id": "79683", "Score": "0", "body": "@HighlandMark: #6 is currently not a javadoc comment (starts with `/*` instead of `/**`), that's why I've mentioned it as noise comment. I don't know how javadoc handles public overridden methods without any comment. If it's useful change the comment to a javadoc comment and keep it. If it's same without the comment (javadoc could be smart here, I guess) remove it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T19:45:44.720", "Id": "79688", "Score": "1", "body": "It turns out that javadoc produces almost the same output if nothing is there!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T19:46:25.993", "Id": "79689", "Score": "0", "body": "@HighlandMark: Cool, thanks for the feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T18:19:11.553", "Id": "80035", "Score": "0", "body": "@palacsint Is it just me or there is no 4 ? About #2, if the iterator contain `[1,2,3]` doing 3 `next()` should not throw an execpetion, Am I wrong here ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T18:52:36.067", "Id": "80043", "Score": "0", "body": "@Marc-Andre: #4: It's there (check the markdown). I guess it's a Google Chrome issue. Feel free to report on Meta :) I don't have time for that now. #2: the upper-bound is not inclusive (check the javadoc of the original code), so I think I'm right here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T18:57:49.920", "Id": "80044", "Score": "0", "body": "@Marc-Andre: #4: http://meta.stackexchange.com/q/136019/169573" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T19:12:19.047", "Id": "80046", "Score": "0", "body": "My bad, you're right `The last integer to be returned will be (next - 1).`. (Thanks for the link for the bug)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:41:36.597", "Id": "45553", "ParentId": "45535", "Score": "6" } } ]
{ "AcceptedAnswerId": "45553", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:11:41.590", "Id": "45535", "Score": "10", "Tags": [ "java", "unit-testing", "iterator", "interval" ], "Title": "Using a Pythonesque range() generator function with the Java foreach loop" }
45535
<p>I'm an experienced programmer but not too great at JavaScript so I'm looking to see if I'm doing this 'right'. I want to have several files loaded in (Ajax or really AJAJ) and, once loaded, run some final code. My basic idea is:</p> <pre><code>var jobsToDo = 2; // global function getAsync(url, func) { var client = new XMLHttpRequest(); var handler = function() { func(); jobsToDo--; if(jobsToDo == 0) allLoaded(); }; client.open('GET', url); client.onreadystatechange = handler; client.send(); } getAsync('file1.json', function() { // process file }); getAsync('file2.json', function() { // process file }); function allLoaded() { // ... } </code></pre> <p>Is this correct? Is it a reasonable solution, or are there better ways? Actually <code>onreadystatechange</code> already feels like the wrong thing; is there a better handler that will wait until I get a 200, or should I expand my function above to exit unless the state is appropriate?</p> <p>Also, since I don't do much JavaScript these days (or all the cool kids calling it ECMAScript now?): will I run into trouble with the local function being passed around?</p> <p>My current code has only one file being loaded, so I'm trying to extract the basic functionality here to keep the code DRY.</p> <p><em>Meta: I don't know if this belongs here or on SO; feel free to move if I made the wrong choice.</em></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:19:55.103", "Id": "79445", "Score": "0", "body": "Why you don't do jobsToDo++; inside getAsync() ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:47:29.713", "Id": "79448", "Score": "0", "body": "@MarcoAcierno: Just to guard against the possibility that I ask for one file and it finishes before I ask for the next, in which case `allLoaded()` would be called prematurely. I don't think it's likely but I'd rather not risk it, ceteris paribus." } ]
[ { "body": "<p>1) Nah, the kids still call it JavaScript, but ECMAScript works too. More power to you for knowing both names :)</p>\n\n<p>2) Yes, I'd say you should wait for a less ambiguous state to occur before considering the request done. But there's not really anything better than <code>onreadystatechange</code> (as far as I recall) to check for the request's success. So you still have to code a \"ready-state change\" handler, just make it check <code>client.status === 200</code> (and possibly some headers and whatnot) before deciding what to call next.</p>\n\n<p>Other than that, though, your code's good. The hardcoded <code>2</code> would need to go for this to be of general use, but the basic idea of decrementing a counter is solid.</p>\n\n<p>You could take a look at <a href=\"http://en.wikipedia.org/wiki/Futures_and_promises\" rel=\"nofollow noreferrer\">the futures and promises pattern</a>. There are several JS-implementations of this you can use.</p>\n\n<p>jQuery has such an implementation (via the <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow noreferrer\">Deferred object</a>) built into it's Ajax-system, allowing you to do, say:</p>\n\n<pre><code>var file1 = $.getJSON(\"file1.json\"), // $.getJSON returns a Deferred\n file2 = $.getJSON(\"file2.json\"), \n all = $.when(file1, file2); // and $.when groups several Deferreds\n\n// example usage - you can do the same for the individual files\nall.done(function () {\n // something to call when all files have been successfully loaded\n});\n\nall.fail(function () {\n // something to call in case one or more files fail\n});\n\nall.always(function () {\n // something to always call (like, say, hiding a \"loading\" indicator)\n});\n</code></pre>\n\n<p>Point is that Deferred lets you attach handlers asynchronously - the requests are sent the moment you call <code>getJSON</code>, but you can attach handlers whenever. And you can add several handlers to the same state, if you want. If the response has already been received, the handler will simply be called immediately.</p>\n\n<p>Now, I know this is all jQuery, and perhaps you don't want to use that. If so, more power to you (again). It is however a neat approach and a simple API - or (in my opinion) one to emulate if you so choose.</p>\n\n<hr>\n\n<p>Seeing <a href=\"https://codereview.stackexchange.com/a/45548/14370\">@Kevindra's simple answer</a> (go upvote!), I'm reminded of a different pattern <a href=\"https://stackoverflow.com/a/9432799/167996\">I've used before</a>:</p>\n\n<pre><code> // a simple factory function\n function makeCounter(limit, callback) {\n return function () {\n if( --limit === 0 ) {\n callback();\n }\n }\n }\n\n // ....\n\n // make a \"done\" function set up to expect 2 invocations\n // before calling its callback\n var done = makeCounter(2, function () {\n // all done!\n });\n\n getAsync(\"file1.json\", function () {\n // process file and call the done() function\n done();\n )};\n\n getAsync(\"file2.json\", function () {\n // process file and call the done() function\n done();\n )};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:48:27.000", "Id": "79449", "Score": "0", "body": "That is a near approach with jQuery -- but yes, I'd prefer to avoid it if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:12:16.167", "Id": "79451", "Score": "0", "body": "@Charles Gotcha. Well, the wiki page [lists a number of implementations for JS](http://en.wikipedia.org/wiki/Futures_and_promises#List_of_implementations), but if you fancy a programming challenge, making a simple implementation is fun. I'm actually trying that right now, just to see" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:30:13.930", "Id": "79458", "Score": "0", "body": "@Charles And done; [here's a simple implementation](http://jsfiddle.net/XeLMD/) - as mentioned, I just wrote it to see what it'd take, so it's not tested like the ready-made libraries out there. But it might give you some ideas" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T20:41:46.473", "Id": "45544", "ParentId": "45541", "Score": "4" } }, { "body": "<p>IMO, you keep the jobsToDo counter away from your getAsync method. I think job of your getAsync method should be just to load a file and call the respective handler. </p>\n\n<pre><code>function getAsync(url, func) {\n var client = new XMLHttpRequest();\n client.open('GET', url);\n client.onreadystatechange = func;\n client.send();\n}\n</code></pre>\n\n<p>And you should separately monitor the status - </p>\n\n<pre><code>var filesLoaded = 0;\ngetAsync('file1.json', function() {\n // process file\n checkAllLoaded();\n});\ngetAsync('file2.json', function() {\n // process file\n checkAllLoaded();\n});\n\nfunction checkAllLoaded() {\n filesLoaded += 1;\n if(filesLoaded == 2) {\n // ...\n }\n // ...\n}\n</code></pre>\n\n<p>I don't know if it's a good solution, but I think it would help you to keep the core method <code>getAsync</code> simple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:31:50.587", "Id": "79459", "Score": "3", "body": "You could make `checkAllLoaded()` do the counter increment too - then there's only one thing to do in each handler." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:27:39.373", "Id": "45548", "ParentId": "45541", "Score": "4" } } ]
{ "AcceptedAnswerId": "45544", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T19:44:35.113", "Id": "45541", "Score": "8", "Tags": [ "javascript", "asynchronous", "concurrency" ], "Title": "Wait until all files are loaded asynchronously, then run code" }
45541
<p>I would like advice if this is a good implementation of an application for maintaining information about people (first name, last name, and age).</p> <p>The index.html contains an empty div and 2 templates (1 for listing people and the other for entering/editing a user):</p> <pre><code>&lt;div id="app"&gt; &lt;/div&gt; &lt;script type="text/template" id="listTemplate"&gt; &lt;!-- Iterates over people and makes a table. --&gt; &lt;/script&gt; &lt;script type="text/template" id="editTemplate"&gt; &lt;!-- Displays a form which if for existing user will fill the values. --&gt; &lt;/script&gt; </code></pre> <p>In my starting point JS file I put into a namespace 'people.global' a bunch of things that I use throughout the application:</p> <pre><code>$(function() { people.global = { people: new people.collections.PeopleCollection() }; people.global = $.extend(people.global, { listView: new people.views.ListView(), editView: new people.views.EditView(), router: new people.Router() }); people.global.people.fetch(); Backbone.history.start(); }); </code></pre> <p>The router demonstrates the basic idea which is depending on the screen that should be shown it takes the View's el and draws it in the #app element:</p> <pre><code>var people = people || {}; people.Router = Backbone.Router.extend({ $app: $('#app'), routes: { '': 'list', 'edit': 'edit', 'edit/:id': 'edit', 'delete/:id': 'delete' }, list: function() { this.$app.html(people.global.listView.render().el); }, edit: function(id) { people.global.editView.setId(id); this.$app.html(people.global.editView.render().el); }, delete: function(id) { var person = people.global.people.get(id); person.destroy(); this.navigate('', {trigger: true, replace: true}); } }); </code></pre> <p>Below is the view for editing/adding a person:</p> <pre><code>var people = people || {}; people.views = people.views || {}; people.views.EditView = Backbone.View.extend({ template: _.template($('#editTemplate').html()), setId: function(id) { this.id = id; }, edit: function() { var person; if (this.$("#id").val() !== '') { person = people.global.people.get(this.id); person.set({ 'first': this.$("#first").val(), 'last': this.$("#last").val(), 'age': this.$("#age").val() }); person.save(); } else { people.global.people.create({ first: this.$('#first').val(), last: this.$('#last').val(), age: this.$('#age').val() }); } people.global.router.navigate('', {trigger: true, replace: true}); }, render: function() { var person, that = this; if (this.id) { person = people.global.people.get(this.id); this.$el.html(this.template(person.toJSON())); } else { this.$el.html(this.template({})); } this.$('button').click(function() { that.edit(); }); return this; } }); </code></pre> <p>Is this a good design choice?</p> <p>Is there something that can be done better?</p>
[]
[ { "body": "<p>All in all, this looks okay to me, proper naming, nothing bizarre, ( no commenting ).</p>\n\n<p>The only thing that bothers me is that you call <code>.setId(id);</code> on the <code>editView</code>.</p>\n\n<p><code>editView</code> should have a data model with 1 person, and the <code>.setId()</code> should be called on that data model ( perhaps your function <code>setId()</code> does exactly that ? )</p>\n\n<p>(Deleted race conditions, it not relevant)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T18:26:10.087", "Id": "79679", "Score": "0", "body": "I don't know if this is good. As you can see in EditView edit() method checks for this.id and takes appropriate action." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T19:09:12.553", "Id": "79681", "Score": "0", "body": "I removed my race condition remark, I still feel it's odd that the view get's the data itself instead of getting the data from the controller, or keeping a reference to `this.person` which could be set in `setId`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:26:42.417", "Id": "45614", "ParentId": "45546", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:19:29.973", "Id": "45546", "Score": "6", "Tags": [ "javascript", "backbone.js" ], "Title": "Maintaining information about people" }
45546
<p>From a <a href="https://codereview.stackexchange.com/q/45310/507">previous question</a> I got <a href="https://codereview.stackexchange.com/a/45334/507">an answer</a> that included some template magic (that to be blunt was mind-boggling (as I could not understand it)).</p> <p>So I have been trying to achieve the same results (because trying helps me learn).<br> To make sure I have learn correctly I am putting it here for comment. Hopefully it will also help somebody else (and you never know it may encourage me to write a blog post about it).</p> <p>Template based ranges (I am sure it has been done to death).</p> <p>The idea you provide a range that expanded by the template to make writing code easier. So the code I use to test it is working correctly.</p> <pre><code>template&lt;typename&gt; struct printNumberRange; // Only a specialization for my range is implemented. template&lt;int... N&gt; struct printNumberRange&lt;Sizes&lt;N...&gt;&gt; { static void call() { std::vector&lt;int&gt; v {N...}; std::copy(std::begin(v), std::end(v), std::ostream_iterator&lt;int&gt;(std::cout, "\n")); } }; // Function to deduce the arguments and // Call the print correctly. template&lt;int S, int E&gt; void printRange() { print&lt;typename Range&lt;S,E&gt;::type&gt;::call(); } int main() { // Print the range using a template printRange&lt;3,8&gt;(); } </code></pre> <h3>Version 1</h3> <p>The template code I started with:</p> <pre><code>template&lt;int... N&gt; struct Sizes { typedef Sizes&lt;N...&gt; type; }; template&lt;int C, int P, int... N&gt; struct GetRange { typedef typename GetRange&lt;C-1, P+1, N..., P&gt;::type type; }; template&lt;int P, int... N&gt; struct GetRange&lt;0, P, N...&gt; { typedef typename Sizes&lt;N..., P&gt;::type type; }; template&lt;int S, int E&gt; struct Range { typedef typename GetRange&lt;E-S, S&gt;::type type; }; </code></pre> <p>But it seems the trend nowadays is to use inheritance to get rid of the ugly <code>typedef typename ....</code> at each level:</p> <h3>Version 2</h3> <p>This should be exactly the same.<br> But we use inheritance to get the type of the terminal class in the recursion. Personally I find this much harder to read than the previous version. But it is more compact.</p> <pre><code>template&lt;int... N&gt; struct Sizes { typedef Sizes&lt;N...&gt; type; }; template&lt;int C, int P, int... N&gt; struct GetRange: GetRange&lt;C-1, P+1, N..., P&gt; {}; template&lt;int P, int... N&gt; struct GetRange&lt;0, P, N...&gt;: Sizes&lt;N...&gt; {}; template&lt;int S, int E&gt; struct Range: GetRange&lt;E-S+1, S&gt; {}; </code></pre> <p>I can specialize <code>printNumberRange</code> to take a range directly.</p> <pre><code>template&lt;int S, int E&gt; struct printNumberRange&lt;Range&lt;S, E&gt;&gt;: printNumberRange&lt;typename Range&lt;S,E&gt;::type&gt; // Inherits from the version {}; // That takes a Sizes&lt;int...&gt; </code></pre> <p>Then the print becomes:</p> <pre><code>int main() { printNumberRange&lt;Range&lt;4,18&gt;&gt;::call(); } </code></pre> <p>Any comments on the Range stuff or the test harness welcome.</p>
[]
[ { "body": "<p>Generally speaking, it's good and works great (version 2 seems better). There are some things that could be changed/added though:</p>\n\n<ul>\n<li><p>In C++, ranges tend to be <code>[begin, end)</code> ranges. Your compile-time integer ranges are actually <code>[begin, end]</code> ranges. The last element should not be included in the range. Therefore, you change this code:</p>\n\n<pre><code>template&lt;int S, int E&gt;\nstruct Range: GetRange&lt;E-S+1, S&gt;\n{};\n</code></pre>\n\n<p>By this one:</p>\n\n<pre><code>template&lt;int S, int E&gt;\nstruct Range: GetRange&lt;E-S, S&gt;\n{};\n</code></pre>\n\n<p>I tried it and it even works for <code>Range&lt;8,8&gt;</code> by producing an empty range.</p></li>\n<li><p>Currently, your <code>Range</code> only works for increasing ranges of values (and empty ones). You could modify your code so that it also works with decreasing ranges of values. What I did is probably not really clean, but it works (take it as a proof of concept). I replaced <code>Range</code> and <code>GetRange</code> by the following classes:</p>\n\n<pre><code>template&lt;int C, int P, int... N&gt;\nstruct GetIncreasingRange:\n GetIncreasingRange&lt;C-1, P+1, N..., P&gt;\n{};\n\ntemplate&lt;int C, int P, int... N&gt;\nstruct GetDecreasingRange:\n GetDecreasingRange&lt;C+1, P-1, N..., P&gt;\n{};\n\ntemplate&lt;int P, int... N&gt;\nstruct GetIncreasingRange&lt;0, P, N...&gt;:\n Sizes&lt;N...&gt;\n{};\n\ntemplate&lt;int P, int... N&gt;\nstruct GetDecreasingRange&lt;0, P, N...&gt;:\n Sizes&lt;N...&gt;\n{};\n\ntemplate&lt;int S, int E, bool Increasing=(S&lt;E)&gt;\nstruct Range;\n\ntemplate&lt;int S, int E&gt;\nstruct Range&lt;S, E, true&gt;:\n GetIncreasingRange&lt;E-S, S&gt;\n{};\n\ntemplate&lt;int S, int E&gt;\nstruct Range&lt;S, E, false&gt;:\n GetDecreasingRange&lt;E-S, S&gt;\n{};\n</code></pre>\n\n<p>These ranges are <code>[begin, end)</code> ranges and also work for empty ranges.</p></li>\n<li><p>Another possible improvement would be to let the user choose the integer type he wants to use for his range. That is actually what is done in the C++14 class <a href=\"http://en.cppreference.com/w/cpp/utility/integer_sequence\" rel=\"nofollow noreferrer\"><code>std::integer_sequence</code></a>, provided along with <code>std::index_sequence</code> which is its specialization for a range of <code>std::size_t</code> values. <a href=\"https://stackoverflow.com/a/23235942/1364752\">Here</a> is a possible implementation.</p></li>\n<li><p>Also, in your function <code>call</code>, you can drop the <code>std::vector</code> and replace it by <code>std::array</code>. The number of values is known at compile time (thanks to the operator <code>sizeof...</code>), so there's no need to use a dynamic storage container.</p>\n\n<pre><code>static void call()\n{\n std::array&lt;int, sizeof...(N)&gt; v { N... };\n std::copy(std::begin(v), std::end(v), std::ostream_iterator&lt;int&gt;(std::cout, \"\\n\"));\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:05:08.813", "Id": "45595", "ParentId": "45549", "Score": "7" } } ]
{ "AcceptedAnswerId": "45595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T21:45:02.523", "Id": "45549", "Score": "9", "Tags": [ "c++", "c++11", "template", "template-meta-programming", "interval" ], "Title": "C++ template range" }
45549
<p>My code calculates primes from one to n. I have verified that the code always produces all the primes in that range correctly.</p> <p>Are there any optimizations that I can make? Are there any bad programming practices besides variable names (e.g. l is close to 1)? Any better normal Windows API? I am using the Sieve of Eratosthenes.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;math.h&gt; #include &lt;Windows.h&gt; using namespace std; #define printprimes() //for each(bool b in primes) cout &lt;&lt; b &lt;&lt; endl; int main(int argc, char* argv[]) { const double s = GetTickCount(); unsigned long long numt; if(argc &lt; 2) { cout &lt;&lt; "Usage: "&lt;&lt;argv[0]&lt;&lt;" &lt;primes until...&gt;" &lt;&lt; endl; return 1; } else if(atoi(argv[1])&lt;1) { cout &lt;&lt; "Usage: "&lt;&lt;argv[0]&lt;&lt;" &lt;primes until...&gt;" &lt;&lt; endl; return 1; } numt = atol(argv[1])+1; bool skipprint = false; if(argc &gt;=3) if(!strcmp(argv[2], "noprint")) skipprint = true; vector&lt;bool&gt; primes(numt); primes.assign(numt, true); primes[0] = false; primes[1] = false; long double sqrtt = sqrt(numt); for(unsigned long long l = 0; l&lt;=sqrtt; l++) { if(!primes[l]) { //cout &lt;&lt; l &lt;&lt; " is false" &lt;&lt; endl; continue; } for(unsigned long long cl = 2*l; cl &lt; numt; cl+= l) { //cout &lt;&lt; cl &lt;&lt; ", a multiple of " &lt;&lt; l &lt;&lt; endl; primes[cl] = false; } } const double m = GetTickCount(); unsigned long long count = 0; if(!skipprint) for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) { cout &lt;&lt; l &lt;&lt; endl; count ++; } if(skipprint) for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) count ++; const double e = GetTickCount(); cout &lt;&lt; endl; cout &lt;&lt; count &lt;&lt; " primes less than or equal to " &lt;&lt; numt-1 &lt;&lt; endl; cout &lt;&lt; "Calculation took " &lt;&lt; m-s &lt;&lt; " ms"; if(!skipprint) cout &lt;&lt; " and printing took " &lt;&lt; e-m &lt;&lt; " ms"; else cout &lt;&lt; " and counting took " &lt;&lt; e-m &lt;&lt; " ms"; cout &lt;&lt;"." &lt;&lt; endl; //for each(bool b in primes) cout &lt;&lt; b &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<p>The algorithm looks good overall. Here are a few comments :</p>\n\n<hr>\n\n<p><code>using namespace std;</code> is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">sometimes frowned upon</a> : some might say that putting it in a cpp file (by opposition to a header file) is ok, some might say that it's not. In any case, it is worth having a read at the link.</p>\n\n<hr>\n\n<pre><code>#define printprimes() //for each(bool b in primes) cout &lt;&lt; b &lt;&lt; endl;\n</code></pre>\n\n<p>does not seem really useful.</p>\n\n<hr>\n\n<p>If you want to handle wrong input in a better way you could have a look at the <a href=\"https://stackoverflow.com/questions/6093414/convert-char-array-to-single-int\">other ways to convert arrays of char to number</a>.</p>\n\n<hr>\n\n<pre><code>bool skipprint = false;\n\nif(argc &gt;=3) if(!strcmp(argv[2], \"noprint\")) skipprint = true;\n</code></pre>\n\n<p>can become :</p>\n\n<pre><code>bool skipprint = false;\nif(argc &gt;=3 &amp;&amp; !strcmp(argv[2], \"noprint\")) skipprint = true;\n</code></pre>\n\n<p>which is nothing but :</p>\n\n<pre><code>bool skipprint = (argc &gt;=3 &amp;&amp; !strcmp(argv[2], \"noprint\"));\n</code></pre>\n\n<p>Also it might be even better to do :</p>\n\n<pre><code>bool print = (argc &lt; 3 || strcmp(argv[2], \"noprint\"));\n</code></pre>\n\n<hr>\n\n<pre><code> if(!primes[l]) {\n //cout &lt;&lt; l &lt;&lt; \" is false\" &lt;&lt; endl;\n continue;\n }\n for(unsigned long long cl = 2*l; cl &lt; numt; cl+= l) {\n //cout &lt;&lt; cl &lt;&lt; \", a multiple of \" &lt;&lt; l &lt;&lt; endl;\n primes[cl] = false;\n }\n</code></pre>\n\n<p>can be written :</p>\n\n<pre><code> if(primes[l]) {\n for(unsigned long long cl = 2*l; cl &lt; numt; cl+= l) {\n //cout &lt;&lt; cl &lt;&lt; \", a multiple of \" &lt;&lt; l &lt;&lt; endl;\n primes[cl] = false;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>In <code>for(unsigned long long l = 0; l&lt;=sqrtt; l++)</code>, you can start from index 2. Please note that if you forget to initialise prime[0] to false, you'll get stuck in an infinite loop.</p>\n\n<hr>\n\n<p>In <code>for(unsigned long long cl = 2*l; cl &lt; numt; cl+= l)</code>, you can start at index <code>l*l</code> because any <code>i*l</code> with <code>i &lt; l</code> should have been crossed out already.</p>\n\n<hr>\n\n<pre><code>if(!skipprint) for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) {\n cout &lt;&lt; l &lt;&lt; endl;\n count ++;\n}\nif(skipprint) for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) count ++;\n</code></pre>\n\n<p>could be rewritten in many different ways. Most obvious one is to use an <code>else</code> :</p>\n\n<pre><code>if (skipprint) for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) count ++;\nelse for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) {\n cout &lt;&lt; l &lt;&lt; endl;\n count ++;\n}\n</code></pre>\n\n<p>A probably better option in order not to repeat code is to do :</p>\n\n<pre><code>for(unsigned long long l = 0; l&lt;numt; l++) if(primes[l]) {\n if (!skipprint)\n cout &lt;&lt; l &lt;&lt; endl;\n count ++;\n}\n</code></pre>\n\n<hr>\n\n<p>Also, you should probably write your algorithm in a function on its own. Other optimisation can be analysed like removing all even numbers from the beginning to use a smaller container.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:03:01.600", "Id": "79589", "Score": "0", "body": "the printprimes was debug which was commented out so I didn't have to remove all the instances. They have all been removed now. The double ifs are there because for some reason the program evaluates both before deciding. primes[0] is always init to false because it represents 0 which is not a prime number. `i` will always be greater than l. I will take everything you told me in to account, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:46:46.293", "Id": "79610", "Score": "0", "body": "`is sometime frowned upon`! Any body doing this in real production code should be shot. FIne if you do it in a ten line program that you write to test something. But anything that goes public should not have it in. Your just shooting the maintainer in the foot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T21:47:48.783", "Id": "79695", "Score": "0", "body": "Yeah @LokiAstari I am not planning on writing an big program for a while yet. If I do, It will be in Java." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:01:20.770", "Id": "45555", "ParentId": "45550", "Score": "7" } }, { "body": "<blockquote>\n <p>Any better normal Windows API?</p>\n</blockquote>\n\n<p>The <code>GetTickCount</code> function returns a <code>DWORD</code> not a <code>double</code>.</p>\n\n<p>According to the documentation it wraps every 50 days, so there's a <code>GetTickCount64</code> function to avoid this problem.</p>\n\n<p>Its resolution is in the 10..60 msec range, which isn't great for measuring the performance of fast code; there's a <code>QueryPerformanceCounter</code> function used with <code>QueryPerformanceFrequency</code> which you can use for measuring shorter intervals.</p>\n\n<hr>\n\n<p>Also, this looks strange to me ...</p>\n\n<pre><code>vector&lt;bool&gt; primes(numt);\n</code></pre>\n\n<p>Does <code>vector</code> support an <code>unsigned long long</code> size? Maybe you should be using <code>size_t</code> everywhere instead of <code>unsigned long long</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:06:12.643", "Id": "79591", "Score": "0", "body": "vector does support unsigned long long. at least on visual studio." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:33:05.467", "Id": "79632", "Score": "0", "body": "ULONGLONG means 64-bit on a Windows 32-bit machine. When you say that \"`vector` does support `unsigned long long`\" is that on 32-bit or 64-bit windows? Have you tried it with a number bigger than 2<sup>32</sup>? Don't you agree that `size_t` (or `vector::size_type`) is the only type that `vector` really supports as a constructor parameter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T19:35:12.917", "Id": "79682", "Score": "0", "body": "64 bit windows... 2^32 is larger than the amount of ram than my system has. I have exactly 4GB of memory." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:23:44.353", "Id": "45559", "ParentId": "45550", "Score": "1" } } ]
{ "AcceptedAnswerId": "45555", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:18:14.313", "Id": "45550", "Score": "8", "Tags": [ "c++", "primes" ], "Title": "Prime generator from one to n" }
45550
<p>I am just starting to get my feet wet with C; and am rather enjoying myself in doing so. This is sort of a follow up to my last question <a href="https://codereview.stackexchange.com/questions/45284/enumerating-a-boolean-in-c">here</a>. I am posting this ordinate to hopefully getting some feedback on the logic itself, and possibly also some feedback on coding style. I do, however insist on making everything explicit. I'm not a huge fan of implicit <em>anything</em>... Maybe that's something I need to get over?</p> <pre><code>#include &lt;stdio.h&gt; typedef enum { false = (int) 0, true = (int) 1 } bool; inline void set_bit(register unsigned int *x, register const unsigned short int offset, register const bool value) { if (value) *x |= (1 &lt;&lt; offset); else *x &amp;= ~(1 &lt;&lt; offset); } inline bool get_bit(register const unsigned int x, register const unsigned short int offset) { return (x &amp; (1 &lt;&lt; offset)) != 0; } int main(void) { unsigned int x = 0; int count; for (count = 0; count &lt; 8; count += 2) set_bit(&amp;x, count, true); for (count = 7; count &gt;= 0; count--) printf("%d ", (int) get_bit(x, count)); printf("\n"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:28:08.840", "Id": "79528", "Score": "8", "body": "If you want bools, consider using the real `bool` datatype. `#include <stdbool.h>`" } ]
[ { "body": "<p>Drop the <code>inline</code> and <code>register</code> keywords. The compiler will decide what to do better than you can, despite your personal preference for complete mastery over the machine.</p>\n\n<p>Keep in mind that the default compiler optimization setting is set at <code>-O0</code>. For this answer to work properly, you should also set your minimum compiler optimization level to <code>-O3</code> (if you haven't already).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:22:34.607", "Id": "45563", "ParentId": "45551", "Score": "9" } }, { "body": "<p><code>value</code> is not a useful name for a <code>bool</code> variable; it sounds more like it's holding a number rather than a condition. Do you mean for it to be something like <code>isBitValue</code>?</p>\n\n<p>If by explicit, you mean defining your own <code>bool</code> type, then that may be okay for a toy program in C. Otherwise, you should use <code>&lt;stdbool.h&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:10:15.173", "Id": "79496", "Score": "1", "body": "Maybe `bitValue`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:35:43.527", "Id": "45564", "ParentId": "45551", "Score": "7" } }, { "body": "<p>I think <code>set_bit</code> might be better as:</p>\n\n<pre><code>unsigned set_bit(unsigned x, unsigned offset, bool value)\n{\n return (value)\n ? x | (1 &lt;&lt; offset)\n : x &amp; ~(1 &lt;&lt; offset);\n}\n</code></pre>\n\n<p>I'm not sure why I think so; my reasons are:</p>\n\n<ul>\n<li>It's closer to the macros I used to see for doing this kind of thing</li>\n<li>Pointers can be abused (e.g. you could pass a null pointer into your version)</li>\n<li>The compiler might find it easier to optimize (e.g. because taking the address of a local variable and passing it to a subroutine might make the compiler worry about <a href=\"http://en.wikipedia.org/wiki/Pointer_aliasing\">aliasing</a>).</li>\n</ul>\n\n<hr>\n\n<p>You might get better performance by defining separate functions named <code>set_bit</code> and <code>clear_bit</code> (OTOH your compiler might optimize away the difference when you pass a hard-coded <code>value</code> to your <code>set_bit</code>).</p>\n\n<hr>\n\n<p>I don't think that <code>short</code> adds any value to the <code>offset</code> parameter; shorts are often less efficient performance-wise; and even a short value is too long for your needs (you probably want <code>offset</code> to have a value from 0 through 31 or 63).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:57:25.720", "Id": "45568", "ParentId": "45551", "Score": "10" } }, { "body": "<p>Here is a branchless implementation of the <code>set_bit</code> function:</p>\n\n<pre><code>return x &amp; ~(1 &lt;&lt; offset) | (value &lt;&lt; offset);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T17:08:38.903", "Id": "79664", "Score": "0", "body": "You have a missing parenthesis. Should be `(x & ~(1 << offset))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T17:28:41.907", "Id": "79667", "Score": "0", "body": "Fixed, thanks. As `&` has precedence over `|`, parenthesis are optional." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:19:04.383", "Id": "45606", "ParentId": "45551", "Score": "4" } }, { "body": "<blockquote>\n <p>I do, however insist on making everything explicit. I'm not a huge fan of implicit anything... Maybe that's something I need to get over?</p>\n</blockquote>\n\n<p>No, that is very good practice and a good habit. Particularly, there are many dangerous, implicit type promotions going on in C, that explicit type casts can prevent.</p>\n\n<p>However, if you want to be explicit, you must actually have quite a deep understanding of what's going on between the C lines. Until you do, you will end up causing more problems than you solve with this coding practice. Also, you do a couple of pointless things that only clutter down the code.</p>\n\n<hr>\n\n<p>Here are my comments on your code:</p>\n\n<ul>\n<li>Do not define your own bool type. Instead use the standard <code>bool</code> type in stdint.h.</li>\n<li><code>(int) 0</code> This cast is pointless and adds nothing of value. Integer literals are always of the type <code>int</code>. Enumeration constants are also always of the type <code>int</code>.</li>\n<li><code>register</code> is an obsolete keyword from the dark ages, when compilers were worthless at optimizing code. Today, a modern compiler does a much better job at optimizing the code than you do, so let it do its job. Also, the <code>register</code> keyword causes various side-effects: for example you can't take the address of a register variable. So never use <code>register</code>, because there is never a reason to do so. That keyword just remains in the language for backwards compatibility.</li>\n<li>Similarly, it is often best to let the compiler handle inlining in most cases. Because while inlining makes the code faster, it also makes the executable much larger. The compiler is likely better than you at determining when to optimize for size and when to optimize for speed.</li>\n<li>Always use <code>{}</code> after each statement, even if there is only one line of code following it. Skipping <code>{}</code> is dangerous practice that almost certainly leads to bugs sooner or later.</li>\n<li><p>You want to be explicit but miss a few cases where it actually matters. </p>\n\n<ul>\n<li><p><code>1 &lt;&lt; offset</code> means that you do left shift on a signed integer. Assuming 32 bit integers, the case of <code>1 &lt;&lt; 31</code> leads to undefined behavior. Generally, in 99.9% of the cases it doesn't make any sense whatsoever to use bitwise operators on signed integers. If you wish to write safe code, be explicit and type <code>1u &lt;&lt; offset</code>.</p></li>\n<li><p>Because of the above, <code>*x |= (1 &lt;&lt; offset);</code> implicitly stores an <code>int</code> into an <code>unsigned int</code>, which is potentially dangerous in some cases.</p></li>\n<li><p>And also because of the above, you apply <code>~</code> to a signed int, which is always dangerous practice.</p></li>\n<li><p>You have no function declarations, only definitions. You also don't declare the local functions as <code>static</code>, which is proper practice for functions that are private to the specific module.</p></li>\n</ul></li>\n<li><p>As others have commented, naming a bool \"value\" and using it to store values is confusing. <code>uint8_t</code> would have been a more suitable type to use in this case.</p></li>\n<li><p>In general, it is always better to use the types from stdint.h when you do bit manipulations.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T00:56:14.283", "Id": "79722", "Score": "0", "body": "\"Always use {} after each statement\" --> \"Always use {} after each *part of a branching* statement\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T01:25:41.630", "Id": "79726", "Score": "0", "body": "Also, i don't understand *others have commented, naming a bool \"value\" and using it to store values is confusing. uint8_t would have been a more suitable*. I understood Jamal's advice, but not your's." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T05:34:07.893", "Id": "79736", "Score": "1", "body": "\"Integer literals are always of the type int.\" I think depends on range. When `int` is 32 bits, 5000000000 is likely a `long long` and not an `int`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T06:29:02.340", "Id": "79933", "Score": "0", "body": "@martinf Regarding {}: after every if, else, else if, for, while, do-while and switch statement. Regarding the bool value: bit-wise arithmetic is usually done with integers. If you want to tell a function to set a bit to 1 or 0, it makes more sense to pass a 1 or 0 than true/false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T06:42:32.357", "Id": "79935", "Score": "1", "body": "@chux Indeed. They can even be of unsigned type in case of hex or octal literals." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:10:30.453", "Id": "45610", "ParentId": "45551", "Score": "13" } } ]
{ "AcceptedAnswerId": "45610", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T22:35:17.420", "Id": "45551", "Score": "22", "Tags": [ "c", "beginner", "bitwise" ], "Title": "Setting and getting bits in C" }
45551
<p>Using LaTeX creates a bunch of auxiliary files like <code>foo.aux</code>, <code>foo.log</code>, etc. Sometimes, I want to create a clean run of my document. I usually manually execute this in the terminal as</p> <pre><code>$ ls foo* foo.tex foo.aux foo.log foo.bbl foo-blx.bib $ rm foo{.aux,.log,.bbl,-blx.bib} </code></pre> <p>This works fine. However, it is error-prone and I don't want to accidentally erase my <code>.tex</code> file. So I added this function to my <code>~/.bashrc</code>:</p> <pre><code># Delete all non-TeX files # invoke as: cleantex foo # where: foo.tex, foo.aux, foo.log, etc. are files in directory cleantex () { if [ -n "$1"]; then name = $(basename -s ".tex" "$1") rm -f $name{.!(*tex),-blx.bib} fi } </code></pre> <p>My question is about the key line</p> <pre><code>rm -f $name{.!(*tex),-blx.bib} </code></pre> <p>that actually executes the script.</p> <p>Is this line well-written? What might I improve here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:22:46.237", "Id": "79480", "Score": "0", "body": "Which `basename` are you using? I am not familiar with (and can't find) the `-s` option for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:26:57.867", "Id": "79482", "Score": "0", "body": "I'm on Linux Mint 16 with GNU coreutils 8.20. My `man basename` has the option, as does the [official documentation](https://www.gnu.org/software/coreutils/manual/html_node/basename-invocation.html#basename-invocation). Is your distribution out of date?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:27:20.080", "Id": "79483", "Score": "0", "body": "Essentially that fragment just trims the `.tex` suffix if there is one. So, `cleantex foo` is the same as `cleantex foo.tex`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:31:36.947", "Id": "79485", "Score": "0", "body": "That option is not available on RHEL 6.4, Ubuntu 12.04 LTS ... which itself may be a problem. (I work in an 'enterprise'). Also, the basenames I have all will work that way without the -s option `basename foo.tex .tex` will produce `foo`. Food for thought" } ]
[ { "body": "<p>Mostly minor things:</p>\n\n<ul>\n<li><code>[ -n \"$1\" ]</code> is equivalent to <code>[ \"$1\" ]</code>. I'd go for the shorter one</li>\n<li>Since you are in <code>bash</code>, you can use a variable substitution <code>${1%.tex}</code> instead of <code>basename</code>, which is slightly better</li>\n<li>There cannot be spaces around the <code>=</code> sign in assignments: <code>name = val</code> is incorrect, should be <code>name=val</code></li>\n<li>As @rolfl suggested in his answer, it would be better to check if a <code>tex</code> file exists before deleting anything</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>cleantex () {\n if [ \"$1\" ]; then\n name=${1%.tex}\n test -f $name.tex || return 1\n rm -f $name{.!(*tex),-blx.bib}\n fi \n}\n</code></pre>\n\n<p>Some extra remarks:</p>\n\n<ul>\n<li>I would add the <code>-v</code> flag for the <code>rm</code>, so that it will print what it actually removed: <code>rm -vf $name{.!(*tex),-blx.bib}</code></li>\n<li>I guess you will never create <code>.tex</code> files with spaces in the name. If you ever do, you'll need to quote <code>$name</code>, for example: <code>rm -f \"$name\"{.!(*tex),-blx.bib}</code></li>\n<li>I would drop the <code>-f</code> flag from <code>rm</code>. Sure, there will be some error messages that way when there's nothing to delete, but I don't see that as a bad thing.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:51:44.827", "Id": "45560", "ParentId": "45556", "Score": "5" } }, { "body": "<p>My real concerns with the script are:</p>\n\n<ul>\n<li><code>cleantex path/to/file.tex</code> will not delete files in that path, but in the current directory.</li>\n<li>you should check the actual .tex file exists before you delete all the things around it.</li>\n<li>the brace-expansion is unnecessarily complicated...... especially when combined with the extended glob <code>!(*tex)</code>. I would manually resolve the brace-expansion so that there is only one complicated operation on that line.</li>\n<li>I would use actual glob-expansion and only delete existing files.... and not use the -f option on rm (which does more than just suppress the error message if files do not exist....)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:57:04.487", "Id": "45561", "ParentId": "45556", "Score": "6" } } ]
{ "AcceptedAnswerId": "45561", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:05:23.873", "Id": "45556", "Score": "11", "Tags": [ "bash", "cli" ], "Title": "Bash script to clear files not matching a given extension" }
45556
<p>This is my very first program that using threads. I use C++11 standard threads and I run it on Linux.</p> <p>The program creates two threads that sums all the elements in a vector together. The first created thread sums the left half of the vector and the other thread sums the right part of the vector.</p> <p>The main thread runs until both are done, adds the two sums together and then print the sum.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;thread&gt; void adder( const std::vector&lt;int&gt; &amp; v, int begin, int end, int &amp; result) { for( ; begin &lt; end; ++begin ) { result = result + v.at( begin ); } } int main() { int sum_left = 0; int sum_right = 0; std::vector&lt;int&gt; v( 100000000,1); //100 millions int v_size = v.size(); std::thread t1( adder, v, 0,v_size/2 , std::ref(sum_left) ); std::thread t2( adder, v, v_size/2, v_size, std::ref(sum_right) ); t1.join(); t2.join(); int sum_total = sum_left + sum_right; std::cout &lt;&lt; sum_total &lt;&lt; '\n'; return 0; } </code></pre>
[]
[ { "body": "<p>Firstly, it's a good first attempt at writing some threaded code. The major sticking point is that you're passing in an <code>int &amp;</code> and returning <code>void</code>. Of course, <code>std::thread</code> will just run some code and won't return you a result. However, within the C++11 threading library, there are a number of things you can use that will allow you to return results, instead of having to use <code>std::ref</code> and reference parameters.</p>\n\n<p>Before tackling that, let's look at the <code>adder</code> function itself. I'm going to go through a sequence of improvements that can be made to it. Firstly, you should try and use the correct type to index into a <code>std::vector</code>:</p>\n\n<pre><code>using size_type = std::vector&lt;int&gt;::size_type;\n\nint adder( const std::vector&lt;int&gt; &amp; v, size_type begin, size_type end)\n{\n for( ; begin &lt; end; ++begin )\n {\n result = result + v.at( begin );\n }\n}\n</code></pre>\n\n<p>This is ok, but it could be a lot more generic: What if the values aren't stored in a <code>std::vector</code>? Instead, template this so that it can use anything that supports an iterator concept:</p>\n\n<pre><code>template &lt;typename Iterator&gt;\nint adder(Iterator begin, Iterator end)\n{\n int result = 0;\n for(auto it = begin; it != end; ++it) {\n result += *it;\n }\n return result;\n}\n</code></pre>\n\n<p>Ok, getting there, but we can still improve this quite a bit: what if we want to sum any kind of numeric type? (Note this will require an <code>#include &lt;iterator&gt;</code>):</p>\n\n<pre><code>template &lt;typename Iterator&gt;\nstd::iterator_traits&lt;Iterator&gt;::value_type \nadder(Iterator begin, Iterator end)\n{\n std::iterator_traits&lt;Iterator&gt;::value_type result;\n for(auto it = begin; it != end; ++it) {\n result += *it;\n }\n return result;\n}\n</code></pre>\n\n<p>Ok, so we're not locked into a <code>vector</code> or an <code>int</code> type anymore. However, this pattern of summing up a bunch of values is really common, and there is library functionality that takes care of it for us: <code>std::accumulate</code> (note that this needs an <code>#include &lt;algorithm&gt;</code>):</p>\n\n<pre><code>template &lt;typename Iterator&gt;\ntypename std::iterator_traits&lt;Iterator&gt;::value_type\nadder(Iterator begin, Iterator end)\n{\n using T = typename std::iterator_traits&lt;Iterator&gt;::value_type;\n return std::accumulate(begin, end, T());\n}\n</code></pre>\n\n<p>Now for the threading part.</p>\n\n<p>The C++11 threading library has a really handy function called <code>std::async</code>. This allows you to run some piece of code in a thread, and retrieve a result from it. It will give you back what is known as a <code>std::future</code> (note that this needs an <code>#include &lt;future&gt;</code>):</p>\n\n<pre><code>template &lt;typename Iterator&gt;\ntypename std::iterator_traits&lt;Iterator&gt;::value_type\nparallel_sum(Iterator begin, Iterator end)\n{\n using T = typename std::iterator_traits&lt;Iterator&gt;::value_type;\n auto midpoint = begin + std::distance(begin, end) / 2;\n std::future&lt;T&gt; f1 = std::async(std::launch::async, adder&lt;Iterator&gt;, begin, midpoint);\n std::future&lt;T&gt; f2 = std::async(std::launch::async, adder&lt;Iterator&gt;, midpoint, end);\n return f1.get() + f2.get();\n}\n</code></pre>\n\n<p>We then use this as follows:</p>\n\n<pre><code>int main()\n{\n std::vector&lt;int&gt; v;\n for(int i = 0; i &lt; 100000; ++i) {\n v.push_back(i);\n }\n int total = parallel_sum(v.begin(), v.end());\n std::cout &lt;&lt; total &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>There's probably too much to absorb here in one go, but I'll break down the main points:</p>\n\n<ul>\n<li>Try and make your functions work with the facilities provided by the standard library. Iterators permeate the container/algorithm side of it - if you can, try and work with iterators instead of directly with containers.</li>\n<li>Look for functionality in the standard library that can help you with common tasks, such as <code>std::accumulate</code>.</li>\n<li>With threading, if you want to get results back, prefer to use <code>std::async</code> instead of passing parameters by reference to store results.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:16:52.513", "Id": "79536", "Score": "1", "body": "I love this review, it is comprehensive and easy to read :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:18:06.667", "Id": "79537", "Score": "2", "body": "However, if I'm not mistaken, you can drop the calls to `std::future<>::wait` since the method `get` should already call `wait`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:43:00.877", "Id": "79557", "Score": "0", "body": "@Morwenn Yep, you're right. Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-07T21:35:29.367", "Id": "377638", "Score": "0", "body": "Very nice review. There is so much to learn in this. thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-17T20:34:36.777", "Id": "389011", "Score": "0", "body": "This was an excellent primer on C++ threading optimization. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T23:21:07.703", "Id": "394701", "Score": "0", "body": "I just love this code review so much. I keep coming back to it. :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:02:45.447", "Id": "45569", "ParentId": "45557", "Score": "22" } } ]
{ "AcceptedAnswerId": "45569", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:23:22.007", "Id": "45557", "Score": "16", "Tags": [ "c++", "c++11", "multithreading" ], "Title": "Summing values in a vector using threads" }
45557
<p>I would like the program to ask the user if they want to add a color. If they say yes, then ask what color to add. Then after that happens, once the program would ask if you want to, run it again. If they say no to add a color, the program ask if you want to remove a color from the list. If they say yes, it would then ask what color to remove, with error handling built in if the color wasn't in that list. Then after that happens once the program would ask if you want to run it again.</p> <p>Just wanted to point out I do not know a lot about Python, so please don't be harsh, but I can take constructive criticism.</p> <pre><code>import socket # imports the socket module import sys # imports the sys module import console # imports the console module usr = raw_input('What is your name? \n').title() # asks for users name for the hostname information sname = socket.gethostname() # sets sname to gethostname print '\nThis program is being run by', usr, 'on machine name', sname # displays host information mylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange'] # sets mylist to colors templist = list(mylist) # sets templist as mylist runagain = 'y' # sets runagain to a y values while runagain == 'y': # for looping print '\nThe current colors are:', templist # print out list so user knows what colors are already there clradd = raw_input('\nWould you like to add any colors to the list? y or n\n') while clradd == 'y': colors = raw_input('\nWhat colors would you like to add to the list? Please type one color. \n').title() templist.append(colors) # appends color to the list print templist # prints out new list print '\nAscending and Descending' # print out ascending and descending lists print '-' * 30 print '\nAscending (high to low): ', sorted(templist, reverse=True) print '\nDescending (low to high): ', sorted(templist, reverse=False) clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n') while clradd == 'n': clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n') while clrdel == 'y': try: removecolor = raw_input('\nWhat colors would you like to remove? ').title() # asks user color to remove templist.remove(removecolor) # removes color from the list except ValueError: print 'Looks like that color was not in the list, try again.' continue print 'Updated list\n', templist # prints out updated list runagain = raw_input('\nWould you like to run this program again again? y or n') if runagain == 'n': # if runagain is n console.hide_output() # hide the output while clrdel == 'n': runagain = raw_input('\nWould you like to run this program again again? y or n') # asks user to run again if runagain == 'n': # if runagain is n console.hide_output() # hide the output sys.exit() # stops the program </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T18:31:47.033", "Id": "79791", "Score": "1", "body": "This post is now unlocked but is being monitored by moderators. Please do not make edits that invalidate current answers. See [this meta post for instructions on how to edit your post after it has been reviewed](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers)" } ]
[ { "body": "<blockquote>\n<pre><code>import socket # imports the socket module \n</code></pre>\n</blockquote>\n\n<p>The comment is completely pointless. But I cannot help it, my eyes naturally read it, my brain processes it, only to realize it says nothing new. Let your code speak for itself, avoid comments as much possible.</p>\n\n<blockquote>\n<pre><code>print '\\nThis program is being run by', usr, 'on machine name', sname\n</code></pre>\n</blockquote>\n\n<p>Maybe it's somewhat more readable if you use standard Python formatting like this instead:</p>\n\n<pre><code>print '\\nThis program is being run by %s on machine name %s' % (usr, sname)\n</code></pre>\n\n<blockquote>\n<pre><code>runagain = 'y'\n</code></pre>\n</blockquote>\n\n<p>Instead of setting this to a string, and later using <code>== 'y'</code> to evaluate, it would be better to use proper booleans for this kind of thing. For example:</p>\n\n<p>Similarly, instead of:</p>\n\n<blockquote>\n<pre><code>clradd = raw_input('\\nWould you like to add any colors to the list? y or n\\n')\n\nwhile clradd == 'y':\n</code></pre>\n</blockquote>\n\n<p>You could write like this:</p>\n\n<pre><code>clradd = raw_input('\\nWould you like to add any colors to the list? y or n\\n') == 'y'\n\nwhile clradd == 'y':\n</code></pre>\n\n<p>Try-catch block writing style:</p>\n\n<pre><code>try:\n removecolor = raw_input('\\nWhat colors would you like to remove? ').title()\n templist.remove(removecolor)\nexcept ValueError:\n print 'Looks like that color was not in the list, try again.'\n continue \n</code></pre>\n\n<p>It's better to keep the <code>try</code> block as small as possible. For example, the <code>removecolor</code> assignment should be moved out from it. Also, since you simply want to check if the given color is in the list of colors, it would be cleaner to write that exactly:</p>\n\n<pre><code>removecolor = raw_input('\\nWhat colors would you like to remove? ').title()\nif removecolor in templist:\n templist.remove(removecolor)\nelse:\n print 'Looks like that color was not in the list, try again.'\n continue\n</code></pre>\n\n<p>There are couple of other things too, globally:</p>\n\n<ul>\n<li>Incorrectly indented code</li>\n<li>Incorrectly using <code>while</code> instead of a simple <code>if</code></li>\n<li>Duplicated code blocks</li>\n<li><code>sys.exit</code> is a bit harsh way to exit, try to avoid if possible</li>\n</ul>\n\n<h3>Suggested implementation</h3>\n\n<p>Putting the above suggestions together:</p>\n\n<pre><code>import socket\n\nusr = raw_input('What is your name?\\n').title()\nsname = socket.gethostname()\nprint '\\nThis program is being run by %s on machine name %s' % (usr, sname)\n\nmylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange']\ntemplist = list(mylist)\nrunagain = True\n\nwhile runagain:\n print '\\nThe current colors are:', templist\n\n clradd = raw_input('\\nWould you like to add any colors to the list? y or n\\n') == 'y'\n\n if clradd:\n colors = raw_input('\\nWhat colors would you like to add to the list? Please type one color. \\n').title()\n templist.append(colors)\n\n print templist\n print '\\nAscending and Descending'\n print '-' * 30\n print '\\nAscending (high to low): ', sorted(templist, reverse=True)\n print '\\nDescending (low to high): ', sorted(templist, reverse=False)\n\n clrdel = raw_input('\\nWould you like to remove any colors from the list? y or n\\n') == 'y'\n\n while clrdel:\n removecolor = raw_input('\\nWhat colors would you like to remove? ').title()\n if removecolor in templist:\n templist.remove(removecolor)\n else:\n print 'Looks like that color was not in the list, try again.'\n continue\n\n print 'Updated list\\n', templist\n break\n\n runagain = raw_input('\\nWould you like to run this program again again? y or n\\n') == 'y'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:50:45.250", "Id": "79492", "Score": "0", "body": "thanks for your help, since I'm only a beginner. My teacher makes me comment almost every line, thats why import socket was commented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:54:59.200", "Id": "79493", "Score": "0", "body": "@TjF You only need comments when it's hard to understand code from a quick glance. If you're not sure when to comment - you can try having one comment per logical block of code - briefly describing what the following block is doing: `# Repeatedly asking a user for color until he/she gets it right`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:57:01.877", "Id": "79494", "Score": "0", "body": "@RuslanOsipov I actually knew that myself, but my teacher asks as part of every assignment that each line of code to be commented." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:47:47.167", "Id": "45565", "ParentId": "45562", "Score": "7" } }, { "body": "<p>Your code is a bit hard to read due to you not following PEP8. Also, your comments are explicitly verbose - they don't have to duplicate the code. And in your case you need very few comments explaining what is happening overall. You can get a more thorough functional code review if you fix the style and edit the question - right now it is quite hard to edit and understand what is going on due to module not having descriptive variable naming and overall descriptive comments. </p>\n\n<pre><code>import socket # imports the socket module \nimport sys # imports the sys module\nimport console # imports the console module \n</code></pre>\n\n<p>You don't need comments there. Also, it's good to organize imports alphabetically. See PEP8 section: <a href=\"http://legacy.python.org/dev/peps/pep-0008/#id16\" rel=\"nofollow\">http://legacy.python.org/dev/peps/pep-0008/#id16</a>.</p>\n\n<pre><code>usr = raw_input('What is your name? \\n').title() # asks for users name for the hostname information\n</code></pre>\n\n<p>Limit line lengths to 80 characters (applies to all the code below as well). No need for a comment here, it also adds ambiguity. Is it a hostname or a name input? Rename <code>usr</code> to <code>user</code> - cropping one letter out does not help readability.</p>\n\n<pre><code>sname = socket.gethostname() # sets sname to gethostname\n</code></pre>\n\n<p>Again, no need for a comment is needed here. Everywhere below you do not need comments since you are duplicating your code in English. More descriptive variable name as <code>host_name</code> would be good as well.</p>\n\n<pre><code>runagain = 'y' # sets runagain to a y values\n</code></pre>\n\n<p>No comment is needed. Variable naming convention is <code>lowercase_with_underscores</code>. So <code>run_again</code> is a better name. Also, <code>True</code> is a better value here.</p>\n\n<pre><code>while runagain == 'y': # for looping\nprint '\\nThe current colors are:', templist # print out list so user knows what colors are already there\n</code></pre>\n\n<p>Indent second line. Otherwise it'll throw an error.</p>\n\n<pre><code>clradd = raw_input('\\nWould you like to add any colors to the list? y or n\\n')\n</code></pre>\n\n<p>Better variable naming. Try <code>color_add</code> or <code>add_color</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:51:29.077", "Id": "45566", "ParentId": "45562", "Score": "4" } } ]
{ "AcceptedAnswerId": "45565", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T23:58:41.910", "Id": "45562", "Score": "4", "Tags": [ "python", "homework" ], "Title": "Adding/Removing Colors to Lists" }
45562
<p>Grab the input file, and output the second to last word on every line.</p> <p>Can I make it shorter and/or more efficient? I'm surprised by the performance. While the runtime, +2s, is likely dominated by start up, it also requires +40M. </p> <pre><code>(use 'clojure.java.io) (use '[clojure.string :only (join split)]) (with-open [rdr (reader (first *command-line-args*))] (doseq [line (line-seq rdr)] (println (nth (split line #" ") (- (count (split line #" ")) 2))))) </code></pre>
[]
[ { "body": "<p>Are you using Lein to run? Or straight Java? Either way, I think the memory use is normal even for a hello world program. </p>\n\n<p>Following are some naive timings (I didn't run them many times). Here is my baseline hello world (uses about 30M). My computer is quite slow btw :):</p>\n\n<blockquote>\n<pre><code>C:\\george\\test\\secondtolast&gt;timemem cmd /c lein run\nHelloooooooooo world.\nExit code : 0\nElapsed time : 8.31\nKernel time : 0.03 (0.4%)\nUser time : 0.03 (0.4%)\npage fault # : 762\nWorking set : 2864 KB\nPaged pool : 69 KB\nNon-paged pool : 2 KB\nPage file size : 2088 KB\n</code></pre>\n</blockquote>\n\n<p>Next is a baseline with my working corpus (Paradise Lost, 11404 lines of text and about 500 kb). I just output the first line (uses about 30M):</p>\n\n<blockquote>\n<pre><code>C:\\george\\test\\secondtolast&gt;timemem cmd /c lein run\n?The Project Gutenberg EBook of Paradise Lost, by John Milton\nExit code : 0\nElapsed time : 8.45\nKernel time : 0.11 (1.3%)\nUser time : 0.03 (0.4%)\npage fault # : 762\nWorking set : 2864 KB\nPaged pool : 69 KB\nNon-paged pool : 2 KB\nPage file size : 2088 KB\n</code></pre>\n</blockquote>\n\n<p>As you can see the time doesn't change much. Here is your program (about same memory):</p>\n\n<blockquote>\n<pre><code>[11k+ lines of output]\nExit code : 0\nElapsed time : 10.98\nKernel time : 0.05 (0.4%)\nUser time : 0.02 (0.1%)\npage fault # : 762\nWorking set : 2864 KB\nPaged pool : 69 KB\nNon-paged pool : 2 KB\nPage file size : 2088 KB\n</code></pre>\n</blockquote>\n\n<p>A little more time but not much. Finally here is a little different version of that code (about same memory):</p>\n\n<blockquote>\n<pre><code>Exit code : 0\nElapsed time : 9.13\nKernel time : 0.13 (1.4%)\nUser time : 0.02 (0.2%)\npage fault # : 762\nWorking set : 2864 KB\nPaged pool : 69 KB\nNon-paged pool : 2 KB\nPage file size : 2088 KB\n</code></pre>\n</blockquote>\n\n<p>I'm not convinced it's actually faster (it would need many more trials), I think really it is about the same. But maybe you can think about using subvec (<a href=\"http://clojuredocs.org/clojure_core/clojure.core/subvec\" rel=\"nofollow\">http://clojuredocs.org/clojure_core/clojure.core/subvec</a> ) or something similar. Nth is O(n), while subvec is O(1), though in reality these are not very long lines. </p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(ns secondtolast.core\n (require [clojure.java.io :as io]\n [clojure.string :refer [join split]])\n (:gen-class))\n\n\n(defn -main\n \"I don't do a whole lot ... yet.\"\n []\n (with-open [rdr (io/reader \"pg20.txt\")]\n (doseq [line (line-seq rdr)]\n (let [words (split line #\" \")\n c (count words)]\n (if-not (or (empty? line) (= 1 c))\n (println (last (subvec words 0 (- c 1))))\n line)))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T18:24:22.723", "Id": "80190", "Score": "1", "body": "Nth is only O(n) when used on a list (they are just linked lists) but when nth is used on a vector it is actually O(logn) where the log base is 32. In true big-O the base just disappears, but in practice having a log base of 32 pretty much makes nth a O(1) call. I would guess that since you are able to use subvec (which only works on vectors), the cost of calling nth would not be O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-30T10:30:36.963", "Id": "90140", "Score": "1", "body": "@jjcomer Quite. It's not the [`subvec`](http://clojuredocs.org/clojure_core/clojure.core/subvec) that's taking the time; it's the [`last`](http://clojuredocs.org/clojure_core/clojure.core/last), which is linear in the length of its argument. So replace `(last (subvec words 0 (- c 1)))` with `(nth words (- c 2))`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:47:33.770", "Id": "45578", "ParentId": "45567", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T00:52:17.517", "Id": "45567", "Score": "5", "Tags": [ "clojure" ], "Title": "Second to last word" }
45567
<p>For the past week I have been studying and improving a ray tracer that I ported from JavaScript. The bare finished port was only exactly what was written in JavaScript and rendered at around 20fps at 100x100 resolution with a scene of just one plane and two spheres, over the week I have implemented very simple frustum culling (although it doesn't help as nothing is occluded currently), I reduced the number of new objects created per ray by making the Color and Vector class more instance-based and multi-threaded the whole render job which has improved it to around 85fps.</p> <p>While improving the code, debugging and benchmarking it i found that simply five math functions can impact the whole render in the end by 20ms! So as I do not understand the ins-and-outs of all the mathematical functions, I would appreciate any improvements that could be made highly.</p> <pre><code>private static Color traceRay(Scene scene, Raycast job, Ray ray, int depth) { if (depth &gt;= maxRays) return job.sumColor; RaycastReport intersections = intersectScene(scene, ray); if (intersections == null) // Stop tracing if no hit return Color.voidColor; if (depth == 0) job.objdistance += intersections.distance; job.hits = depth; Color hitcolor = shade(job, intersections, scene, depth); job.sumColor.add(hitcolor); return hitcolor; } private static float testRay(Scene scene, Ray ray) { RaycastReport intersection = intersectScene(scene, ray); if (intersection == null) return -1; return intersection.distance; } private static RaycastReport intersectScene(Scene scene, Ray ray) { float closest = Float.POSITIVE_INFINITY; RaycastReport closestobject = null; for (RenderObject object : scene.objects) { RaycastReport intersection = object.intersect(ray); if (intersection != null &amp;&amp; intersection.distance &lt; closest) { closestobject = intersection; closest = intersection.distance; } } return closestobject; } private static Color shade(Raycast job, RaycastReport report, Scene scene, int depth) { Vector direction = report.ray.direction; Vector pos = Vector.add(Vector.multiply(report.distance, direction), report.ray.position); job.hitPositions[depth] = pos; Vector normal = report.object.getNormal(pos); direction.subtract(Vector.multiply(2, Vector.multiply(Vector.dot(normal, direction), normal))); Color naturalcolor = light(scene, report.object, pos, normal, direction); Color reflectedcolor = getReflectionColor(job, scene, report.object, pos, normal, direction, depth); return Color.add(naturalcolor, reflectedcolor); } private static Color light(Scene scene, RenderObject hitobject, Vector hitpos, Vector normal, Vector reflectdirection) { // Rename Color col = Color.defaultcolor; for (Light light : scene.lights) { Vector ldis = Vector.subtract(light.position, hitpos), livec = Vector.normal(ldis); float hitlight = testRay(scene, new Ray(hitpos, livec)); boolean isinshadow = (hitlight == -1) ? false : (hitlight &lt;= Vector.distance(ldis)); if (isinshadow) continue; float illum = Vector.dot(livec, normal); Color lcolor = (illum &gt; 0) ? Color.scale(illum, light.color) : Color.defaultcolor; float specular = Vector.dot(livec, Vector.normal(reflectdirection)); Color scolor = (specular &gt; 0) ? Color.scale((float)Math.pow(specular, hitobject.material.roughness), light.color) : Color.defaultcolor; lcolor.multiply(hitobject.material.diffuseColor(hitpos)); scolor.multiply(hitobject.material.specularColor(hitpos)); lcolor.add(scolor); col = Color.add(col, lcolor); } return col; } private static Color getReflectionColor(Raycast job, Scene scene, RenderObject object, Vector pos, Vector normal, Vector reflectdirection, int depth) { float reflectivity = object.material.reflectivity(pos); if (reflectivity == 0) return Color.black; return Color.scale(reflectivity, traceRay(scene, job, new Ray(pos, reflectdirection), depth+1)); } </code></pre> <h2>Edit:</h2> <pre><code>public abstract class RenderObject { public Material material; public RenderObject(Material mat) { material = mat; } public abstract Vector getNormal(Vector pos); public abstract RaycastReport intersect(Ray ray); } </code></pre> <p>Raycast class contains useful general information about a rays journey as it was reflected such as distance, number of reflections and positions hit.<br> RaycastReport class is used to send data about the last raycast around more cleanly.<br> depth is used to limit the recursion that reflective objects use.<br></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:46:23.813", "Id": "84686", "Score": "0", "body": "Try to follow some style guides like [Google Java style guide](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html), it will make your code more readable and will guide you with some best practices." } ]
[ { "body": "<p><strong>Let your code breathe</strong><br>\nYour code is very hard to read - lines are long and crowded together, containing multiple method nesting (<code>direction.subtract(Vector.multiply(2, Vector.multiply(Vector.dot(normal,...</code>). </p>\n\n<p>Reading code is like reading a book. If you don't give the reader some breathing room (a period, coma, paragraph) - your reader will get lost, and might abandon the book altogether. </p>\n\n<p>You should consider adding a few blank lines to make the structure of your methods more apparent, for example:</p>\n\n<pre><code>private static Color traceRay(Scene scene, Raycast job, Ray ray, int depth) {\n if (depth &gt;= maxRays) return job.sumColor;\n\n RaycastReport intersections = intersectScene(scene, ray);\n if (intersections == null) // Stop tracing if no hit\n return Color.voidColor;\n\n if (depth == 0) job.objdistance += intersections.distance;\n\n job.hits = depth;\n Color hitcolor = shade(job, intersections, scene, depth);\n job.sumColor.add(hitcolor);\n return hitcolor;\n}\n</code></pre>\n\n<p>You should also consider extracting some of the hard computational lines to helper methods, and name them so that the reader will better understand your code:</p>\n\n<pre><code>private static Vector travel(Vector startPosition, Vector direction, float distance) {\n Vector travelPath = Vector.multiply(distance, direction)\n return Vector.add(travelPath, startPosition);\n}\n</code></pre>\n\n<p><strong>Variable Naming</strong><br>\nAlso hindering readability is your choice to use an alllower variable naming convention. <code>naturalColor</code> is much more readable than <code>naturalcolor</code>, all the more so <code>isInShadow</code> vs. <code>isinshadow</code>. </p>\n\n<p>You also tend to use lazy shortcuts like <code>ldis</code>, <code>livec</code>, <code>lcolor</code>, <code>illum</code>, etc. which might seem meaningful to you, but to an outside reader the names might be less helpful.</p>\n\n<p><strong>Something must be missing...</strong></p>\n\n<blockquote>\n<pre><code>for (Object object : scene.objects) {\n RaycastReport intersection = object.intersect(ray);\n</code></pre>\n</blockquote>\n\n<p>How does your <code>object</code> intersect with <code>ray</code>? As far as I know, there is no such method on <code>Object</code>... It is quite hard to calculate complexity of code, if we can't know how this intersection happens, especially since it happens within a polynomial iteration (<code>lights</code>*<code>objects</code>) in <code>testRay</code>, and within a recursion in <code>traceRay</code>.</p>\n\n<p><strong>Caching?</strong><br>\nIf the complexity of <code>intersect</code> is a constant, your complexity would be \\$O(maxRays \\cdot objects \\cdot lights)\\$ (I'm counting your <code>Vector</code> operations' complexity as constant), this might not be ideal. </p>\n\n<p>I've got lost in all the recursion and iteration loop you have there, but might there be a way to cache some of the calculations? Would it help you to \"remember\" distances between your <code>scene</code> (which does not change during your calculations), and your <code>ray</code>s, and reuse them as you go along? This might lower your effective complexity, and make your code run a lot faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:08:03.103", "Id": "79619", "Score": "0", "body": "If I where to cut up the lines into many variables, surely that would only make it more messy, I wouldn't know what to name them either, as I said, I don't understand the mathematics much, I was hoping someone here would. I have added my Object class (which I've now named more appropriately to RenderObject), meanwhile, I will fix the \"lazy\" names and space things out. Have you got any suggestions on how I could go about caching even though the camera moves?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:37:54.140", "Id": "79634", "Score": "0", "body": "I suggested that you add _blank_ lines, so your code won't look like a big kludge of code. Making a few iterations of method extractions (like the one in my example), will make _you_ understand the code better. Unfortunately, I'm not actively familiar with vector optics, and I can't tell you how you could effectively cache these results... Perhaps debug some results, and try to see if you get similar/identical calculations over and over, and cache those results..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:24:15.177", "Id": "45590", "ParentId": "45573", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:22:59.050", "Id": "45573", "Score": "6", "Tags": [ "java", "performance", "recursion", "graphics", "raytracing" ], "Title": "Ray Tracer main loop" }
45573
<p>I have a class called <code>Mailer</code> which has some properties like this </p> <pre><code>public static string Cname { get { return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"])); } set { HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"])); } } </code></pre> <p>I am inheriting this property from another class called <code>EventRegistrationReplyMail</code> like this</p> <pre><code>public class EventRegistrationReplyMail :Mailer </code></pre> <p>and using <code>Cname</code> property inside this class. I doubt whether this is the correct way of doing things or not. I am just a beginner in OOP concepts, so please spare me if I am doing anything completely stupid.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:29:58.953", "Id": "79532", "Score": "0", "body": "Perhaps you could show more of the code like where you are using this and other surrounding code modules???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:53:01.353", "Id": "79645", "Score": "1", "body": "Don't use the word \"[efficiency](http://en.wikipedia.org/wiki/Algorithmic_efficiency)\" to refer to things that have nothing to do with efficiency." } ]
[ { "body": "<p><strong>Accessors in C#</strong><br>\nYou should read on <a href=\"http://msdn.microsoft.com/en-us/library/aa287786%28v=vs.71%29.aspx\">accessors in C#</a> - your setter does not do what it should - it should <em>set</em> the value if <code>Cname</code>. If this has no meaning (you can't change the value of <code>Cname</code> - you should drop the <code>set</code> altogether.<br>\nCorrect use of accessors:</p>\n\n<pre><code>public string Name \n{\n get \n { \n return name; \n }\n set \n {\n name = value; \n }\n}\n</code></pre>\n\n<p>For read only properties:</p>\n\n<pre><code>public static string Cname\n{\n get\n {\n return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request[\"cname\"]));\n }\n}\n</code></pre>\n\n<p><strong>Inheritance and static members</strong><br>\nYou are asking about efficiency in inheriting properties. I don't know what do you mean by \"efficiently inheriting\", but static members are not really <a href=\"http://channel9.msdn.com/forums/TechOff/250972-Static-Inheritance/\">inherited</a>, you simply get some allowance from calling them in the inherited class...</p>\n\n<blockquote>\n <p>Inheritance in .NET works only on instance base. Static methods are\n defined on the type level not on the instance level. That is why\n overriding doesn't work with static methods/properties/events...</p>\n</blockquote>\n\n<p><strong>Use of properties</strong><br>\nWhen using properties, you imply <em>state</em> of the object you are writing the property on (in this case - <code>Mailer</code> class). From looking at your code, it does not look like its the class's <em>state</em>, but rather a calculation made.<br>\nA better choice would be to write it as a utility method, which makes it clear that you are calculating something in it:</p>\n\n<pre><code>public static string ExtractCNameFromCurrentRequest() {\n return HttpUtility.HtmlDecode(\n HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request[\"cname\"]));\n}\n</code></pre>\n\n<p>Or you could use an <a href=\"http://msdn.microsoft.com/en-us//library/bb383977.aspx\">extension method</a>, which will result in a cool usage syntax, and make clear from where you are extracting the <code>CName</code>:</p>\n\n<pre><code>public static class HttpContextExtension {\n public static string GetCName(this HttpContext context) {\n return HttpUtility.HtmlDecode(context.Server.UrlDecode(context.Request[\"cname\"]));\n }\n}\n</code></pre>\n\n<p>And its usage will be:</p>\n\n<pre><code>string cname = HttpContext.Current.GetCName();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T08:29:09.657", "Id": "45587", "ParentId": "45577", "Score": "8" } }, { "body": "<p>@UriAgassi made very good points, I'm just going to add a few thoughts:</p>\n\n<ul>\n<li>In the context of a <code>Mailer</code> class, the name <code>Cname</code> isn't absolutely clear. One of the benefits of <em>encapsulation</em>, is the possibility for <em>abstraction</em> - the code that uses a <code>Mailer</code> object doesn't need to know/care that the HTTP context has a value called \"cname\". <code>ContactName</code> is probably a much more meaningful name.</li>\n</ul>\n\n<blockquote>\n <p><em>I am inheriting this property from another class called <code>EventRegistrationReplyMail</code></em></p>\n</blockquote>\n\n<p>You're not, it's the other way around: the <code>EventRegistrationReplyMail</code> class is inheriting this property from its base class <code>Mailer</code>.</p>\n\n<hr>\n\n<p>What you have here isn't a property, it's a <em>method in disguise</em> (see <a href=\"https://stackoverflow.com/a/601648/1188513\">this StackOverflow answer</a> for more info); properties should be simple and straightforward, and shouldn't throw exceptions - methods are <em>actions</em>, properties are <em>data</em>.</p>\n\n<p>Like Uri Agassi, what I'd recomment you have here instead, is a method - this way if any exception is thrown, it will be less surprising (<a href=\"http://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">POLS</a>) than if it were a property.</p>\n\n<p>Lastly, I'd also recommend separating what's going on in that one-liner, so as to reduce the number of method calls in a single instruction, which increases readability and can make the code self-explanatory with good variable naming:</p>\n\n<pre><code>public string DecodeCNameFromQueryString()\n{\n var encodedName = HttpContext.Current.Request[\"cname\"];\n var decodedName = HttpContext.Current.Server.UrlDecode(encodedName);\n return HttpUtility.HtmlDecode(decodedName);\n}\n</code></pre>\n\n<p>Per <a href=\"https://stackoverflow.com/a/1812486/1188513\">Difference between UrlEncode and HtmlEncode</a>, I don't think you actually need to make both calls - perhaps you could test whether this returns the same value:</p>\n\n<pre><code>public string DecodeCNameFromQueryString()\n{\n var encodedName = HttpContext.Current.Request[\"cname\"];\n return HttpContext.Current.Server.UrlDecode(encodedName);\n}\n</code></pre>\n\n<p>And then I'm guessing your <code>HttpContext.Current.Request</code> would have other query string parameters, so you'd probably be better off with a more generic method that takes a <code>string</code> parameter representing the query string parameter:</p>\n\n<pre><code>public string DecodeQueryStringParameterValue(string parameterName)\n{\n var encodedName = HttpContext.Current.Request[parameterName];\n return HttpContext.Current.Server.UrlDecode(encodedName);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T22:41:35.733", "Id": "45658", "ParentId": "45577", "Score": "3" } } ]
{ "AcceptedAnswerId": "45587", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T05:43:45.990", "Id": "45577", "Score": "3", "Tags": [ "c#", "asp.net", "inheritance" ], "Title": "Using properties efficiently in inheritance" }
45577
<p>I wrote a utility method to override <code>equals()</code> using reflection. This works fine, but I wonder if this code will pass all the tests.</p> <pre><code>public static boolean checkObjectsEqualityFromInstance(Object currentObj,Object otherObj) throws Exception{ if(currentObj==null || otherObj==null){ return false; } else if(otherObj.getClass()!=null&amp;&amp;currentObj.getClass()!=null&amp;&amp;!currentObj.getClass().isInstance(otherObj)){ return false; } boolean result =true; Field[] fields = otherObj.getClass().getDeclaredFields(); Field[] currentObjFields = currentObj.getClass().getDeclaredFields(); Map&lt;String, Object&gt; attriButeNameValueMap=null; /*This map to store *property name and its value of any of object in my calse the otherObj */ try { attriButeNameValueMap=new HashMap&lt;&gt;(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(otherObj); attriButeNameValueMap.put(field.getName(), value); } for (Field field : currentObjFields) { field.setAccessible(true); Object value = field.get(currentObj); if(attriButeNameValueMap.containsKey(field.getName())){ if(value instanceof Boolean){ result=areEqual((Boolean)value, (Boolean)attriButeNameValueMap.get(field.getName())); } else if(value instanceof Character){ result=result&amp;&amp;areEqual((Character)value, (Character)attriButeNameValueMap.get(field.getName())); } else if(value instanceof Long){ result=result&amp;&amp;areEqual((Long)value, (Long)attriButeNameValueMap.get(field.getName())); } else if(value instanceof Float){ result=result&amp;&amp;areEqual((Float)value, (Float)attriButeNameValueMap.get(field.getName())); } else if(value instanceof Double){ result=result&amp;&amp;areEqual((Double)value, (Double)attriButeNameValueMap.get(field.getName())); } else if(value instanceof Object[]){ result=result&amp;&amp; Arrays.equals((Object[])value, (Object[])attriButeNameValueMap.get(field.getName())); } else{ result=result&amp;&amp;areEqual(value, attriButeNameValueMap.get(field.getName())); } if(!result){ return result; } } else{ return false; } } } catch (IllegalArgumentException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } return result; } </code></pre> <p>The <code>areEqual()</code> methods are overloaded for different types.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:57:21.523", "Id": "79546", "Score": "1", "body": "This code doesn't deal properly with fields that are arrays of primitives." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:33:06.377", "Id": "79553", "Score": "1", "body": "There is no need for a special case for box classes like `Boolean`, `Character`, `Double`... they can simply be treated the same as Object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:35:53.433", "Id": "79579", "Score": "0", "body": "I agree thanks.... i am waiting for more comments so that i can remember points for future, when i code again :)" } ]
[ { "body": "<ol>\n<li><p>You should check if the references are equal first to save a whole lot of comparing when there is no need to.</p></li>\n<li><p>If both objects are <code>null</code> your method will return false which is probably unexpected.</p></li>\n<li><p>You call <code>getClass()</code> several times on these objects - It should only be called once for each object and then stored in a local variable.</p></li>\n<li><p>There is a typo in <code>attriButeNameValueMap</code> - should be <code>attributeNameValueMap</code></p></li>\n<li><p>You call <code>field.getName()</code> several times - again just call once per loop and store in a local variable.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:21:03.477", "Id": "45583", "ParentId": "45579", "Score": "7" } }, { "body": "<ol>\n<li><p>It ignores values in superclasses. You might want to check that too.</p>\n\n<p>Anyway, don't reinvent the weel, <strong>there is a library for that!</strong> I guess <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/builder/EqualsBuilder.html#reflectionEquals%28java.lang.Object,%20java.lang.Object,%20boolean%29\" rel=\"nofollow noreferrer\"><code>EqualsBuilder.reflectionEquals</code></a> from <a href=\"http://commons.apache.org/proper/commons-lang/\" rel=\"nofollow noreferrer\">Apache Commons Lang</a> does exactly what you want. It also has solutions to corner cases, like </p>\n\n<ul>\n<li>transient fields (since they are likely derived fields, and not part of the value of the Object) in a configurable way</li>\n<li><a href=\"https://stackoverflow.com/q/7484210/843804\">generated fields with <code>$</code> (for inner classes)</a>.</li>\n</ul>\n\n<p>You can also exclude field names from the comparison.</p>\n\n<p>It's open-source, you can check the <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/src-html/org/apache/commons/lang3/builder/EqualsBuilder.html#line.324\" rel=\"nofollow noreferrer\">source for further details</a>.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>The <code>else</code> keyword is unnecessary here:</p>\n\n<pre><code>if(currentObj==null || otherObj==null){\n return false;\n}\nelse if(otherObj.getClass()!=null&amp;&amp;currentObj.getClass()!=null&amp;&amp;!currentObj.getClass().isInstance(otherObj)){\n return false;\n}\n</code></pre>\n\n<p>The following is the same:</p>\n\n<pre><code>if (currentObj == null || otherObj == null){\n return false;\n}\nif (otherObj.getClass() != null &amp;&amp; currentObj.getClass() != null &amp;&amp; \n !currentObj.getClass().isInstance(otherObj)) {\n return false;\n}\n</code></pre>\n\n<p>It's called <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">guard clause</a>. I've also used a little bit more spacing to make it readable (easier separaton of values, comparisons, method calls).</p></li>\n<li><p>Guard clauses would make this easier to follow too:</p>\n\n<blockquote>\n<pre><code> if(value instanceof Boolean){\n result=areEqual((Boolean)value, (Boolean)attriButeNameValueMap.get(field.getName()));\n }\n else if(value instanceof Character){\n result=result&amp;&amp;areEqual((Character)value, (Character)attriButeNameValueMap.get(field.getName()));\n }\n else if(value instanceof Long){\n result=result&amp;&amp;areEqual((Long)value, (Long)attriButeNameValueMap.get(field.getName()));\n }\n ...\n if(!result){\n return result;\n }\n</code></pre>\n</blockquote>\n\n<p>I've used a few exaplanatory variable to remove some duplication:</p>\n\n<pre><code>Object value = field.get(currentObj);\nString fieldName = field.getName();\nif(attriButeNameValueMap.containsKey(fieldName)){\n Object otherFieldValue = attriButeNameValueMap.get(fieldName);\n if (value instanceof Boolean) {\n if (!areEqual((Boolean) value, (Boolean) otherFieldValue)) {\n return false;\n }\n } \n if (value instanceof Character) {\n if (!areEqual((Character) value, (Character) otherFieldValue)) {\n return false;\n }\n }\n</code></pre>\n\n<p>Note that it makes superfluous the <code>result</code> variable. The last line of the method could be simply the following, since its never modified anymore:</p>\n\n<blockquote>\n<pre><code>return true;\n</code></pre>\n</blockquote></li>\n<li><p>Formatting is not consistent. Indentation sometimes is two spaces, sometimes four.</p></li>\n<li><blockquote>\n<pre><code> Map&lt;String, Object&gt; attriButeNameValueMap=null; \n /*This map to store *property name and its value of any of object in my calse the otherObj */\n try {\n attriButeNameValueMap=new HashMap&lt;&gt;();\n</code></pre>\n</blockquote>\n\n<p><code>B</code> should be lowercase in the variable name (I guess it's just a typo) and you could declare it inside the <code>try</code> block:</p>\n\n<p>I'd also rename it to <code>otherObjectAttributeValues</code> to make the comment unnecessary:</p>\n\n<pre><code>try {\n Map&lt;String, Object&gt; otherObjectAttributeValues = new HashMap&lt;&gt;();\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Consistent formatting would be great here too:</p>\n\n<blockquote>\n<pre><code> } catch (IllegalArgumentException | IllegalAccessException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n throw e;\n }\n</code></pre>\n</blockquote>\n\n<p>Furthermore, <code>TODO</code> comments does not suggest professional work. Fix that and remove the comment.</p>\n\n<p>I'd throw out the <code>IllegalAccessException</code> or wrap it into a <code>RuntimeException</code>. The IllegalArgumentException already a <code>RuntimeException</code>, so you don't have to put it into the method signature.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T17:46:26.597", "Id": "79782", "Score": "1", "body": "I really liked the way you reviewed my code and commented on each mistake.This was nice experience for me on this site ... :) thanks bro." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T20:26:02.720", "Id": "79799", "Score": "0", "body": "@khushnood: You're welcome! I'm happy that you found it helpful :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T22:14:19.213", "Id": "79804", "Score": "1", "body": "@khushnood: One more thing: If you like the site help [graduating](http://meta.codereview.stackexchange.com/q/1572/7076). I'm quite sure that you can find other useful questions and answers on the site to [vote on](http://meta.codereview.stackexchange.com/q/612/7076)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:21:17.740", "Id": "45584", "ParentId": "45579", "Score": "8" } } ]
{ "AcceptedAnswerId": "45584", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:17:42.030", "Id": "45579", "Score": "10", "Tags": [ "java", "reflection", "hashcode" ], "Title": "Override equals() and hashCode() using reflection" }
45579
<p>I've noticed I've got quite a few repeated lines in my code.</p> <pre><code>$start = mktime(0, 0, 0, 3, 1, 2014); $rate = 1 / 30; $amount = number_format(floor((time() - $start) * $rate)); $id = array( array("42706686", "rebel2america"), array("100004055720670", "marquez.candace"), array("100000756492404", "vince.goode.3"), array("100007763585373", "laura.allen.75491"), ); // 70% chance of red an 30% of green $status = array( array("red", "no"), array("red", "no"), array("red", "no"), array("red", "no"), array("red", "no"), array("red", "no"), array("red", "no"), array("green", "yes"), array("green", "yes"), array("green", "yes") ); $online = range(7, 21); // create and assign a 'seed' value that changes // every $duration and assign to mt_srand $duration = 5; $mins = date('i', strtotime('now')); $seed = $mins - ($mins % $duration); mt_srand($seed); // use mt_rand to build an 'order by' // array that will change every $duration $orderBy = array_map(function() { return mt_rand(); }, range(1, count($id))); // sort $ids against $orderBy array_multisort($orderBy, $id); $orderBy = array_map(function() { return mt_rand(); }, range(1, count($status))); array_multisort($orderBy, $status); $orderBy = array_map(function() { return mt_rand(); }, range(1, count($online))); array_multisort($orderBy, $online); for($i = 0; $i &lt; 10; $i++) { $results1 = array_pop($id); $results2 = array_pop($status); echo " &lt;td&gt;{$results1[0]}&lt;/td&gt;\n"; echo " &lt;td&gt;{$results1[1]}&lt;/td&gt;\n"; echo " &lt;td&gt;&lt;span class=\"{$results2[0]}\"&gt;{$results2[1]}&lt;/span&gt;&lt;/td&gt;\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:35:20.287", "Id": "79530", "Score": "0", "body": "you are effectively writting a lot of loops complex - - can you please put it the input ouput of your algorithm so that we can see if we can shorten the code by known what to expect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:09:52.963", "Id": "79531", "Score": "3", "body": "Could you please also state what this code does? That should especially be in the title." } ]
[ { "body": "<p>This part is duplicated:</p>\n\n<blockquote>\n<pre><code>$orderBy = array_map(function() {\n return mt_rand();\n}, range(1, count($id)));\narray_multisort($orderBy, $id);\n</code></pre>\n</blockquote>\n\n<p>You apply the same logic to <code>$id</code>, <code>$status</code>, <code>$online</code>.</p>\n\n<p>To eliminate duplication, you can move this common logic to a function with one parameter:</p>\n\n<pre><code>function reorder(&amp;$arr) {\n $orderBy = array_map(function() {\n return mt_rand();\n }, range(1, count($arr)));\n array_multisort($orderBy, $arr);\n}\nreorder($id);\nreorder($status);\nreorder($online);\n</code></pre>\n\n<p>Note that we pass the array by reference (<code>&amp;$arr</code>), because <code>array_multisort</code> does the same, and modifies the content of the array anyway.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>As other answers and comments have pointed out, you could also eliminate the magic numbers and duplication when creating the <code>$status</code> array, for example like this:</p>\n\n<pre><code>$color1 = array(\"red\", \"no\");\n$color2 = array(\"green\", \"yes\");\n$num_color1 = 7;\n$num_color2 = 3;\n$status = array_fill(0, $num_color1, $color1)\n + array_fill($num_color1, $num_color2, $color2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:17:25.840", "Id": "45582", "ParentId": "45581", "Score": "11" } }, { "body": "<p>Extract some constants:</p>\n\n<p>replace</p>\n\n<pre><code>// 70% chance of red an 30% of green\n$status = array(\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"red\", \"no\"),\n array(\"green\", \"yes\"),\n array(\"green\", \"yes\"),\n array(\"green\", \"yes\")\n);\n</code></pre>\n\n<p>by:</p>\n\n<pre><code>// 70% chance of red an 30% of green\n$red = array(\"red\", \"no\");\n$green = array(\"green\", \"yes\");\n$status = array($red, $red, $red, $red, $red, $red, $red, $green, $green, $green);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:28:43.627", "Id": "79539", "Score": "3", "body": "The above code can be further re factored by avoiding [magic numbers](http://c2.com/cgi/wiki?MagicNumber) i.e. you can use a constant like: `define(\"COLOR_RED\", \"red\")` and then use this constant identifier in you code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:50:14.980", "Id": "79542", "Score": "3", "body": "This could be even more elegant with array_fill: http://www.php.net/manual/en/function.array-fill.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T09:54:34.730", "Id": "79545", "Score": "0", "body": "@vivekpoddar: I am not a php programmer. You are right defining `$red = array(\"red\", \"no\");` (and also `$green`) as a constant would be an improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T10:29:17.573", "Id": "79552", "Score": "1", "body": "@MrSmith42: I am not php programmer too ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:39:27.140", "Id": "79608", "Score": "0", "body": "@vivekpoddar: If you're going to use constants, they should have less specific names. What happens when i want `COLOR_RED` to be `\"blue\"` instead? :P (And if that will never ever change, why constify it?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T05:36:29.893", "Id": "79931", "Score": "1", "body": "A better approach would be to use a enum and use color names as a constants there. That way you can manage that as a single source of information about colors and hence keep your code dry." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T07:56:35.983", "Id": "45585", "ParentId": "45581", "Score": "10" } }, { "body": "<p>I'm assuming you want your script to output a list of user ids, usernames, and online status. Each user has a 30% chance of being online and the list changes randomly every 5 minutes. If I'm wrong about any of that please correct me.</p>\n\n<p>These lines of code don't affect the output.</p>\n\n<pre><code>$start = mktime(0, 0, 0, 3, 1, 2014);\n$rate = 1 / 30;\n$amount = number_format(floor((time() - $start) * $rate));\n\n$online = range(7, 21);\n\n$orderBy = array_map(function() {\n return mt_rand();\n}, range(1, count($online)));\narray_multisort($orderBy, $online);\n</code></pre>\n\n<ul>\n<li>Your seed changes every five minutes, but loops every hour. This gives you just 12 possible seeds.</li>\n<li>For the online status, inside your loop generate a true/false value that has a certain probability of being true. This requires fewer lines of code and the maximum number of ids is not limited by the size of your status array.</li>\n<li>Use $i as an index to the array rather than poping elements.</li>\n<li>Don't print extra white space with your HTML, unless you have a specific reason for doing so.</li>\n</ul>\n\n<p>The modified code:</p>\n\n<pre><code>// 30% chance of being online\n$ONLINE_PROB = 0.3;\n\n// create and assign a 'seed' value that changes \n// every $DURATION seconds and assign to mt_srand\n$DURATION = 5*60;\nmt_srand(floor(time()/$DURATION));\n\n$id = array(\n array(\"42706686\", \"rebel2america\"),\n array(\"100004055720670\", \"marquez.candace\"),\n array(\"100000756492404\", \"vince.goode.3\"),\n array(\"100007763585373\", \"laura.allen.75491\"),\n);\n// randomly shuffle $id\n$orderBy = array_map(function(){return mt_rand();},range(1,count($id)));\narray_multisort($orderBy,$id);\n\nfor($i=0; $i&lt;count($id); ++$i)\n{\n echo \"&lt;td&gt;{$id[$i][0]}&lt;/td&gt;&lt;td&gt;{$id[$i][1]}&lt;/td&gt;\";\n if(mt_rand()/mt_getrandmax() &lt;= $ONLINE_PROB)\n echo \"&lt;td&gt;&lt;span class=\\\"green\\\"&gt;yes&lt;/span&gt;&lt;/td&gt;\";\n else\n echo \"&lt;td&gt;&lt;span class=\\\"red\\\"&gt;no&lt;/span&gt;&lt;/td&gt;\";\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T08:55:32.117", "Id": "45589", "ParentId": "45581", "Score": "7" } } ]
{ "AcceptedAnswerId": "45582", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T06:29:41.253", "Id": "45581", "Score": "2", "Tags": [ "php", "php5" ], "Title": "Any simpler and more efficient way of writing this code?" }
45581
<p>I've got a piece of code that takes an element, checks where it is, and if it's beyond a set place in the viewport, make the opacity increase to 1. I've made the code so that it only runs the checks if they're needed, the problem is that the code looks atrocious, and I suspect there's a better way for me to be doing it.</p> <pre><code>var $wheresThisAt = viewportHeight*4; if (scrolled &gt; ($wheresThisAt)) { //there has to bve a better way... $('.salafoot').css('opacity', '0'); $('#salamander-1').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+20)){ $('#salamander-2').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+40)){ $('#salamander-3').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+60)){ $('#salamander-4').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+80)){ $('#salamander-5').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+100)){ $('#salamander-6').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+120)){ $('#salamander-7').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+140)){ $('#salamander-8').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+160)){ $('#salamander-9').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+180)){ $('#salamander-10').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+200)){ $('#salamander-11').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+220)){ $('#salamander-12').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+240)){ $('#salamander-13').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+260)){ $('#salamander-14').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+280)){ $('#salamander-15').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+300)){ $('#salamander-16').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+320)){ $('#salamander-17').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+340)){ $('#salamander-18').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+360)){ $('#salamander-19').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+380)){ $('#salamander-20').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+400)){ $('#salamander-21').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+420)){ $('#salamander-22').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+440)){ $('#salamander-23').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+460)){ $('#salamander-24').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+480)){ $('#salamander-25').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+500)){ $('#salamander-26').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+520)){ $('#salamander-27').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+540)){ $('#salamander-28').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+560)){ $('#salamander-29').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+580)){ $('#salamander-30').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+600)){ $('#salamander-31').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+620)){ $('#salamander-32').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+640)){ $('#salamander-33').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+660)){ $('#salamander-34').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+680)){ $('#salamander-35').css('opacity', '1'); if (scrolled &gt; (($wheresThisAt)+700)){ $('#salamander-36').css('opacity', '1'); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} // close all if statements before if (scrolled &gt; ($wheresThisAt)) } // end if (scrolled &gt; ($wheresThisAt)) </code></pre> <p>Here's a sample of the HTML that's being affected by the code</p> <pre><code>&lt;div class="salafoot" id="salamander-8" style="opacity: 0;"&gt;&lt;/div&gt; </code></pre> <p>As you can see I reuse almost identical code a lot of times, and if I want to change the number of steps (say to 37) I need to add another line. The if statements all get left open until the end, so that it only runs the check on the next line if it's useful (only checks +40 if the +20 has already been approved). All of the <code>#salamander-(n)</code> IDs are tied to the <code>.salafoot</code> class. The expected output is footprints that appear one at a time as you scroll down the page.</p>
[]
[ { "body": "<p>Gah! Thanks for coming here.</p>\n\n<p>Essentially, all your if-statements have the following structure:</p>\n\n<pre><code>if (scrolled &gt; (($wheresThisAt)+(N * 20))){\n $('#salamander-(N + 1)').css('opacity', '1');\n</code></pre>\n\n<p>So we can comfortably roll that into a loop:</p>\n\n<pre><code>for (var i = 0; i &lt; 35; i++) {\n if (scrolled &lt;= ($wheresThisAt + i * 20)) {\n break;\n }\n $(\"#salamander-\" + (i + 1)).css('opacity', '1');\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:43:26.977", "Id": "79563", "Score": "2", "body": "That's some terrible abuse of `break` and `if`, not to mention you can do it without an `if` structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:47:09.520", "Id": "79565", "Score": "0", "body": "@Kvothe quite popular in `while(true)` applications though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:03:39.583", "Id": "79569", "Score": "4", "body": "@Kvothe: Isn't that a guard clause? http://blog.codinghorror.com/flattening-arrow-code/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:14:42.263", "Id": "79571", "Score": "0", "body": "@palacsint Then it should really have been used in the `if`'s conditional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:15:38.687", "Id": "79572", "Score": "4", "body": "@Kvothe (1) I see nothing wrong with `break`. While I'd personally prefer functional programming, JS is at its heart an imperative language. (2) I see no “terrible abuse” of anything in my code, except maybe magic numbers. (3) It was intended as a simple refactoring of the original code – I applied the rule “three or more: use a `for`”, and swapped `>` for `<=` with an “early `return`“, except that `return` is a `break` in the context of a loop. I decided not to use excessive cleverness which does make the `if` unnecessary. I don't quite understand your criticism." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:25:03.230", "Id": "79574", "Score": "0", "body": "@amon Right. I just dislike breaking out of `if` loops. It's a bad practice imo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:34:22.803", "Id": "79578", "Score": "7", "body": "@Kvothe bad practice? I don't think so. Of course the alternative would be `for (var i = 0; i < 35 && scrolled > ($wheresThisAt + i * 20); i++)`, but that's far less readable. The way I wrote it in my answer makes it clear that we are primarily iterating `i` over `0`–`35`, and that we'll stop once we've scrolled too far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:44:07.213", "Id": "79609", "Score": "2", "body": "Passion abound this morning! Not abuse in my mind, but I would still have reversed the condition and put the `.css()` in the `if` block. Easier to grok that way." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:25:18.090", "Id": "45597", "ParentId": "45596", "Score": "17" } }, { "body": "<pre><code>var top = Math.max(Math.min(Math.ceil((scrolled-$wheresThisAt)/20),35),1); \n\nfor (var i = 1; i &lt; top; i++) {\n $('#salamander-' + i).css('opacity', '1');\n}\n</code></pre>\n\n<p>This is similar to Amon's answer, but avoids the <code>if</code> structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:08:44.717", "Id": "79592", "Score": "10", "body": "That long combination of `Math.max`, `Math.min`, `Math.ceil` *on the same line* I don't like. Otherwise a good approach. Using some additional variables would help make that long line more readable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:28:26.483", "Id": "45598", "ParentId": "45596", "Score": "12" } }, { "body": "<p>You could easily loop over the element names...</p>\n\n<pre><code>for (var i = 2; i &lt;= 36; ++i) {\n if (scrolled &gt; ($wheresThisAt + (i-1)*20)) {\n $('#salamander-' + i).css('opacity', 1);\n }\n else break;\n}\n</code></pre>\n\n<p>But if they're all defined sequentially in the page as i'm assuming they are, you could assign them a CSS class and then say something like</p>\n\n<pre><code>var shownCount = Math.max(Math.floor((scrolled - $wheresThisAt) / 20), 0) + 1;\n$('.theirClass').slice(0, shownCount).css('opacity', 1);\n</code></pre>\n\n<p>and avoid the loop altogether (on your end, anyway).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:44:40.953", "Id": "79564", "Score": "1", "body": "`else break;`, what...? Change the conditional of an `if` loop, `break` is just a glorified `goto`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:47:15.490", "Id": "79566", "Score": "1", "body": "@Kvothe: Yeah. there's actually a bunch of nested `if` statements. :P It's not strictly necessary to skip to the end, but that's what the code it's replacing is basically doing. And there's no good reason to keep looping, or to go through the contortions required to satisfy the anti-`break` cargo cultists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:28:57.917", "Id": "79577", "Score": "0", "body": "@cHao I'd call that premature optimization... this is only relevant when processing large sets of data, and ~40 items is definitely not a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:47:51.707", "Id": "79582", "Score": "4", "body": "@Kvothe - `break` is a glorified `GOTO`, in the same way that a `while` loop, `if` statement, and `for` loop are all also glorified `GOTO`. What sets them apart is the target of the jump.... not the source. `GOTO` is ugly because the target of the jump is unconstrained. `break` is great because the target of the jump is a well-defined and optimized code-point. See [what Knuth has to say about it](http://www.scribd.com/doc/38873257/Knuth-1974-Structured-Programming-With-Go-to-Statements), and realize that 'break' and 'continue' are the good kind of 'goto'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:33:47.003", "Id": "79598", "Score": "1", "body": "@Vogel612: I wasn't even talking about performance. If you know there won't be any more results, there's simply no good reason to continue. If you're continuing because you haven't realized that there's no further work to do, OK. But if you do realize it, and you're continuing solely to avoid a \"glorified `goto`\", that's boneheaded." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:42:50.443", "Id": "45599", "ParentId": "45596", "Score": "0" } }, { "body": "<p>You're already getting all the elements to set the initially opacity: <code>$('.salafoot').css('opacity', '0');</code></p>\n\n<p>You may as well set the opacity for each item so you're only going over them once (this assumes they are in sequential order).</p>\n\n<pre><code>$('.salafoot').css('opacity', function(i, elem){\n return scrolled &gt; $wheresThisAt+20*(1+i) ? '1' : '0';\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:38:20.827", "Id": "45616", "ParentId": "45596", "Score": "0" } }, { "body": "<p>I think @amon's and @Kvothe's solutions can be simplified a bit into something which is simple and readable at the same time:</p>\n\n<pre><code>var i = 0;\nwhile (i &lt; 35 &amp;&amp; $wheresThisAt + i * 20 &lt; scrolled) {\n $(\"#salamander-\" + (i + 1)).css('opacity', '1');\n i++;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:50:00.717", "Id": "45627", "ParentId": "45596", "Score": "0" } } ]
{ "AcceptedAnswerId": "45598", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T11:10:30.350", "Id": "45596", "Score": "15", "Tags": [ "javascript", "optimization", "jquery" ], "Title": "Increasing opacity based on an element's location" }
45596
<p>What would be the best way to format this code? It looks a bit messy to me in regards to indentation etc.</p> <pre><code> if (typeof _srwc != 'undefined') { for (var i=0; i &lt; _srwc.length; i++){ var currentArg = _srwc[i];; if (typeof window[currentArg[0]] == 'function') { window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]); } else { console.log('The Setter method: "' + currentArg[0] + '" is undefined'); } } } </code></pre>
[]
[ { "body": "<p>How to format code is not really how CodeReview works ;)</p>\n\n<ul>\n<li>You are indenting with 2 and with 4 spaces, pick one, I advocate 2</li>\n<li>It is more common to compare <code>_srwc</code> to <code>undefined</code> itself</li>\n<li><code>_srwc</code> is an unfortunate name, it conveys no meaning</li>\n<li><code>window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);</code> could use a comment block</li>\n<li>Do not use <code>console.log</code> in production code</li>\n<li><p>Also, read about <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"nofollow\"><code>apply</code></a>, it allows you to call a function and pass an array of arguments so you don't have to be limited to 3 arguments.</p>\n\n<pre><code>if (_srwc !== undefined) {\n for (var i=0; i &lt; _srwc.length; i++){\n var currentArg = _srwc[i];\n if (typeof window[currentArg[0]] == 'function') {\n window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);\n } else {\n console.log('The Setter method: \"' + currentArg[0] + '\" is undefined');\n }\n }\n} \n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:52:07.693", "Id": "79584", "Score": "2", "body": "2 spaces? Infidel! 4 spaces is the one true style for perfect legibility. Well, maybe we can compromise on three. And we can both agree that tabs are worse ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:54:42.060", "Id": "79587", "Score": "1", "body": "Agreed on tabs!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:27:14.240", "Id": "79603", "Score": "0", "body": "Philistines, the lot of you. Tabs forever!! :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T17:50:36.883", "Id": "79669", "Score": "0", "body": "\"It is more common to compare _srwc to undefined itself\" <-- well, that's *actually* true, but note that on older environments `undefined` was overridable, so checking `typeof` is a better choice IMHO - also note that *common* isn't ever *better* :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:45:15.193", "Id": "45602", "ParentId": "45601", "Score": "3" } }, { "body": "<p>Use <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clauses</a>, consistent indentation, some spaces around the operators and remove the double semicolon. You could also extract out an explanatory variable for <code>currentArg[0]</code> (which would remove some duplication and describe its content).</p>\n\n<pre><code>if (typeof _srwc == 'undefined') {\n return;\n}\nfor (var i = 0; i &lt; _srwc.length; i++) {\n var currentArg = _srwc[i];\n // TODO: just guessing, you might have a better name\n var methodName = currentArg[0]; \n if (typeof window[methodName] != 'function') {\n console.log('The Setter method: \"' + methodName + '\" is undefined');\n continue;\n }\n window[methodName](currentArg[1], currentArg[2], currentArg[3]);\n}\n</code></pre>\n\n<p>I suppose its a function or it could be extracted out to a function. Otherwise, the <code>return</code> won't be appropriate at the beginning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:53:09.120", "Id": "79585", "Score": "1", "body": "This could die without a `continue` in the `if (typeof window[currentArg[0]] != 'function') {` since you would be trying to execute `currentArg` without it being a function" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:48:55.553", "Id": "45604", "ParentId": "45601", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T12:33:49.617", "Id": "45601", "Score": "2", "Tags": [ "javascript" ], "Title": "How to format embedded if statements in JavaScript" }
45601
<p>Below I have two players that win or lose and their score fluctuates using the Elo function. I have adapted this code from something closer to my language which is ActionScript. I found <a href="http://jobemakar.wordpress.com/2007/05/18/why-the-elo-rating-system-rocks/" rel="nofollow noreferrer">the functions here</a>. It is an older example and I didn't really get the point of it. My code is in ColdFusion. The problem I have with the code was that it spins through a 'single player' and the player's score started to go down. In addition, the poster only accounted for one Player. Mine has two players.</p> <p>In coldfusion there is log10() but if I reverse things and plant a player2 victory it gives a divide by zero error so I am doing 10^. This may be wrong.</p> <p>To expand, how do I avoid a divide by zero on a result of -.42 using log10() while it works using 10^ ? Now, I have compensated using the if statement following the elo equation on the 'outcome' flag for playerone to get the 'result' to look like a score, but I could be generating the result wrong.</p> <p>This is my best interpretation of the Elo function in ColdFusion. If something is wrong or can be improved, let me know what it is and how I should fix it.</p> <pre><code>function determineRatingConstant(required numeric rating) { // Some rating contants depending strong or weak ratings. // Note I want the middle range wins to count higher // because players in that spectum would face higher competition // You might see this differntly or this could be var returnVal = 10; if (rating GT 2400) { returnVal = 50; } else if (rating GT 2300 AND rating LTE 2400) { returnVal = 40; } else if (rating GT 2200 AND rating LTE 2300) { returnVal = 30; } else if (rating GT 2100 AND rating LTE 2200) { returnVal = 20; } else if (rating GT 2000 AND rating LTE 2100) { returnVal = 10; } else { returnVal = 5; } return returnVal; } function calculateNewRating(required numeric player1Rating, required numeric player2Rating, required numeric player1Victory){ var outcome = 0; if (player1Victory) { outcome = 1; } // in coldfusion there is log10() but if I reverse things and plant a // player2 victory it gives a divide by zero error so I am doing 10^ // is this right? var expected_outcome = 1/(1+10^((player1Rating-player2Rating)/400)); var k = determineRatingConstant(player1Rating); var newrating = round(player1Rating+k*(outcome-expected_outcome)); // I am not sure I am doing this right but // there are sometimes decimals and negatives // I need to deal with... this could be unnecessary // because I could be doing it wrong in expected // outcome when I reverse things. if (outcome eq 0){ newrating = round(abs(newrating)); } return newrating; } // Here we call our functional stuff... // Ok I am creating a struct here and I am setting some starting variables // as you can see I have player two at an advantage. // I give player A the first win too. player = structNew(); player.rating1 = 2150; player.rating2 = 2200; // Lets run through 25 games and see the fate of your two players. // Also if marktWin eq 1 that is a win for Player1 for (i=0;i&lt;25;++i) { if ( i eq 0 ) { marktWin = 1; } else { marktWin = randrange(0,1); //you can comment this out to see player one have an unfair advantage } player.rating1 = calculateNewRating(player.rating1, player.rating2, (marktWin ? 1 : 0)); player.rating2 = calculateNewRating(player.rating2, player.rating1, (marktWin ? 0 : 1)); writeOutput("game " &amp; numberformat(i,'00')); //doing this to get a clean output writeOutput(" : " &amp; player.rating1 &amp; " | " &amp; player.rating2); // NOTE: inital player. struct values are overwritten writeOutput(" - Player 1:"); // below ternary operator funzies in Coldfusion writeOutput((marktWin ? " &lt;span style='color:blue'&gt;&lt;b&gt;won&lt;/b&gt;&lt;/span&gt;" : " &lt;span style='color:red'&gt;lost&lt;/span&gt;")); writeOutput("&lt;br&gt;"); } </code></pre> <p>Here is output of 25 games under normal conditions.</p> <p><img src="https://i.stack.imgur.com/tNMW0.png" alt="Normal Elo Output"></p> <p>And here is what happens when I let player one win every time.</p> <p><img src="https://i.stack.imgur.com/SDGcH.png" alt="enter image description here"></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:32:17.240", "Id": "45608", "Score": "4", "Tags": [ "algorithm", "coldfusion", "cfml" ], "Title": "Calculating player ratings" }
45608
<p>I am not very familiar with JavaScript and I'am a little confused with the object oriented peculiarities of it. I am trying to create a Caesar shift using the concepts of objects, methods and properties in JavaScript. I am using an HTML form to take input from user and OnClick return the encoded cipher text to user. This is what I have. I'm pretty much sure about my logic but I guess my object creation and method calls fall through. Am I doing it right?</p> <pre><code>&lt;head&gt; &lt;script&gt; function Caesar(order){ this.order = order; this.encode = encode; function encode(input){ this.output = ''; for (var i = 0; i &lt; input.length; i++) { var this.c = input.charCodeAt(i); if (this.c &gt;= 65 &amp;&amp; this.c &lt;= 90) this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65); // Uppercase else if (this.c &gt;= 97 &amp;&amp; this.c &lt;= 122) this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97); // Lowercase else this.output += input.charAt(i); } return answer.innerHTML= output; } &lt;/script&gt;&lt;/head&gt; &lt;body&gt; &lt;form&gt; Enter Plaintext : &lt;input type = "text" name = "plaintext" id = "plaintext"&gt; Enter Shift: &lt;input type = "text" name = "shift" id = "shift"&gt;&lt;br&gt; --How do I get the input from here and create my caesar object and pass the constructor the shift from this text box? &lt;input type="button" value="Encode" onclick ="encode()"&gt; --How do I call the encode() method with input from the plaintext text box? &lt;/form&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:11:45.923", "Id": "79599", "Score": "0", "body": "Welcome! Does your code works ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:28:23.280", "Id": "79604", "Score": "0", "body": "The encode function works independently. However, it doesn't run when I try calling it as a method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:58:11.987", "Id": "79647", "Score": "0", "body": "Welcome to Code Review! It seems like you have misunderstood what this site is about. We help with improving the cleanliness of existing, working code. We are not the site to ask for help in fixing or changing *what* your code does. We love helping people do the same thing in a cleaner way!" } ]
[ { "body": "<p>Your code is reviewable, even if it does not work, from a once over:</p>\n\n<ul>\n<li><p>Indent your code (!!), this is bad:</p>\n\n<pre><code>function Caesar(order){\nthis.order = order;\nthis.encode = encode;\nfunction encode(input){\nthis.output = '';\nfor (var i = 0; i &lt; input.length; i++) {\nvar this.c = input.charCodeAt(i);\nif (this.c &gt;= 65 &amp;&amp; this.c &lt;= 90) this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65); // Uppercase\nelse if (this.c &gt;= 97 &amp;&amp; this.c &lt;= 122) this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97); // Lowercase\nelse this.output += input.charAt(i); \n}\nreturn answer.innerHTML= output;\n } \n</code></pre>\n\n<p>This is better:</p>\n\n<pre><code>function Caesar(order){\n this.order = order;\n this.encode = encode;\n function encode(input){\n this.output = '';\n for (var i = 0; i &lt; input.length; i++) {\n var this.c = input.charCodeAt(i);\n if (this.c &gt;= 65 &amp;&amp; this.c &lt;= 90) \n // Uppercase\n this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65); \n else if (this.c &gt;= 97 &amp;&amp; this.c &lt;= 122) \n // Lowercase\n this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97); \n else \n this.output += input.charAt(i); \n }\n return answer.innerHTML= output;\n} \n</code></pre></li>\n<li><code>Caesar</code> is an unfortunate name\n<ul>\n<li>It does not really say what it does ( one can guess )</li>\n<li>it should not start with a capital C, it is not a constructor</li>\n</ul></li>\n<li>The <code>Caesar</code> is completely wrong\n<ul>\n<li>it puts <code>encode</code> in <code>this.encode</code> and then never uses <code>this.encode</code></li>\n<li>if <code>encode</code> were called, it set <code>this.output</code> but then in the end you put <code>output</code> in <code>answer.innerHTML</code></li>\n<li>you try to access <code>answer</code>, but you never declared it with <code>var</code>, much less pointed it to the answer element with <code>getElementById</code></li>\n</ul></li>\n<li>You hardcode magical numbers\n<ul>\n<li>Some developers know <code>65</code> is <code>A</code>, you should put a comment about that</li>\n<li>Same for <code>97</code> , <code>26</code> and <code>122</code></li>\n</ul></li>\n<li><code>order</code> -> what does <code>order</code> do ? Should be commented, it is not obvious</li>\n<li><code>onclick =\"encode()\"</code> &lt;- This is very old skool ( bad ), the correct way is using an <code>addEventListener</code> for <code>load</code> and in there use an <code>addEventListener</code> for <code>click</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:49:56.187", "Id": "79612", "Score": "0", "body": "Thank you for your comments. However, I'd like to point out that Caesar is a constructor function. I want to be able to create Caesar objects with 'new' and initialize them with 'order'. Is it not the right way to create a constructor function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:44:53.613", "Id": "79637", "Score": "0", "body": "It is the right way, but the constructor should not `return answer.innerHTML= output;` in that case" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:41:29.210", "Id": "45617", "ParentId": "45609", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:08:15.900", "Id": "45609", "Score": "2", "Tags": [ "javascript", "beginner", "html", "caesar-cipher" ], "Title": "Caesar cipher implementation" }
45609
<p>I have this old project I wrote years ago and it's all classes and methods all over the place. I am trying to learn/understand how I can apply a more OOP principle. It is very large and can't paste all the code here. Instead I will demonstrate what I have as a basic.</p> <p>Checkup.cs </p> <pre><code>public class CheckUp { //General information public string CliniciansName { get; set; } public string EmploymentStatus { get; set; } public DateTime DateOfCheck { get; set; } public string CheckUpType { get; set; } public ColourVision ColourVisionObject { get; set; } ///lots of other checkups like 45 and growing and forever changin } </code></pre> <p>ColourVision.cs</p> <pre><code>public class ColourVision { public int ColourVisionType { get; set; } public int OutcomeID { get; set; } public DateTime RecallDate { get; set; } public string Recommendations { get; set; } //Contains a few horrible methods to parse form other formats, // CSV datatables, XML, but needed. Here is one from a DataTable public Boolean ColourVision Load(System.Data.DataTable dt){ Boolean isLoaded = false; System.Data.DataRow row = DataRow; try { ColourVisionType = row["ColourVision"].ToString(); FFTOutcomeID = Convert.ToInt32(import.getOutcomeValue(row["ColourVisionOutcome"].ToString())); RecallDate = (row["ColourVisionRecallDate"] != DBNull.Value) ? (DateTime)row["ColourVisionRecallDate"] : DateTime.MinValue; Recommendations = (row["ColourVisionRecommendations"] != DBNull.Value) ? (string)row["ColourVisionRecommendations"] : ""; isLoaded = true; } catch (Exception ex) { isLoaded = false; } return isLoaded; } //And this takes the data row and populates it self //by reference from healtchcheck, where there //are thousands of checks and lines of code //and this is what I am trying to streamline public void Update(ref Data.CheckUp checkUp) } </code></pre> <p>The database is one table with over 400 columns and contains at least the General Info defined in CheckUp. It may or may not contain 0 more fields up to all the fields.</p> <p>I am racking up my brain on how to create a Checkup Class, that can load the basic data form the data table, or 0 or more checkup objects, without manually calling methods like this for each kind of import logic. </p> <pre><code>if (ColorurVision.Load(ref dataRowFromSomethingElse) == true ) { CheckUp.ColourVision == null } </code></pre> <p>I am reading about Inheritance and the examples are clear but I just cannot for the life of me figure out how to do that here. I have a feeling this is perfect project for that. Maybe I am just looking at it wrong. Should I be rather inheriting from something else, like <code>System.Data.DataTable</code> and returning <code>ColourVision</code>, or <code>CheckUp</code>?</p> <p>This is really a high level code review question based more on programming principles.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:51:35.083", "Id": "79613", "Score": "1", "body": "\"//Contains horrible methods to parse datatables, XML, but needed.\" You could also put up these methods for review ;) Wheter in a separate question or as additional code here is up to you. From what you write about your database, I take you have not applied [normalization](http://en.wikipedia.org/wiki/Database_normalization). This might be worth taking a look at for you. It should make Extraction of Classes for your Data easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:57:15.560", "Id": "79615", "Score": "0", "body": "Yea OK i put the load from datatable. Its really rough but it has been written and works. I suspect that moving that out o the Model class and into an Extension (Extend DataRow? with 50 extension methods???) would be pretty good OOP? BUt I still have to create lots of lines of codes that call each of these separately and test results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T06:02:05.293", "Id": "79847", "Score": "1", "body": "I'm troubled by the thought of extending `DataTable` 50 times. Look at @Ocelot20 answer and do some \"wishful thinking\" about what your classes should look like. Think about what properties should be - for example `Recommendations` - plural - is a single string? I doubt it. DO NOT DESIGN YOUR CLASSES BASED ON THE DATABASE SCHEMA." } ]
[ { "body": "<p>Just a small observation:</p>\n\n<blockquote>\n<pre><code>public int ColourVisionType { get; set; }\npublic int OutcomeID { get; set; }\n</code></pre>\n</blockquote>\n\n<p>From the names of these properties, it looks like your code could benefit from a few <code>enum</code> types. An enum value is always easier to read and understand than any magic <code>int</code> number:</p>\n\n<pre><code>public ColourVisionType ColourVisionType { get; set; }\npublic OutcomeValue OutcomeId { get; set; }\n</code></pre>\n\n<hr>\n\n<p>This line looks like it's assigning a <code>string</code> value to an <code>int</code>-typed member - which wouldn't compile:</p>\n\n<pre><code>ColourVisionType = row[\"ColourVision\"].ToString();\n</code></pre>\n\n<p>If <code>ColourVisionType</code> is what I think it is (if it's not then you have a readability issue!), then I'd try to parse the value into some <code>ColourVisionType</code> enum.</p>\n\n<p>I don't see <code>OutcomeID</code> being assigned, but I'd give it the same treatment - parse it to a meaningful enum value.</p>\n\n<hr>\n\n<p>Notice I've renamed <code>OutcomeID</code> to <code>OutcomeId</code> - per the <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229002%28v=vs.100%29.aspx\" rel=\"nofollow\">C# naming guidelines</a>, <code>ID</code> should be named <code>Id</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:17:35.767", "Id": "79622", "Score": "0", "body": "Yea.. there are like 400 properties names like this :) I know.. it was years ago but I can work on that I just dont know what the \"big picture\" is on how to create a proper OOP classes and architecture :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:30:41.440", "Id": "79630", "Score": "0", "body": "I am trying to learn OOP practices and how to apply them. Maybe I am showing the wrong end of the code here, but if I post it it will be 100 pages long... shocking for such a simple thing really. What books you recommend reading?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:32:46.683", "Id": "79631", "Score": "2", "body": "Best possible read I can think of would be \"Design Patterns: Elements of Reusable Object-Oriented Software\" (the GoF patterns book) - and then \"Clean Code\" by Robert C. Martin, and also \"Dependency Injection in .NET\", by Mark Seemann." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T06:05:18.257", "Id": "79848", "Score": "0", "body": "I vigorously disagree with starting with the \"Gang of Four\" book if \"I am trying to learn OOP..\" Look at some of the \"Head First\" series like [Object Oriented Analysis and Design](http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=sr_1_1?s=books&ie=UTF8&qid=1396159467&sr=1-1&keywords=head+first+object-oriented+analysis+and+design)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:15:41.943", "Id": "45619", "ParentId": "45611", "Score": "4" } }, { "body": "<h3>Properties</h3>\n\n<p>I like that you use Properties, but I don't like, the Datatype you use:</p>\n\n<blockquote>\n<pre><code>public int ColourVisionType{ get; set;}\n</code></pre>\n</blockquote>\n\n<p>this is definitely <strong>not</strong> an int. You should represent finite element types by enums:</p>\n\n<pre><code>public enum ColourVisionType{\n TYPEONE, TYPETWO, TYPETHREE\n}\n</code></pre>\n\n<p>Same goes for <code>OutcomeId</code>. This is DataStructure. You should not need to care for DataStructure in itself (id, references, etc.) when writing the handling layer</p>\n\n<p>instead reference:</p>\n\n<pre><code> public Outcome Outcome { get; set; }\n</code></pre>\n\n<p>and this also is an enum (As well as <code>EmploymentStatus</code> and <code>CheckUpType</code>)</p>\n\n<pre><code> public enum Outcome{\n FAILURE, SUCCESS, SOMETHING_DIFFERENT\n }\n</code></pre>\n\n<p>On the other hand, if you had more to an outcome than just a type, you should make it a separate class:</p>\n\n<pre><code> public class Outcome{\n public int OutcomeId { get; set; }\n public Diagnosis Diag { get; set; }\n // [...]\n }\n</code></pre>\n\n<h3>Talking about data structure:</h3>\n\n<p>From what you write about your database, I take you have not applied <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow\">normalization</a>.<br>\nThis might be worth taking a look at for you. It should make extraction of classes for your data-structures easier.</p>\n\n<p>You might also want to take a look at the <a href=\"http://msdn.microsoft.com/de-de/library/vstudio/bb386884%28v=vs.100%29.aspx\" rel=\"nofollow\">Microsoft Entity Framework</a>, it might help you make your data-fetching easier<br>\n[example code]:</p>\n\n<pre><code>public boolean Load(int Id){\n try\n {\n using(Context myContext = new Context())\n {\n ColourVisionModel data = (from cv in context.ColourVisions\n select cv where cv.id = Id).FirstOrDefault();\n }\n }\n catch (Exception e){\n //handle exception\n return false;\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:20:31.223", "Id": "79623", "Score": "0", "body": "Thanks _ most of the top stuff I understand. I will change that as I apply top level changes to everything. I just do not know if I should 50extensions on DataTable? Or Create Base classes and inheritance somehow. PS There are like 10 more methods to load from CSV, from XML, from Webservices, From all sorts. The one file is like a monster, which is OK but its a nightmare to work with. I would like to apply some kind of best OOP practises, speration, inheritance. ANy advice on that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:23:43.643", "Id": "79624", "Score": "1", "body": "@ppumkin in fact I recommend you recreate your whole data layer. DataTable is a hassle to work with, you can instead have EntityFramework do the writing-intensive stuff for you. You need to have a better data-structure first though. I recommend you extract smaller subsets of Columns, that belong together to separate tables. Concerning OOP: Your Data (which is the only thing you posted) does not really care about Object Orientation. You don't have to worry about the OOP Character of your data, just fit them to subsets and it should be fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:25:13.810", "Id": "79625", "Score": "1", "body": "also you'd need to post code for a better overview. *personally*(!) I **love** using Services. If you combine them with a factory Pattern you can load all sorts of data with always similar calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:27:43.067", "Id": "79626", "Score": "0", "body": "This project is meant to deal with various people. and guest what, most healthcompanies expoert datat in CSV! YAAAAy :( or Crazy Webservices that embed DataSets! Yaaaay :( And over the years its grown into this monster and I just cannot bear to look at it. There must be a better way, so I am seeking some experienced advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:28:32.400", "Id": "79627", "Score": "0", "body": "Do you have alink into this factory stuff. I have seen it around but not really understood it. Maybe its worth looking at." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:30:00.283", "Id": "79629", "Score": "1", "body": "@ppumkin I found [this tutorial](http://www.codeproject.com/Tips/469453/Illustrating-Factory-pattern-with-a-very-basic-exa)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T15:16:26.710", "Id": "45620", "ParentId": "45611", "Score": "3" } }, { "body": "<p>The biggest issues I see with this code is naming of Classes/Properties/Methods and proper <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">separation of concerns</a>.</p>\n\n<p>I find the best way to think about separation of concerns is to think in terms of \"has a\" relationships to see if they make sense. For example, you might question whether a \"Checkup <em>has an</em> employment status\". When you put it that way, it's pretty clear that a Checkup doesn't make sense to have an employment status, but a <em>Person</em> might. It's pretty easy to fall into the trap of saying \"I don't need to make a <code>Person</code> class because it's not that complex yet\". This will come back to bite you later whether it's another developer that can't understand your code (maybe even yourself) or wishing you could more easily modify functionality because the elements are so tightly coupled.</p>\n\n<p>Here's an example of how you might better organize your classes:</p>\n\n<pre><code>public class CheckUp\n{\n public DateTime AppointmentTime { get; set; }\n public DateTime StartTime { get; set; }\n public DateTime EndTime { get; set; }\n\n public Clinician Clinician { get; set; }\n public Patient Patient { get; set; }\n\n // A type of test might be a ColorVisionTest.\n public List&lt;Test&gt; TestsRun { get; set; }\n}\n\npublic class Person\n{\n public String FirstName { get; set; }\n public String LastName { get; set; }\n}\n\npublic class Clinician : Person\n{\n public List&lt;Licenses&gt; Licenses { get; set; }\n}\n\npublic class Patient : Person\n{\n public List&lt;Checkups&gt; Checkups { get; set; }\n}\n\npublic static class DatatableTestParser\n{\n public static List&lt;Test&gt; ParseTests(DataTable dt)\n {\n // Parsing logic here.\n }\n}\n</code></pre>\n\n<p>To keep harping on the separation of concerns, let's talk about a comment of yours:</p>\n\n<blockquote>\n <p>I am racking up my brain on how to create a Checkup Class, that can\n load the basic data form the data table</p>\n</blockquote>\n\n<p>Typically you don't want to have something like a <code>Checkup</code> class also be concerned with parsing from things like a datatable. Again, a <code>Checkup</code> should only be concerned with being a <code>Checkup</code> and nothing more. You could have another class that did parsing from a <code>DataTable</code> or other data source, but the key is to separate it from the <code>Checkup</code> itself. Hopefully this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T08:44:39.560", "Id": "79947", "Score": "0", "body": "THank you this does make. That is why I am struggling since easc healthcheck contains its properties, plus methods to parse ands save. Its bloating now. So inheritance is really used to define objects and not really for business/data logic (we use INterfaces there?) THis does make sense and I suppose I can separate it all into tiers that are responsible for it. I suppose there is not much I can do to make reading 400 columns and deciding where to assign them, without writing it out. I thought there might be a principle that can help deal with that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T13:56:12.137", "Id": "79966", "Score": "0", "body": "The main purpose of Inheritance is to avoid duplicate code. Whether or not this relates to business logic depends on how you're using it. If you're looking for a way to map properties to an object, there are a ton of tools/patterns to help with that. As it sits however, your question is a bit too broad (hence me commenting on the general OOP aspect of it). You may consider starting a new question that addresses the property mapping aspect of the code specifically." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T21:15:59.333", "Id": "45710", "ParentId": "45611", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T14:10:34.813", "Id": "45611", "Score": "2", "Tags": [ "c#", "object-oriented", "inheritance" ], "Title": "Color vision checkup" }
45611