body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>There is a application with a very slow query (listed below), and I have to optimize to run faster. The truth is that I don't know where to start. Any help? Thanks!</p> <pre><code>SELECT DISTINCT v.order_ANC, v.order_ANC2, f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia, SUM (num_uni_imatges) AS num_uni_imatges, SUM (unitats_text) AS unitats_text, SUM (unitats_notext) AS unitats_notext FROM ( SELECT f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia, SUM (CASE WHEN u.num_imatges &gt; 0 THEN 1 ELSE 0 END) AS num_uni_imatges, COUNT (u.codi_unitat) AS unitats_text, 0 AS unitats_notext FROM ianc_fons f JOIN ianc_unicat u ON ( f.codi_arxiu = u.codi_arxiu AND f.codi_fons = u.codi_fons ) WHERE 1 = 1 AND u.anc_unicat_id IN (SELECT DISTINCT u.anc_unicat_id FROM ianc_unicat u WHERE 1 = 1 AND u.codi_arxiu = '1' AND u.codi_grup = 'ANC' AND u.codi_fons = 1) GROUP BY f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia UNION SELECT f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia, SUM (CASE WHEN u.num_imatges &gt; 0 THEN 1 ELSE 0 END) AS num_uni_imatges, 0 AS unitats_text, COUNT (u.nt1_unitat) AS unitats_notext FROM ianc_fons f JOIN ianci_unicats u ON ( f.codi_arxiu = u.nt1_codi_arxiu AND f.codi_fons = u.nt1_codi_fons ) WHERE 1 = 1 AND u.nt1_id IN (SELECT DISTINCT u.nt1_id FROM ianci_unicats u WHERE 1 = 1 AND u.nt1_codi_arxiu = '1' AND u.codi_grup = 'ANC' AND u.nt1_codi_fons = 1) GROUP BY f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia ) AS f LEFT JOIN v_ianc_arxius_order v ON ( f.codi_arxiu=v.codi_arxiu ) GROUP BY v.order_ANC,v.order_ANC2,f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe, f.codi_fons, f.nom_fons, f.any_ini, f.any_fi, f.cronologia ORDER BY v.order_ANC,v.order_ANC2,f.nom_arxiu, f.nom_fons </code></pre>
[]
[ { "body": "<p>Optimising an SQL statement generally involves two phases: Understanding how the DBMS has chosen to execute the query in terms of index lookup and join order (called the query plan), and figuring out a way to write a query that gets the same effect, but that the DBMS finds a better query plan for.</p>\n\n<p>Forcing the DBMS to choose a better query plan can be as simple as forcing a different index choice (overriding an automatic but non-optimal choice of index), adding a missing index or overriding the optimiser's choice of table join ordering. Or you might find a completely different way of expressing the same logical query, for example by using a join rather than <code>WHERE column IN (SELECT ...)</code>. Overriding the optimiser usually requires special syntax that is specific to your SQL product (SQL Server, in this case) that should be explained in the manuals somewhere.</p>\n\n<p>In your case, your first step should probably be to get a better insight into exactly why this query is slow. You can do this to a limited extent by removing some clauses from the query and seeing whether it gets immediately quicker; perhaps removing the <code>ORDER BY</code> clause or removing <code>JOIN</code> clauses.</p>\n\n<p>If it's available, then a more powerful option is to use whatever analysis tools are provided with your DBMS, or available as third party tools. I don't know SQL server specifically, but I'm sure there's a tool that will show you the query plan for any given query, and ideally give some insight into why the optimiser chose that query plan over other possibilities.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T10:24:05.840", "Id": "2844", "ParentId": "2843", "Score": "0" } }, { "body": "<p>I suspect one bottleneck is the grouping in the subqueries. For each row in the <code>ianc_fons</code> table the rows are being duplicated - one for each join the chile table <code>ianc_unicat</code>. And then they are being grouped again.</p>\n\n<p>I would try a different approach and move the summing into a joined subquery :</p>\n\n<pre><code>SELECT f.codi_arxiu,\n f.nom_arxiu,\n f.codi_grup,\n f.codi_fons_refe,\n f.codi_fons,\n f.nom_fons,\n f.any_ini,\n f.any_fi,\n f.cronologia,\n child.num_uni_imatges,\n child.unitats_text\n FROM ianc_fons f\n LEFT JOIN\n ( SELECT codi_arxiu, codi_fons,\n SUM (CASE WHEN u.num_imatges &gt; 0 THEN 1 ELSE 0 END) AS num_uni_imatges,\n COUNT (u.codi_unitat) AS unitats_text\n FROM ianc_unicat u \n WHERE u.anc_unicat_id IN\n (SELECT u.anc_unicat_id\n FROM ianc_unicat u\n WHERE 1 = 1\n AND u.codi_arxiu = '1'\n AND u.codi_grup = 'ANC'\n AND u.codi_fons = 1)\n GROUP BY codi_arxiu, codi_fons\n ) AS child ON f.codi_arxiu = child.codi_arxiu AND f.codi_fons = child.codi_fons\n</code></pre>\n\n<p>Note I have removed the DISTINCT from the Select from <code>ianc_unicat</code>. As this is just used in the filtering, the DISTINCT is not necessary. Using DISTINCT is always an overhead as the query engine needs to sort the records and then compare them all one by one to remove duplicates. Avoid as much as possible.</p>\n\n<p>Each side of the <code>UNION</code> is selecting from the same table, and then summing different child records.</p>\n\n<p>As the summing is now in a separate joined subquery, you can get rid of the union, and just join in the other table in a similar fashion. The Select will now need to sum up the totals from both joined subqueries.</p>\n\n<pre><code>SELECT f.codi_arxiu,\n f.nom_arxiu,\n f.codi_grup,\n f.codi_fons_refe,\n f.codi_fons,\n f.nom_fons,\n f.any_ini,\n f.any_fi,\n f.cronologia,\n COALESCE(child.num_uni_imatges, 0) + COALESCE(child2.num_uni_imatges, 0) AS num_uni_imatges,\n child.unitats_text,\n child2.unitats_notext\n</code></pre>\n\n<p>Note the use of COALESCE. As you are left joining these totals now, there is a chance that the values may be Null. Null is not the same as 0. Null + 4 would not equal 4, the result would be Null. So the COALESCE is necessary to make Null values 0.</p>\n\n<p>Now you no longer need the outer select as this was being used to just sum the rows within the union. You can get rid of this all together. The row joined in to the outer query can just be joined into our main query. We no longer the the extra grouping here either. This gives us a query similar to the following :</p>\n\n<pre><code>SELECT f.codi_arxiu,\n f.nom_arxiu,\n f.codi_grup,\n f.codi_fons_refe,\n f.codi_fons,\n f.nom_fons,\n f.any_ini,\n f.any_fi,\n f.cronologia,\n COALESCE(child.num_uni_imatges, 0) + COALESCE(child2.num_uni_imatges, 0) AS num_uni_imatges,\n child.unitats_text,\n child2.unitats_notext\n FROM ianc_fons f\n LEFT JOIN\n ( SELECT codi_arxiu, codi_fons,\n SUM (CASE WHEN u.num_imatges &gt; 0 THEN 1 ELSE 0 END) AS num_uni_imatges,\n COUNT (u.codi_unitat) AS unitats_text\n FROM ianc_unicat u \n WHERE u.anc_unicat_id IN\n (SELECT u.anc_unicat_id\n FROM ianc_unicat u\n WHERE 1 = 1\n AND u.codi_arxiu = '1'\n AND u.codi_grup = 'ANC'\n AND u.codi_fons = 1)\n GROUP BY codi_arxiu, codi_fons\n ) AS child ON f.codi_arxiu = child.codi_arxiu AND f.codi_fons = child.codi_fons\n\n LEFT JOIN \n ( SELECT u.nt1_codi_arxiu, u.codi_fons,\n SUM (CASE WHEN u.num_imatges &gt; 0 THEN 1 ELSE 0 END) AS num_uni_imatges,\n COUNT (u.nt1_unitat) AS unitats_notext\n FROM ianci_unicats u \n WHERE 1 = 1\n AND u.nt1_id IN\n (SELECT u.nt1_id\n FROM ianci_unicats u\n WHERE 1 = 1\n AND u.nt1_codi_arxiu = '1'\n AND u.codi_grup = 'ANC'\n AND u.nt1_codi_fons = 1)\n ) AS child2 ON f.codi_arxiu = child2.nt1_codi_arxiu AND f.codi_fons = child2.nt1_codi_fons\n\n LEFT JOIN v_ianc_arxius_order v ON ( f.codi_arxiu=v.codi_arxiu )\n ORDER BY v.order_ANC,v.order_ANC2,f.nom_arxiu, f.nom_fons\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T12:15:04.413", "Id": "2852", "ParentId": "2843", "Score": "2" } } ]
{ "AcceptedAnswerId": "2852", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:22:40.433", "Id": "2843", "Score": "0", "Tags": [ "sql", "sql-server" ], "Title": "Optimize slow SQL query" }
2843
<p>This is my first attempt to create a reusable and tested module. Any comments is highly appreciated.</p> <pre><code>#-*- coding: utf-8 -*- """ Micron: a micro wrapper around Unix crontab. Micron is a thin wrapper around Unix crontab command. It let you add and remove jobs from the crontab file or remove the entire crontab file. "crontab" is the program used to install, deinstall or list the tables used to drive the cron daemon How it works: &gt;&gt;&gt; #Obviously you need to import the module &gt;&gt;&gt; import micron &gt;&gt;&gt; #Then you create a crontab instance &gt;&gt;&gt; crontab = micron.CronTab() &gt;&gt;&gt; #Assuming your crontab does not exist trying to read it will rise an error &gt;&gt;&gt; crontab.read() Traceback (most recent call last): ... raise CronTabMissing() CronTabMissing: Current crontab does not exist &gt;&gt;&gt; #Now you can add some jobs. Micron supports some common presets &gt;&gt;&gt; sorted(crontab.PRESETS.items()) [('daily', '0 0 * * * '), ('hourly', '0 * * * * '), ('monthly', '0 0 1 * * '), ('weekly', '0 0 * * 1 ')] &gt;&gt;&gt; crontab.add_job('weekly', 'echo "WOW"', 0) &gt;&gt;&gt; crontab.add_job('daily', 'echo "BOOM!"', 1) &gt;&gt;&gt; #You can omit the job id and micron will generate it for you &gt;&gt;&gt; crontab.add_job('daily', 'echo "BOOM!"') &gt;&gt;&gt; #Read again the crontab content &gt;&gt;&gt; crontab.read() ['0 0 * * 1 echo "WOW" #MICRON_ID_0', '0 0 * * * echo "BOOM!" #MICRON_ID_1', '0 0 * * * echo "BOOM!" #MICRON_ID_2'] &gt;&gt;&gt; #See how it look in the crontab file &gt;&gt;&gt; print crontab 0 0 * * 1 echo "WOW" #MICRON_ID_0 0 0 * * * echo "BOOM!" #MICRON_ID_1 0 0 * * * echo "BOOM!" #MICRON_ID_2 &gt;&gt;&gt; #Remove job with id 0 &gt;&gt;&gt; crontab.remove_job(0) &gt;&gt;&gt; print crontab 0 0 * * * echo "BOOM!" #MICRON_ID_1 0 0 * * * echo "BOOM!" #MICRON_ID_2 &gt;&gt;&gt; #Remove job with non existing id and you'll get and error &gt;&gt;&gt; crontab.remove_job(11) Traceback (most recent call last): ... raise ValueError('Id %s not in crontab' % job_id) ValueError: Id 11 not in crontab &gt;&gt;&gt; #If the presets are not enough, you can add your own timing using the &gt;&gt;&gt; #crontab syntax &gt;&gt;&gt; crontab.add_job('* * * * * ', 'echo "This will work"') &gt;&gt;&gt; #But you must use the correct syntax &gt;&gt;&gt; crontab.add_job('*wrong syntax* ', 'echo "This will not work"') Traceback (most recent call last): ... raise CronTabSyntaxError(added_job[0]) CronTabSyntaxError: Syntax error adding: *wrong syntax* echo "This will not work" #MICRON_ID_4 &lt;BLANKLINE&gt; &gt;&gt;&gt; #Sometimes you want to remove all the jobs added by Micron &gt;&gt;&gt; crontab.remove_all_jobs() &gt;&gt;&gt; #Any other crontab content is not removed &gt;&gt;&gt; crontab.read() [] &gt;&gt;&gt; #Remove the entire crontab file &gt;&gt;&gt; crontab.remove_crontab() """ from subprocess import Popen, PIPE, CalledProcessError class CronTabError(Exception): """Base error class.""" pass class CronTabMissing(CronTabError): """Cron tab missing.""" def __str__(self): return "Current crontab does not exist" class CronTabSyntaxError(CronTabError): """Crontab syntax error.""" def __init__(self, string): self.string = string def __str__(self): return "Syntax error adding:\n %s" % self.string class CronTabIdError(CronTabError): """Crontab job already exists.""" def __init__(self, cron_id): self.cron_id = cron_id def __str__(self): return "Job ID %s already exists" % self.cron_id class CronTab(): """A simple UNIX crontab wrapper This class let you interact with the crontab file of the current user reading, adding and removing lines. """ CRONTAB_PATH = "/usr/bin/crontab" PRESETS = { "hourly":"0 * * * * ", "daily": "0 0 * * * ", "weekly":"0 0 * * 1 ", "monthly":"0 0 1 * * ", } PLACEHOLDER = ' #MICRON_ID_' #must start with a space, must be separated by "_" def __str__(self): jobs = self.read() return "\n".join(jobs) def read(self): """Read the crontab file content Return the content as a list of lines. """ args = [self.CRONTAB_PATH, '-l'] process = Popen(args, stdout=PIPE, stderr=PIPE) output, unused_err = process.communicate() retcode = process.poll() if retcode == 1: raise CronTabMissing() elif retcode: raise CalledProcessError(retcode, self.CRONTAB_PATH) jobs = output.splitlines() return jobs def _get_id(self, job): job_id = job.split(self.PLACEHOLDER)[-1] return int(job_id) def _create_id(self): """Create a unique id for a cron job.""" try: jobs = self.read() job_ids = sorted([self._get_id(job) for job in jobs if self.PLACEHOLDER in job]) if job_ids: new_job_id = int(job_ids[-1]) + 1 else: new_job_id = 0 except CronTabMissing: new_job_id = 0 return new_job_id def save(self, job_list): """Overwrite the current crontab.""" process = Popen([self.CRONTAB_PATH, '-'], stdout=PIPE, stdin=PIPE, stderr=PIPE) content = "\n".join(job_list) process.communicate(input=content) if process.returncode != 0: current_jobs = self.read() added_job = list(set(job_list) - set(current_jobs)) raise CronTabSyntaxError(added_job[0]) def add_job(self, timing, program, job_id=None): """Add a job to the current user crontab.""" if self.PRESETS.has_key(timing): new_job = self.PRESETS[timing] + program else: new_job = timing + program if job_id is None: job_id = self._create_id() new_job += "%s%s\n" % (self.PLACEHOLDER, job_id) try: jobs = self.read() except CronTabMissing: jobs = [] for job in jobs: if self.PLACEHOLDER in job: current_job_id = self._get_id(job) if current_job_id == job_id: raise CronTabIdError(job_id) jobs.append(new_job) self.save(jobs) def remove_job(self, job_id): """Delete a job with the given job id.""" jobs = self.read() for job in jobs: if self.PLACEHOLDER in job: current_job_id = self._get_id(job) if current_job_id == job_id: jobs.remove(job) self.save(jobs) break else: raise ValueError('Id %s not in crontab' % job_id) def remove_all_jobs(self): """Delete all jobs created by micron.""" jobs = self.read() other_jobs = [job for job in jobs if self.PLACEHOLDER not in job] self.save(other_jobs) def remove_crontab(self): """Remove the crontab file. Remove the crontab file of the current user. The information contained in the crontab file is permanently lost. """ process = Popen([self.CRONTAB_PATH, '-r'], stdout=PIPE, stderr=PIPE) output, unused_err = process.communicate() if process.returncode: raise CronTabError if __name__ == "__main__": import doctest doctest.testmod() </code></pre>
[]
[ { "body": "<p>I think it is a pretty good start:</p>\n\n<ul>\n<li>I would like to see a Job class.</li>\n<li>The stderr output would be great in cases of an retcode != 0.</li>\n<li>A validation and/or escaping of timing and program would be great.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T07:28:52.217", "Id": "4409", "Score": "0", "body": "Thanks for the feedback. What do you mean with: \"The stderr output would be great in cases of an retcode != 0.\"? You think I should include the stderr output when I raise one of the custom exception? It seems a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T13:42:43.767", "Id": "4412", "Score": "0", "body": "Yes, that is the idea." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T16:27:31.203", "Id": "2854", "ParentId": "2846", "Score": "2" } }, { "body": "<p>I concur with dmeister.</p>\n\n<p>Jobs are treated too opaquely by Micron and therefore have no access. A crontab entry is highly structured and a good Job class would allow inspection and modification of its elements.</p>\n\n<p>This leads me to think that you have focused on the container (a crontab) while ignoring the item of interest (a Job). You did code a goodly amount of care into handling exceptions. Is there a higher level fall-back (that is, \"first, do no harm\" as you really don't want to stomp existing entries)? Does the crontab(1) command preserve the prior state on errors or is that something a top-level except ought do?</p>\n\n<p>It is not clear what happens with non-MICRON tagged jobs, you should expect that they will exist.</p>\n\n<p>One nitpick. CRONTAB_PATH is ambiguous where CRONTAB_CMD would not be. You could also put the definition of the command path at module scope which would</p>\n\n<ol>\n<li>Push it higher in the source code</li>\n<li>Save an unnecessary <code>self.</code> as module namespace is assumed and you don't expect the command to vary per instance</li>\n</ol>\n\n<p>Finally, thanks for not making an artificial singleton of the Micron class. Not that you might have, just that some would.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T04:51:54.913", "Id": "2987", "ParentId": "2846", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T11:59:25.433", "Id": "2846", "Score": "3", "Tags": [ "python" ], "Title": "Review request: a simple Cron wrapper in Python" }
2846
<p>I have included the code from a second year project that I would like some advice on. Basically it utilises WMI to query a NIC card from a selection (depending how many are installed in the host machine) and shows various settings such as IP info, DHCP info etc. It also has a ping function.</p> <p>How can I improve this to make it a more professional application? I'm looking for things like code structure, functionalities (bearing in mind mark 2 will have the ability to actually interact with the NIC to turn DHCP off and change addresses, plus I hope to incorporate a TRACERT function).</p> <p>This project is now finished so I'm not cheating by asking this. I just want to take the step from creating a rough but working piece of code to a polished professional one.</p> <p>The program is written in Visual Studio 2010.</p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Management; using System.Management.Instrumentation; ///////////////////////////////////// using System.Net; using System.Net.NetworkInformation; using System.ComponentModel; using System.Threading; namespace WindowsFormsApplication3 { public partial class Form1 : Form { private int pingsSent; AutoResetEvent resetEvent = new AutoResetEvent(false); public Form1() { { InitializeComponent(); } // win32 class //http://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx try { ManagementObjectSearcher query = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\%'"); ManagementObjectCollection queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { if (mo["MacAddress"] != null) { comboBox1.Items.Add(mo["Description"].ToString()); } } } catch (Exception ex) { } } string[] availabilityArray = new string[] { "", "Other", "Unknown", "Running or Full Power", "Warning", "In Test", "Not Applicable", "Power Off", "Off Line", "Off Duty", "Degraded", "Not Installed", "Install Error", "Power Save - Unknown" + "\n" + "The device is known to be in a power save state, but its exact status is unknown.", "Power Save - Low Power Mode" + "/n" + "The device is in a power save state, but still functioning, and may exhibit degraded performance.", "Power Save - Standby" + "/n" + "The device is not functioning, but could be brought to full power quickly.", "Power Cycle", "Power Save - Warning" + "/n" + "The device is in a warning state, though also in a power save state.", }; string[] errorArray = new string[] { "Device is working properly.", "Device is not configured correctly.", "Windows cannot load the driver for this device.", "Driver for this device might be corrupted, or the system may be low on memory or other resources.", "Device is not working properly. One of its drivers or the registry might be corrupted.", "Driver for the device requires a resource that Windows cannot manage.", "Boot configuration for the device conflicts with other devices.", "Cannot filter.", "Driver loader for the device is missing.", "Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.", "Device cannot start.", "Device failed.", "Device cannot find enough free resources to use.", "Windows cannot verify the device's resources.", "Device cannot work properly until the computer is restarted.", "Device is not working properly due to a possible re-enumeration problem.", "Windows cannot identify all of the resources that the device uses.", "Device is requesting an unknown resource type.", "Device drivers must be reinstalled.", "Failure using the VxD loader.", "Registry might be corrupted.", "System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.", "Device is disabled.", "System failure. If changing the device driver is ineffective, see the hardware documentation.", "Device is not present, not working properly, or does not have all of its drivers installed.", "Windows is still setting up the device.", "Windows is still setting up the device.", "Device does not have valid log configuration.", "Device drivers are not installed", "Device is disabled. The device firmware did not provide the required resources.", "Device is using an IRQ resource that another device is using.", "Device is not working properly. Windows cannot load the required device drivers.", }; private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { ManagementObjectSearcher intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'"); ManagementObjectCollection queryCollection = intquery.Get(); foreach (ManagementObject mo in queryCollection) { string Dev = (mo["DeviceID"].ToString()); txtMacAdd.Text = (" " + mo["MacAddress"].ToString()); TxtAdapter.Text = (" " + mo["AdapterType"].ToString()); txtAvailability.Text = (" " + mo["Availability"].ToString()); txtCaption.Text = (" " + mo["Caption"].ToString()); txtDeviceID.Text = (" " + mo["DeviceID"].ToString()); txtErrorCode.Text = (mo["ConfigManagerErrorCode"].ToString()); ManagementObjectSearcher intquery1 = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID='" + Dev + "'}WHERE ResultClass=Win32_NetworkAdapterConfiguration"); ManagementObjectCollection queryCollection1 = intquery1.Get(); queryCollection1 = intquery1.Get(); foreach (ManagementObject mo1 in queryCollection1) { string[] addresses = (string[])mo1["IPAddress"]; string[] gateways = (string[])mo1["DefaultIPGateway"]; string[] Subnets = (string[])mo1["IPSubnet"]; foreach (string ipaddress in addresses) { listIp.Items.Add(ipaddress); } foreach (string gateway in gateways) { TxtGateway.Text = (gateway); } foreach (string subnet in Subnets) { listSubnet.Items.Add(subnet); } /////// SHOW DCHP CONFIG///////// if ((bool)mo1["DHCPEnabled"] == true) { checkBox1.Checked = true; } if ((bool)mo1["DHCPEnabled"] != true) { checkBox1.Checked = !true; } DateTime dt = System.Management.ManagementDateTimeConverter.ToDateTime(mo1["DHCPLeaseExpires"].ToString()); txtDHCPExpires.Text = dt.ToString(); DateTime dte = System.Management.ManagementDateTimeConverter.ToDateTime(mo1["DHCPLeaseObtained"].ToString()); txtDHCPObtained.Text = dte.ToString(); txtDHCPServer.Text = (mo1["DHCPServer"].ToString()); //////////////////////Security//////////////////////////// if ((bool)mo1["IPFilterSecurityEnabled"] == true) { chkboxIPFilter.Checked = true; } if ((bool)mo1["IPFilterSecurityEnabled"] != true) { chkboxIPFilter.Checked = !true; } string[] IPSecProtocols = (string[])mo1["IPSecPermitIPProtocols"]; string[] IPSecPermitTCPPorts = (string[])mo1["IPSecPermitTCPPorts"]; string[] IPSecPermitUDPPorts = (string[])mo1["IPSecPermitUDPPorts"]; foreach (string IPSecProtocol in IPSecProtocols) { //richTextBox1.AppendText(IPSecProtocol); listPermitIP.Items.Add(IPSecProtocol); } foreach (string TCPPort in IPSecPermitTCPPorts) { listPermitTCP.Items.Add(TCPPort); } foreach (string UDPPort in IPSecPermitUDPPorts) { listPermitUDP.Items.Add(UDPPort); } ///////////////////DNS///////////////////////////// try { txtDNSDomain.Text = (mo1["DNSDomain"].ToString()); txtDNShostName.Text = (mo1["DNSHostName"].ToString()); string[] DNSDomainSuffSearch = (string[])mo1["DNSDomainSuffixSearchOrder"]; string[] DNSServerSearchOrder = (string[])mo1["DNSServerSearchOrder"]; foreach (string domainSuff in DNSDomainSuffSearch) { listDomainSuffSearchOrder.Items.Add(domainSuff); } foreach (string DNSServer in DNSServerSearchOrder) { listDNSServerSearchOrder.Items.Add(DNSServer); } if ((bool)mo1["DNSEnabledForWINSResolution"] == true) { chkDNSWinsResolution.Checked = true; } if ((bool)mo1["DNSEnabledForWINSResolution"] != true) { chkDNSWinsResolution.Checked = !true; } if ((bool)mo1["DomainDNSRegistrationEnabled"] == true) { chkDNSRegEnabled.Checked = true; } if ((bool)mo1["DomainDNSRegistrationEnabled"] != true) { chkDNSRegEnabled.Checked = !true; } } catch (Exception ex3) { } } } } private void button2_Click(object sender, EventArgs e) { try { ManagementObjectSearcher intquery; intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'"); ManagementObjectCollection queryCollection = intquery.Get(); queryCollection = intquery.Get(); foreach (ManagementObject mo in queryCollection) { string thisstring = (mo["ConfigManagerErrorCode"].ToString()); int error; int.TryParse(thisstring, out error); MessageBox.Show(errorArray[error]); } } catch (Exception ex1) { MessageBox.Show("Please Select a Device"); } } private void BtnAvailability_Click(object sender, EventArgs e) { try { ManagementObjectSearcher intquery; intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'"); ManagementObjectCollection queryCollection = intquery.Get(); queryCollection = intquery.Get(); foreach (ManagementObject mo in queryCollection) { string thisstring = (mo["Availability"].ToString()); int Avail; int.TryParse(thisstring, out Avail); MessageBox.Show(availabilityArray[Avail]); } } catch (Exception ex2) { MessageBox.Show("Please Select a Device"); } } private void btnPing_Click(object sender, EventArgs e) { // Reset the number of pings pingsSent = 0; // Clear the textbox of any previous content txtResponse.Clear(); txtResponse.Text += "Pinging " + txtIP.Text + " with 32 bytes of data:\r\n\r\n"; // Send the ping SendPing(); } private void SendPing() { System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); // Create an event handler for ping complete pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete); // Create a buffer of 32 bytes of data to be transmitted. byte[] packetData = Encoding.ASCII.GetBytes("................................"); // Jump though 50 routing nodes tops, and don't fragment the packet PingOptions packetOptions = new PingOptions(50, true); // Send the ping asynchronously pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent); } private void pingSender_Complete(object sender, PingCompletedEventArgs e) { // If the operation was canceled, display a message to the user. if (e.Cancelled) { txtResponse.Text += "Ping was canceled...\r\n"; // The main thread can resume ((AutoResetEvent)e.UserState).Set(); } else if (e.Error != null) { txtResponse.Text += "An error occured: " + e.Error + "\r\n"; // The main thread can resume ((AutoResetEvent)e.UserState).Set(); } else { PingReply pingResponse = e.Reply; // Call the method that displays the ping results, and pass the information with it ShowPingResults(pingResponse); } } public void ShowPingResults(PingReply pingResponse) { if (pingResponse == null) { // We got no response txtResponse.Text += "There was no response.\r\n\r\n"; return; } else if (pingResponse.Status == IPStatus.Success) { // We got a response, let's see the statistics txtResponse.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n"; } else { // The packet didn't get back as expected, explain why txtResponse.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n"; } // Increase the counter so that we can keep track of the pings sent string strpings = txtNumPackets.Text; int numbpings = int.Parse(strpings); if (txtNumPackets.Text == null) { numbpings = 4; } pingsSent++; // Send 4 pings if (pingsSent &lt; numbpings) { SendPing(); } } private void panel2_Paint(object sender, PaintEventArgs e) { } ////////////////////////////////////////////////////////////////////////////////////////// } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:06:51.077", "Id": "4383", "Score": "12", "body": "First casualty would be all those extraneous blank lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:08:41.443", "Id": "4384", "Score": "3", "body": "One very easy way to make this code vastly more readable is to remove the many redundant blank lines. Whitespace generally increases readability, but only up to a point. Your code forces the reader to scroll all the time, nothing ever fits completely onto the screen. This is *bad*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:26:52.173", "Id": "4387", "Score": "0", "body": "There seem to be new lines where they are not needed and no new lines where they are required." } ]
[ { "body": "<p>Refactor your <code>comboBox1_SelectedIndexChanged</code> method to just call different functions for each different task it is doing. Passing the correct arguments to your functions as necessary.</p>\n\n<p>Do NOT have empty catch clauses in your code. Shows bad exception handling. If you put code in a <code>try catch</code> you should at least make sure you handle your exceptions properly. </p>\n\n<p>Name your controls properly. Controls with names as ComboBox1 is not proper naming. That doesn't tell me from looking at your code what this combobox is all about. Proper naming makes a lot of \ndifference to readability of your code. </p>\n\n<p>This: </p>\n\n<pre><code>catch (Exception ex1)\n{\n MessageBox.Show(\"Please Select a Device\");\n}\n</code></pre>\n\n<p>does not fit in that catch clause, the code that is inside the accompanying try block will not always fail due to a non selected device. You should handle this with an if statement, as it really is not an exception, just a flow in your program, informing the user what should be done. It does not signify an exceptional circumstance in your program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:07:32.593", "Id": "2848", "ParentId": "2847", "Score": "9" } }, { "body": "<p>One or rarely two blank lines can aid readability, any more degrades readability.</p>\n\n<p>If a line of code is long and goes off the screen you could put a new line in to make it readable without scrolling.</p>\n\n<p>Why the meaningless <code>/////////////////////////////////////</code> spacer?</p>\n\n<p>The code has very few comments, especially near start, and they don't add much to the readability, if you want to split the code into regions the use <code>region</code> and <code>end region</code> keywords.</p>\n\n<p>Your namespace <code>namespace WindowsFormsApplication3</code> and your classes <code>public partial class Form1 : Form</code>, and controls all have automatically generated names. These should be changed to something that actually imparts some indication of the their purpose.</p>\n\n<p>Catch generic exceptions sparingly, only do it if you really want to treat all exceptions the same and comment this accordingly, just <code>catch</code> on its own works for this.</p>\n\n<p>If you are going suppress the exception you should comment accordingly, you don't need to provide a name for the exception when doing this, just use <code>catch (SomeException)</code>.</p>\n\n<p>Consider declaring literals as constants or as resources, this is not always expedient, especially when the string is effectively code and self descriptive but is generally good practice.</p>\n\n<p><code>!true</code> is false.</p>\n\n<p>Use camel case declaration names, pascal case for constants. Variable names should comprise of whole words or recognised acronyms or abbreviations. Acronyms of 3 or over chars should be written lower case.</p>\n\n<p>Use <code>String.Format</code> with an <code>IFormatProvider</code> when building or concatenating a string, not the <code>+</code> operator.</p>\n\n<p>Don't have empty event handlers.</p>\n\n<p>Consider using FXCop or Resharper.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:19:08.040", "Id": "2849", "ParentId": "2847", "Score": "12" } }, { "body": "<p>A couple of things based on a quick read through the code:</p>\n\n<p>First, catching exceptions that you don't know how to handle is generally not a good idea. And squashing exceptions is almost always a bad idea. For example, you have:</p>\n\n<pre><code>try\n{\n // do stuff here\n}\ncatch (Exception)\n{\n // do nothing\n}\n</code></pre>\n\n<p>You should catch only those exceptions that you know how to handle. There are many unexpected things that could happen in your code that could put the program in an unstable state. If that happens, you should let the program crash. By catching and squashing all exceptions, you allow the program to potentially corrupt data or return incorrect results.</p>\n\n<p>You have this code in one of your methods:</p>\n\n<pre><code>if ((bool)mo1[\"DNSEnabledForWINSResolution\"] == true)\n{\n chkDNSWinsResolution.Checked = true;\n}\nif ((bool)mo1[\"DNSEnabledForWINSResolution\"] != true)\n{\n chkDNSWinsResolution.Checked = !true;\n}\n</code></pre>\n\n<p>You can shorten that and make it more readable by using <code>if...else</code>:</p>\n\n<pre><code>if ((bool)mo1[\"DNSEnabledForWINSResolution\"] == true)\n{\n chkDNSWinsResolution.Checked = true;\n}\nelse\n{\n chkDNSWinsResolution.Checked = !true;\n}\n</code></pre>\n\n<p>Also, <code>!true</code> is the same thing as <code>false</code> in C#. <code>bool</code> is a type that can only take one of two values, unlike the old C <code>BOOL</code> that was just an alias for <code>int</code>. C# programmers are used to seeing <code>false</code>. <code>!true</code> will confuse them.</p>\n\n<p>The code can be further simplified to:</p>\n\n<pre><code>chkDNSWinsResolution.Checked = (bool)mo1[\"DNSEnabledForWINSResolution\"];\n</code></pre>\n\n<p>without losing clarity. In fact, one could argue that it's more clear. Terseness isn't a goal in itself, but here the meaning is quite clear, and it eliminates several lines of extraneous lines of code.</p>\n\n<p>Your <code>availabilityArray</code> and <code>errorArray</code> arrays should be defined as <code>static readonly</code>, and formatted across multiple lines. For example:</p>\n\n<pre><code>static readonly string[] availabilityArray = new string[]\n{\n \"\",\n \"Other\",\n \"Unknown\",\n // etc.\n}\n</code></pre>\n\n<p>That's much more readable. Making them <code>readonly</code> prevents them from being modified and also tells others looking at the program that they won't be modified. <code>static</code> ensures that only one copy will be used. If it's not static, then every instance of the class will create a separate array to hold the same constant strings.</p>\n\n<p>You need to handle error return values. For example, you have:</p>\n\n<pre><code>int error;\nint.TryParse(thisstring, out error);\n</code></pre>\n\n<p>If <code>thisstring</code> is not a valid integer, then <code>error</code> will be 0. You probably should write instead something like:</p>\n\n<pre><code>int error;\nstring errMsg;\nif (int.TryParse(thisstring, out error) &amp;&amp; error &gt;= 0 &amp;&amp; error &lt; errorArray.Length)\n{\n errMsg = errorArray[error];\n}\nelse\n{\n errMsg = string.Format(\"Unknown error code: {0}\", thisstring);\n}\nMessageBox.Show(errMsg);\n</code></pre>\n\n<p>Otherwise your code will throw an exception if <code>error</code> is outside the range of possible error codes, and if <code>thisstring</code> isn't a valid integer you'll display a bogus error message.</p>\n\n<p>In general, if a conversion can cause an error, assume that it will at some point, and be prepared to handle it. In one place, for example, you're using <code>int.Parse</code> to parse user input from a text box. If the user enters a non-numeric value or a value that can't be converted to an integer (for example, 3000000000), that's going to throw an exception. You should use <code>TryParse</code>, check the return value, and display an error message if it fails.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:22:26.480", "Id": "4390", "Score": "0", "body": "@Jim Thankyou, this is exactly the kind of advice i'm lookinf for and can apply in many situations :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:37:16.630", "Id": "4391", "Score": "0", "body": "@Jim would validation on the textbox do the same thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:55:22.210", "Id": "4392", "Score": "0", "body": "@Dylan: Validation on the textbox *can* do the same thing, as long as you guarantee that the user can't exit the textbox without it being validated. That turns out to be something of a difficult problem in the general case, and often turns out to be annoying to the user because it interferes with editing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:19:27.270", "Id": "2850", "ParentId": "2847", "Score": "10" } }, { "body": "<p>@Tony The Tiger's <a href=\"https://stackoverflow.com/questions/6262940/how-can-i-turn-this-from-a-rough-functioning-program-to-a-polished-professional-o/6262992#6262992\">answer</a> is perfect so I only want to ask a favor of you.</p>\n\n<p>Please replace</p>\n\n<pre><code>if ((bool)mo1[\"DNSEnabledForWINSResolution\"] != true)\n{\n chkDNSWinsResolution.Checked = !true;\n}\n</code></pre>\n\n<p>blocks with something more readable, like</p>\n\n<pre><code>chkDNSWinsResolution.Checked = (bool)mo1[\"DNSEnabledForWINSResolution\"];\n</code></pre>\n\n<p>Also, <code>!true</code> is called <code>false</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T12:20:04.143", "Id": "4394", "Score": "4", "body": "Your replacement code is not logically equivalent to the original code. If the value of mo1[\"DNSEnabledForWINSResolution\"] is true, then the checkbox.Checked value remains unchanged. Your code would set it to false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T12:54:52.457", "Id": "4395", "Score": "0", "body": "@Mongus Pong: thanks for the note. I thought he relied on default values being set in the form designer, and in case they didn't match default `mo1` settings, he would see it either way first time the form is shown after the changes. However you're right it is worth mentioning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T12:58:44.703", "Id": "4396", "Score": "0", "body": "it is certainly possible that your code might be what he meant!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:24:06.277", "Id": "2851", "ParentId": "2847", "Score": "5" } }, { "body": "<p>Some thoughts:</p>\n\n<ol>\n<li><p>Comments would be nice. I see a few, very sparsely written, and it makes it hard to figure out what is going on from a quick glance. Furthermore, in your comments, add something like this:</p>\n\n<pre><code>/*\n* NIC-WMI Query\n* Version 1.0, Created on 1/2/10 by Dylan Jackson\n*\n* Description of program...\n*\n* Audit Trail:\n* ------------\n*\n* 01/01/2010 DJ v0.9 Added a,b,c. Fixed d,e.\n* ...\n*/\n</code></pre>\n\n<p>A comment block like this lets me know what the program is about, what version it is, who wrote it (and when), what changes have been made (and by whom). You'll come up with your own style and what you do and don't want there (or it may be dictated to you), but something at the top is never a bad thing to help other readers know what is going on.</p></li>\n<li><p>Don't use generic object/class names. Things like <code>WindowsFormApplication3</code> or <code>button2</code> are bad as I can't tell what they do, especially when you're writing event code for them. <code>button2_click</code> tells me zip.</p></li>\n<li><p>Whitespace can be bad (as in too much between lines), but whitespace in long lists is always <em>good</em>. Ideally avoid going beyond 132 chars, and even then, if you have a long list break it up nicely so it is easily readable. For example:</p>\n\n<pre><code>string[] errorArray = new string[] \n{ \n \"Device is working properly.\", \n \"Device is not configured correctly.\", \n \"Windows cannot load the driver for this device.\", \n \"Driver for this device might be corrupted, or the system may be low on memory or other resources.\", \n \"Device is not working properly. One of its drivers or the registry might be corrupted.\",\n};\n</code></pre></li>\n<li><p>I know you can't put the actual appearance of the form in the code, but hey, it'd be nice to have some idea of what the form looks like and what objects are what. Something like this wouldn't be objectionable (as an example):</p>\n\n<blockquote>\n <p>frmWhatIsYourName looks like this:</p>\n\n<pre><code>+---------------------------------------------------+\n| What is your name? |\n|---------------------------------------------------|\n| |\n| Please enter your name: [txtName ] |\n| |\n| [ Ok ] [ Cancel ] |\n| (btnOk) (btnCancel)|\n+---------------------------------------------------+\n</code></pre>\n</blockquote>\n\n<p>You don't have to get particularly fancy; a verbal description would work as well:</p>\n\n<pre><code>/*\n * The form frmWhatIsYourName has a single text box named txtName for storing\n * the person's name, and two buttons, btnOk (OK) and btnCancel (CANCEL).\n */\n</code></pre></li>\n</ol>\n\n<p>That would make a good start, I think, and there have been good suggestions from everyone else here as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T04:04:03.927", "Id": "2880", "ParentId": "2847", "Score": "6" } }, { "body": "<p>@KerriShotts already mentioned Whitespace in declaring your string arrays, but what no one talks about is the trailing (<code>,</code>) comma in your string array</p>\n\n<pre><code>string[] errorArray = new string[] \n{ \n \"Device is working properly.\", \n \"Device is not configured correctly.\", \n \"Windows cannot load the driver for this device.\", \n \"Driver for this device might be corrupted, or the system may be low on memory or other resources.\", \n \"Device is not working properly. One of its drivers or the registry might be corrupted.\",\n};\n</code></pre>\n\n<p>The compiler won't like this because it will be looking for another item in the array, </p>\n\n<p>It's kind of like writing a list of things but ending with a comma, or not using <code>and</code> before the last item and instead ending the thought with a <code>,</code></p>\n\n<p>You do this in both String Arrays <code>errorArray</code>, and <code>availabilityArray</code></p>\n\n<p><strong><em>Note</em></strong>: it seems that the Compiler just removes the Comma (<em>Visual Studio 2013</em>) but I wouldn't get into the habit of doing this, it isn't compliant with standards I am sure.</p>\n\n<p>Another thing about these two arrays is that the naming isn't the best, personally I would name them something like <code>errorMessages</code> and <code>availabilityMessages</code>. not much of a change, but now I know that the error array isn't an array of exceptions, rather it's an array of type <code>string</code></p>\n\n<p>These should be declared before the constructor because they are class variables, some may disagree on this.</p>\n\n<p>You may want to look into <code>List&lt;string&gt;</code> or even a <code>dictionary</code> for these arrays.</p>\n\n<p>With a dictionary you would have a key/value pair, which might suit your usage a lot better than an array.</p>\n\n<hr>\n\n<p>Your naming conventions allow me to see what is a text box just from looking at the code, but hungarian naming is really going out of style (if it isn't already dead and buried), if you ask anyone on Code Review they will say pretty much the same thing.</p>\n\n<p>Use descriptive variable names, even for form elements. (<em>And don't disemvowel</em>)</p>\n\n<hr>\n\n<p>I noticed that you have newline characters in your string and that one of them is different from the others.</p>\n\n<blockquote>\n<pre><code> , \"Power Save - Low Power Mode\" + \"/n\" + \"The device is in a power save state, but still functioning, and may exhibit degraded performance.\"\n</code></pre>\n</blockquote>\n\n<p>There is no need to concatenate these into the string either, so what you would have for this one is something like this.</p>\n\n<pre><code>, \"Power Save - Unknown /nThe device is known to be in a power save state, but its exact status is unknown.\"\n</code></pre>\n\n<p>no concatenation needed.</p>\n\n<hr>\n\n<p>You have a double assignment inside of your first foreach loop.</p>\n\n<blockquote>\n<pre><code> ManagementObjectCollection queryCollection1 = intquery1.Get();\n queryCollection1 = intquery1.Get();\n</code></pre>\n</blockquote>\n\n<p>completely unnecessary, but I am going to change this in a little bit as well.</p>\n\n<p>You do this in every button click method.</p>\n\n<hr>\n\n<p>your <code>TxtGateway</code> breaks naming first of all and second it is only going to be set to the last <code>gateway</code> in the collection.</p>\n\n<p>Going through your code I see a lot of stuff that is being overwritten over and over again, like </p>\n\n<blockquote>\n<pre><code> if ((bool)mo1[\"DHCPEnabled\"] == true)\n {\n checkBox1.Checked = true;\n }\n if ((bool)mo1[\"DHCPEnabled\"] != true)\n {\n checkBox1.Checked = !true;\n }\n</code></pre>\n</blockquote>\n\n<p>Which is inside of a foreach loop (that is inside a foreach loop), this checkbox is going to get confused because it is set so many times, why don't we set a boolean variable and set the check box once at the end of the method?</p>\n\n<p>Let us also do the same with the <code>TxtGateway</code>: create a variable to hold the value and set the <code>.text</code> once at the end of the method.</p>\n\n<hr>\n\n<p>Pretty sure that this code is left over or accidental double click on the form.</p>\n\n<blockquote>\n<pre><code> private void panel2_Paint(object sender, PaintEventArgs e)\n {\n }\n</code></pre>\n</blockquote>\n\n<p>so let's just get rid of it.</p>\n\n<hr>\n\n<p>In <code>btnPing_Click</code> your comment says that you are resetting the number of pings, but this isn't completely true, the private variable has been declared but no assignment was made, this means that until you set it to 0 it has a value of null.</p>\n\n<p>While we are talking about the <code>pingsSent</code> variable, why are you incrementing it inside of a display method(<code>ShowPingResults</code>)? </p>\n\n<p>In order to check to make sure that you are receiving all ping replies you should increment <code>pingsSent</code> inside of the <code>SendPing</code> method, that way you can compare between pings sent and pings received and see if there is an issue with dropped (pings). </p>\n\n<p>then you can count how many <code>cancelled</code>, <code>error</code>, or <code>reply</code> events you receive to determine what is going on with your pings.</p>\n\n<hr>\n\n<p><code>DateTime</code> objects are nice and neat.</p>\n\n<blockquote>\n<pre><code>DateTime dt = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseExpires\"].ToString());\ntxtDHCPExpires.Text = dt.ToString();\nDateTime dte = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseObtained\"].ToString());\ntxtDHCPObtained.Text = dte.ToString();\n</code></pre>\n</blockquote>\n\n<p>There is no need to create DateTime variables for this, just assign straight to the text field of the textbox like this</p>\n\n<pre><code>txtDHCPExpires.Text = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseExpires\"].ToString());\ntxtDHCPObtained.Text = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseObtained\"].ToString());\n</code></pre>\n\n<hr>\n\n<p>Your <code>Management</code> objects are IDisposable so you should make use of the <code>using</code> construct like your code looks like this </p>\n\n<blockquote>\n<pre><code> private void button2_Click(object sender, EventArgs e)\n {\n try\n {\n ManagementObjectSearcher intquery;\n intquery = new ManagementObjectSearcher(\"SELECT * FROM Win32_NetworkAdapter WHERE Description ='\" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + \"'\");\n ManagementObjectCollection queryCollection = intquery.Get();\n queryCollection = intquery.Get();\n foreach (ManagementObject mo in queryCollection)\n {\n string thisstring = (mo[\"ConfigManagerErrorCode\"].ToString());\n int error;\n int.TryParse(thisstring, out error);\n MessageBox.Show(errorArray[error]);\n }\n }\n catch (Exception ex1)\n {\n MessageBox.Show(\"Please Select a Device\");\n }\n }\n</code></pre>\n</blockquote>\n\n<p>and with using statements stacked nicely it would look like this.</p>\n\n<pre><code>try\n{\n using (ManagementObjectSearcer intquery = new ManagementObjectSearcer(\"SELECT * FROM Win32_NetworkAdapter WHERE Description ='\" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + \"'\"))\n using (ManagementObjectCollection queryCollection = intquery.Get())\n {\n foreach (ManagementObject mo in queryCollection)\n {\n string thisstring = (mo[\"ConfigManagerErrorCode\"].ToString());\n int error;\n int.TryParse(thisstring, out error);\n MessageBox.Show(errorArray[error]);\n }\n }\n}\ncatch (Exception ex1)\n{\n MessageBox.Show(\"Please Select a Device\");\n}\n</code></pre>\n\n<p>and the object will be disposed of appropriately so that there are no leaks anywhere.</p>\n\n<hr>\n\n<p>with all of those changes, this is what the code looks like, I think there is still plenty to do, please feel free to post a follow-up question with your new(er) code!</p>\n\n<pre><code>public partial class Form1 : Form\n{\n private int pingsSent;\n AutoResetEvent resetEvent = new AutoResetEvent(false);\n public Form1()\n {\n {\n InitializeComponent();\n }\n // win32 class\n //http://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx\n try\n {\n ManagementObjectSearcher query = new ManagementObjectSearcher(@\"SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\\\%'\");\n ManagementObjectCollection queryCollection = query.Get();\n foreach (ManagementObject mo in queryCollection)\n {\n if (mo[\"MacAddress\"] != null)\n {\n comboBox1.Items.Add(mo[\"Description\"].ToString());\n }\n }\n }\n catch (Exception ex)\n {\n }\n }\n string[] availabilityArray = new string[] \n { \"\"\n , \"Other\"\n , \"Unknown\"\n , \"Running or Full Power\"\n , \"Warning\", \"In Test\"\n , \"Not Applicable\"\n , \"Power Off\"\n , \"Off Line\"\n , \"Off Duty\"\n , \"Degraded\"\n , \"Not Installed\"\n , \"Install Error\"\n , \"Power Save - Unknown /nThe device is known to be in a power save state, but its exact status is unknown.\"\n , \"Power Save - Low Power Mode\" + \"/n\" + \"The device is in a power save state, but still functioning, and may exhibit degraded performance.\"\n , \"Power Save - Standby\" + \"/n\" + \"The device is not functioning, but could be brought to full power quickly.\"\n , \"Power Cycle\"\n , \"Power Save - Warning\" + \"/n\" + \"The device is in a warning state, though also in a power save state.\" \n };\n string[] errorArray = new string[] \n { \"Device is working properly.\"\n , \"Device is not configured correctly.\"\n , \"Windows cannot load the driver for this device.\"\n , \"Driver for this device might be corrupted, or the system may be low on memory or other resources.\"\n , \"Device is not working properly. One of its drivers or the registry might be corrupted.\"\n , \"Driver for the device requires a resource that Windows cannot manage.\"\n , \"Boot configuration for the device conflicts with other devices.\"\n , \"Cannot filter.\", \"Driver loader for the device is missing.\"\n , \"Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.\"\n , \"Device cannot start.\", \"Device failed.\"\n , \"Device cannot find enough free resources to use.\"\n , \"Windows cannot verify the device's resources.\"\n , \"Device cannot work properly until the computer is restarted.\"\n , \"Device is not working properly due to a possible re-enumeration problem.\"\n , \"Windows cannot identify all of the resources that the device uses.\"\n , \"Device is requesting an unknown resource type.\"\n , \"Device drivers must be reinstalled.\"\n , \"Failure using the VxD loader.\"\n , \"Registry might be corrupted.\"\n , \"System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.\"\n , \"Device is disabled.\", \"System failure. If changing the device driver is ineffective, see the hardware documentation.\"\n , \"Device is not present, not working properly, or does not have all of its drivers installed.\"\n , \"Windows is still setting up the device.\", \"Windows is still setting up the device.\"\n , \"Device does not have valid log configuration.\", \"Device drivers are not installed\"\n , \"Device is disabled. The device firmware did not provide the required resources.\"\n , \"Device is using an IRQ resource that another device is using.\"\n , \"Device is not working properly. Windows cannot load the required device drivers.\"\n };\n private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n {\n using (ManagementObjectSearcher intquery = new ManagementObjectSearcher(\"SELECT * FROM Win32_NetworkAdapter WHERE Description ='\" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + \"'\"))\n using (ManagementObjectCollection queryCollection = intquery.Get())\n {\n foreach (ManagementObject mo in queryCollection)\n {\n string Dev = (mo[\"DeviceID\"].ToString());\n txtMacAdd.Text = (\" \" + mo[\"MacAddress\"].ToString());\n TxtAdapter.Text = (\" \" + mo[\"AdapterType\"].ToString());\n txtAvailability.Text = (\" \" + mo[\"Availability\"].ToString());\n txtCaption.Text = (\" \" + mo[\"Caption\"].ToString());\n txtDeviceID.Text = (\" \" + mo[\"DeviceID\"].ToString());\n txtErrorCode.Text = (mo[\"ConfigManagerErrorCode\"].ToString());\n using (ManagementObjectSearcher intquery1 = new ManagementObjectSearcher(\"ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID='\" + Dev + \"'}WHERE ResultClass=Win32_NetworkAdapterConfiguration\"))\n using (ManagementObjectCollection queryCollection1 = intquery1.Get())\n {\n foreach (ManagementObject mo1 in queryCollection1)\n {\n string[] addresses = (string[])mo1[\"IPAddress\"];\n string[] gateways = (string[])mo1[\"DefaultIPGateway\"];\n string[] Subnets = (string[])mo1[\"IPSubnet\"];\n foreach (string ipaddress in addresses)\n {\n listIp.Items.Add(ipaddress);\n }\n foreach (string gateway in gateways)\n {\n TxtGateway.Text = (gateway);\n }\n foreach (string subnet in Subnets)\n {\n listSubnet.Items.Add(subnet);\n }\n /////// SHOW DCHP CONFIG/////////\n\n checkBox1.Checked = mo1[\"DHCPEnabled\"];\n\n txtDHCPExpires.Text = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseExpires\"].ToString());\n txtDHCPObtained.Text = System.Management.ManagementDateTimeConverter.ToDateTime(mo1[\"DHCPLeaseObtained\"].ToString());\n txtDHCPServer.Text = (mo1[\"DHCPServer\"].ToString());\n //Security\n chkboxIPFilter.Checked = mo1[\"IPFilterSecurityEnabled\"];\n\n string[] IPSecProtocols = (string[])mo1[\"IPSecPermitIPProtocols\"];\n string[] IPSecPermitTCPPorts = (string[])mo1[\"IPSecPermitTCPPorts\"];\n string[] IPSecPermitUDPPorts = (string[])mo1[\"IPSecPermitUDPPorts\"];\n foreach (string IPSecProtocol in IPSecProtocols)\n {\n listPermitIP.Items.Add(IPSecProtocol);\n }\n foreach (string TCPPort in IPSecPermitTCPPorts)\n {\n listPermitTCP.Items.Add(TCPPort);\n }\n foreach (string UDPPort in IPSecPermitUDPPorts)\n {\n listPermitUDP.Items.Add(UDPPort);\n }\n //DNS\n try\n {\n txtDNSDomain.Text = (mo1[\"DNSDomain\"].ToString());\n txtDNShostName.Text = (mo1[\"DNSHostName\"].ToString());\n string[] DNSDomainSuffSearch = (string[])mo1[\"DNSDomainSuffixSearchOrder\"];\n string[] DNSServerSearchOrder = (string[])mo1[\"DNSServerSearchOrder\"];\n foreach (string domainSuff in DNSDomainSuffSearch)\n {\n listDomainSuffSearchOrder.Items.Add(domainSuff);\n }\n foreach (string DNSServer in DNSServerSearchOrder)\n {\n listDNSServerSearchOrder.Items.Add(DNSServer);\n }\n\n chkDNSWinsResolution.Checked = mo1[\"DNSEnabledForWINSResolution\"];\n chkDNSRegEnabled.Checked = mo1[\"DomainDNSRegistrationEnabled\"];\n }\n catch (Exception ex3)\n { }\n }\n }\n }\n }\n }\n private void button2_Click(object sender, EventArgs e)\n {\n try\n {\n using (ManagementObjectSearcer intquery = new ManagementObjectSearcer(\"SELECT * FROM Win32_NetworkAdapter WHERE Description ='\" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + \"'\"))\n using (ManagementObjectCollection queryCollection = intquery.Get())\n {\n foreach (ManagementObject mo in queryCollection)\n {\n string thisstring = (mo[\"ConfigManagerErrorCode\"].ToString());\n int error;\n int.TryParse(thisstring, out error);\n MessageBox.Show(errorArray[error]);\n }\n }\n }\n catch (Exception ex1)\n {\n MessageBox.Show(\"Please Select a Device\");\n }\n }\n private void BtnAvailability_Click(object sender, EventArgs e)\n {\n try\n {\n using (ManagementObjectSearcher intquery = new ManagementObjectSearcher(\"SELECT * FROM Win32_NetworkAdapter WHERE Description ='\" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + \"'\"))\n using (ManagementObjectCollection queryCollection = intquery.Get())\n {\n foreach (ManagementObject mo in queryCollection)\n {\n string thisstring = (mo[\"Availability\"].ToString());\n int Avail;\n int.TryParse(thisstring, out Avail);\n MessageBox.Show(availabilityArray[Avail]);\n }\n }\n }\n catch (Exception ex2)\n {\n MessageBox.Show(\"Please Select a Device\");\n }\n }\n private void btnPing_Click(object sender, EventArgs e)\n {\n // Reset the number of pings\n pingsSent = 0;\n // Clear the textbox of any previous content\n txtResponse.Clear();\n txtResponse.Text += \"Pinging \" + txtIP.Text + \" with 32 bytes of data:\\r\\n\\r\\n\";\n // Send the ping\n SendPing();\n }\n private void SendPing()\n {\n System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();\n // Create an event handler for ping complete\n pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);\n // Create a buffer of 32 bytes of data to be transmitted.\n byte[] packetData = Encoding.ASCII.GetBytes(\"................................\");\n // Jump though 50 routing nodes tops, and don't fragment the packet\n PingOptions packetOptions = new PingOptions(50, true);\n // Send the ping asynchronously\n pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent);\n }\n private void pingSender_Complete(object sender, PingCompletedEventArgs e)\n {\n // If the operation was canceled, display a message to the user.\n if (e.Cancelled)\n {\n txtResponse.Text += \"Ping was canceled...\\r\\n\";\n // The main thread can resume\n ((AutoResetEvent)e.UserState).Set();\n }\n else if (e.Error != null)\n {\n txtResponse.Text += \"An error occured: \" + e.Error + \"\\r\\n\";\n // The main thread can resume\n ((AutoResetEvent)e.UserState).Set();\n }\n else\n {\n PingReply pingResponse = e.Reply;\n // Call the method that displays the ping results, and pass the information with it\n ShowPingResults(pingResponse);\n }\n }\n public void ShowPingResults(PingReply pingResponse)\n {\n if (pingResponse == null)\n {\n // We got no response\n txtResponse.Text += \"There was no response.\\r\\n\\r\\n\";\n return;\n }\n else if (pingResponse.Status == IPStatus.Success)\n {\n // We got a response, let's see the statistics\n txtResponse.Text += \"Reply from \" + pingResponse.Address.ToString() + \": bytes=\" + pingResponse.Buffer.Length + \" time=\" + pingResponse.RoundtripTime + \" TTL=\" + pingResponse.Options.Ttl + \"\\r\\n\";\n }\n else\n {\n // The packet didn't get back as expected, explain why\n txtResponse.Text += \"Ping was unsuccessful: \" + pingResponse.Status + \"\\r\\n\\r\\n\";\n }\n // Increase the counter so that we can keep track of the pings sent\n string strpings = txtNumPackets.Text;\n int numbpings = int.Parse(strpings);\n if (txtNumPackets.Text == null)\n {\n numbpings = 4;\n }\n pingsSent++;\n // Send 4 pings\n if (pingsSent &lt; numbpings)\n {\n SendPing();\n }\n }\n}\n</code></pre>\n\n<p>As you can see I left the pinger alone, I didn't want to get pinged.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-08T13:48:33.657", "Id": "65086", "ParentId": "2847", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T09:03:12.650", "Id": "2847", "Score": "14", "Tags": [ "c#", ".net", "networking" ], "Title": "Showing various network information from a NIC card" }
2847
<p>How does this recursive selection sort look to everyone here? Am I missing anything 'pythonic' about the way I have done it?</p> <pre><code>def selection_sort(li, out=None): if out is None: out = [] li = li[:] if len(li) == 0: return out small = min(li) li.remove(small) out.append(small) return selection_sort(li, out) </code></pre>
[]
[ { "body": "<pre><code>def selection_sort(li, out=None):\n</code></pre>\n\n<p>I dislike the name \"li,\" I think abbreviations are bad.</p>\n\n<pre><code> if out is None:\n out = [] \n li = li[:]\n</code></pre>\n\n<p>Rather then using the out parameter to do this, I suggest creating a seperate internal function which is called. Otherwise, it looks like the caller to the function might reasonable pass out = something, when its only meant to be used internally.</p>\n\n<pre><code> if len(li) == 0:\n return out\n</code></pre>\n\n<p>Better to use <code>if not li:</code></p>\n\n<pre><code> small = min(li)\n li.remove(small)\n out.append(small)\n return selection_sort(li, out)\n</code></pre>\n\n<p>Its a little hard to gauge this code because you are doing two things you shouldn't, using recursion when its not necessary and implementing your own sort routine. But if you are doing so for learning purposes that's fine.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Iterative solution:</p>\n\n<pre><code>def selection_sort(li):\n li = li[:]\n out = []\n\n while li:\n smallest = min(li)\n li.remove(smallest)\n out.append(smallest)\n\n return out\n</code></pre>\n\n<p>But why is this better than the recursive solution:</p>\n\n<ol>\n<li>There is a limit to your stack space. If you try to sort a large list using this function you'll get a RuntimeError</li>\n<li>Calling a function has extra overhead that iterating in a loop does not, the iterative version will be faster</li>\n<li>A loop is usually easier to read then recursion. The while loop makes it easy to see whats doing on, whereas the recursive version requires some thought about the code to see the logic.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:06:54.487", "Id": "4399", "Score": "0", "body": "Aye learning, and why not recursion for this situation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:18:50.980", "Id": "4400", "Score": "0", "body": "@Jakob, see edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T01:09:09.093", "Id": "4554", "Score": "0", "body": "+1: amplifying \"don't have output parameters\". Given Python's ability to return arbitrary tuples, there is never a reason to use an output parameter. For example: `return (a_list, a_dict_of_dicts, status)` is valid and idiomatic. Also pay attention to the difference between list.sort() and list.sorted() in the standard library (hint: one returns a value, the other doesn't, why?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T23:14:03.037", "Id": "4559", "Score": "0", "body": "@msw, I wouldn't quite say \"never.\" For example, numpy has reasonable use of out parameters for efficiency reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T10:04:35.483", "Id": "4564", "Score": "0", "body": "Fair 'nuff. How about \"unless you know whyfor\"?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:06:23.740", "Id": "2856", "ParentId": "2855", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T18:34:22.767", "Id": "2855", "Score": "4", "Tags": [ "python", "algorithm", "recursion" ], "Title": "Selection sort using recursion" }
2855
<p>I have an account page where I have three forms. A user can change his name, his email address, and his password.</p> <p>There are two difficulties I am having from trying to do this:</p> <p>1) the request.user information is not updating accordingly (e.g., it will lag behind by one change or it will update if the form is not validated)</p> <p>2) I have three separate forms, however, when I submit one form, I will get validation messages from another form. For example, if I submit the "Change Name" form, I will get <code>'This field is required</code> from the password fields in the password form. Here is what I currently have -- </p> <p>in forms:</p> <pre><code># in forms.py from django.contrib.auth.models import User class ChangeNameForm(ModelForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ('first_name', 'last_name' ) class ChangeEmailForm(ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('email',) </code></pre> <p>in views:</p> <pre><code>@login_required def account(request): name_message = password_message = email_message = '' change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user) change_password_form = PasswordChangeForm(data=request.POST or None, user = request.user) change_email_form = ChangeEmailForm(data=request.POST or None, instance=request.user) if request.method == "POST": if "change_name" in request.POST and change_name_form.is_valid(): change_name_form.save() name_message = 'Your name has been changed.' if "change_password" in request.POST and change_password_form.is_valid(): change_password_form.save() password_message = 'Your password has been changed.' if "change_email" in request.POST and change_email_form.is_valid(): ... email_message = 'Please click the link in your email to confirm changes.' return render_to_response('userprofile/account.html', {'change_name_form': change_name_form, 'change_email_form': change_email_form, 'change_password_form': change_password_form, 'password_message': password_message, 'name_message': name_message, 'email_message': email_message,}, context_instance=RequestContext(request)) </code></pre> <p>in template:</p> <pre><code>&lt;h3&gt;Change Name&lt;/h3&gt; &lt;form method="post" action="/account/change/" name='name'&gt; {% csrf_token %} &lt;h4&gt;Change name: {{user.first_name}} {{user.last_name}}&lt;/h4&gt; &lt;table&gt;{{change_name_form.as_table}}&lt;/table&gt; &lt;p&gt;{{name_message}}&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Save Changes" name="change_name"/&gt;&lt;/p&gt; &lt;/form&gt; &lt;h3&gt;Change Email&lt;/h3&gt; &lt;form method="post" action="/account/change/" name='email'&gt; {% csrf_token %} &lt;h4&gt;Change email: {{user.email}}&lt;/h4&gt; &lt;table&gt;{{change_email_form.as_table}}&lt;/table&gt; &lt;p&gt;{{email_message}}&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Save Changes" name="change_email" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;h3&gt;Change Password&lt;/h3&gt; &lt;form method="post" action="/account/change/" name='password'&gt; {% csrf_token %} &lt;h4&gt;Change password&lt;/h4&gt; &lt;table&gt;{{change_password_form.as_table}}&lt;/table&gt; &lt;p&gt;{{password_message}}&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Save Changes" name="change_password"/&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>What do I need to do to solve the two issues of making sure the request.user information is current and making sure validation only runs for the current form? Also, would it be possible to run a <code>for loop</code> to reduce redundancy in the template code? If so, how would I do this given the fact that the two <code>name</code> fields?. Thank you.</p>
[]
[ { "body": "<p>Somewhere on \"Stack Overflow\" was question like your.</p>\n\n<p>Main idea was remove <code>None</code> from form initialization.</p>\n\n<pre><code>if \"change_name\" in request.POST:\n change_name_form = ChangeNameForm(data=request.POST, instance=request.user)\n if change_name_form.is_valid():\n change_name_form.save()\n name_message = 'Your name has been changed.'\nelse:\n change_name_form = ChangeNameForm(instance=request.user)\n\nif \"change_password\" in request.POST:\n change_password_form = PasswordChangeForm(user=request.user)\n if change_password_form.is_valid():\n change_password_form.save() \n password_message = 'Your password has been changed.'\nelse:\n change_password_form = PasswordChangeForm(user=request.user)\n\nif \"change_email\" in request.POST:\n change_email_form = ChangeEmailForm(request.POST, instance=request.user)\n if change_email_form.is_valid():\n ...\n email_message = 'Please click the link in your email to confirm changes.'\nelse:\n change_email_form = ChangeEmailForm(instance=request.user)\n</code></pre>\n\n<p>This is my solution. I hope it's help you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T22:18:24.147", "Id": "4418", "Score": "0", "body": "Thank you for the answer. Could you please elaborate on why you'd remove `None`. What is the advantage of doing so?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T05:21:29.363", "Id": "4424", "Score": "0", "body": "For your case, when you commit any form `request.POST` isn't empty and you put it into all your forms. Then form got any POST data it become **bound** form, and fields already have error attribute after this form become bound. https://docs.djangoproject.com/en/1.3/ref/forms/api/#django.forms.BoundField.errors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T10:36:39.787", "Id": "4432", "Score": "1", "body": "I think there is one more solution, form prefixes. https://docs.djangoproject.com/en/1.3/ref/forms/api/#prefixes-for-forms" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T14:29:04.283", "Id": "2876", "ParentId": "2857", "Score": "5" } } ]
{ "AcceptedAnswerId": "2876", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:20:43.630", "Id": "2857", "Score": "3", "Tags": [ "python", "django" ], "Title": "Multiple forms in django" }
2857
<p>I was reading <em>Mathematics: A Very Short Introduction</em> and it mentioned prime factorization. Being a curious person I had to write my own implementation in Perl.</p> <p>This program outputs the prime factorization of the numbers between 0 and 1001. </p> <p>I don't like listing all of my subroutines before everything else, but I'm not sure what would be a better alternative.</p> <p>Also, I remember seeing somewhere a non-bruteforce way of discovering whether a number is a prime. Does anyone have any ideas? I'm a beginner/intermediate Perl programmer and would appreciate suggestions on improving my technique.</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use 5.010; #This array will contian the results of the factorization our @result; sub factorize { my($num,$factorsRef) = @_; # If the only factor is 1, it is a prime number # return the number itself since primes don't # factorize in the known universe if(${$factorsRef}[0] == 1) { push @result, $num; return; } if($num % ${$factorsRef}[0] == 0) { push @result, ${$factorsRef}[0]; my $divResult = $num/${$factorsRef}[0]; # If the result of the division is a prime # we have reached the end of the process if(isPrime($divResult)) { push @result, ($divResult); # If it is not a prime, go down to the # next level } else { factorize($divResult,$factorsRef); } # If the number is no longer divisible by the # current factor, take the factor out so that # the function can use te next factor } else { shift @{$factorsRef}; factorize($num,$factorsRef); } } sub getPrimeFactors { my $num = shift; my $counter = 1; my @primeFactors; if(isPrime($num)) { push @primeFactors, 1; return \@primeFactors; } while($counter++ &lt;= ($num / 2)) { next unless $num % $counter == 0; push @primeFactors, $counter if(isPrime($counter)); } return \@primeFactors; } sub isPrime { my $num = shift; my $limit = $num/2; for(my $i=2; $i&lt;=$limit ;$i++) { if ($num%$i == 0) { return 0;} } return 1; } sub printResults { my $num = shift; print $num . ' = ' . shift @result; print " x $_" for @result; print "\n"; } # Where everything happens for(1..1000) { my $num = $_; factorize($num,getPrimeFactors($num)); printResults($num); @result = (); } </code></pre> <p>Sample output:</p> <blockquote> <pre><code>983 = 983 984 = 2 x 2 x 2 x 3 x 41 985 = 5 x 197 986 = 2 x 17 x 29 987 = 3 x 7 x 47 988 = 2 x 2 x 13 x 19 989 = 23 x 43 990 = 2 x 3 x 3 x 5 x 11 991 = 991 992 = 2 x 2 x 2 x 2 x 2 x 31 993 = 3 x 331 994 = 2 x 7 x 71 995 = 5 x 199 996 = 2 x 2 x 3 x 83 997 = 997 998 = 2 x 499 999 = 3 x 3 x 3 x 37 1000 = 2 x 2 x 2 x 5 x 5 x 5 </code></pre> </blockquote>
[]
[ { "body": "<p>There are a few things which can improve this logic:</p>\n\n<ul>\n<li>In order to find out whether a number <em>n</em> is prime, you only need to go up to <em>sqrt(n)</em>, not <em>n/2</em>; that will speed up the prime validation considerably for large numbers.</li>\n<li>Also, if you're verifying whether a sequence of numbers are primes, you should store the previous results instead of starting from scratch all the time. The function below calculates the primes from 2-1000, which is a good \"pre-processing\" step for your function (factorizing is now a matter of traversing only that prime numbers list)</li>\n</ul>\n\n<p>Calculate prime numbers from 1..1000:</p>\n\n<pre><code>use strict;\n\nmy @primes;\nmy $i;\n\nfor my $i (2..1000) {\n my $isPrime = 1;\n my $sqrt = int(sqrt($i));\n for my $j (@primes) {\n if (($i % $j) == 0) {\n $isPrime = 0;\n last;\n }\n last if $j &gt; $sqrt;\n }\n if ($isPrime) {\n push @primes, $i;\n }\n}\n\nprint join(\", \", @primes);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T14:42:38.217", "Id": "4413", "Score": "0", "body": "Would +1 if I had the ability. It is unclear to me how the `$j` loop can work if you start with an empty `@primes` array. Won't the loop immediately break and end the program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T15:11:27.953", "Id": "4415", "Score": "0", "body": "The $j loop at first simply won't loop at all, it will just go to the next line (if $isPrime), which will be true, and it will add the first element to the prime array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-17T08:34:59.023", "Id": "184915", "Score": "0", "body": "I'd add some small value to the square-root to ensure that floating point rounding won't cause you to skip the last check." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T05:07:27.290", "Id": "2865", "ParentId": "2858", "Score": "4" } } ]
{ "AcceptedAnswerId": "2865", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T21:09:00.533", "Id": "2858", "Score": "2", "Tags": [ "primes", "perl" ], "Title": "Prime factorization of numbers up to 1000" }
2858
<p>Looking for a code review, and hopefully to learn something if someone has a nicer solution. Here's what I wrote:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import division, print_function from future_builtins import * import numpy as np def _walk(num_dims, samples_per_dim, max_): if num_dims == 0: yield np.array([(max_ - 1) / (samples_per_dim - 1)]) else: for i in range(max_): for rest in _walk(num_dims - 1, samples_per_dim, max_ - i): yield np.concatenate((np.array([i]) / (samples_per_dim - 1), rest)) def walk(num_dims, samples_per_dim): """ A generator that returns lattice points on an n-simplex. """ return _walk(num_dims, samples_per_dim, samples_per_dim) </code></pre> <p>So, <code>list(walk(2, 3))</code> yields:</p> <pre><code>[array([ 0., 0., 1.]), array([ 0. , 0.5, 0.5]), array([ 0., 1., 0.]), array([ 0.5, 0. , 0.5]), array([ 0.5, 0.5, 0. ]), array([ 1., 0., 0.])] </code></pre>
[]
[ { "body": "<p>Concatenating numpy arrays isn't a really good idea because that's not how they were designed to be used.</p>\n\n<p>A better way might be this:</p>\n\n<pre><code>def walk(num_dims, samples_per_dim):\n \"\"\"\n A generator that returns lattice points on an n-simplex.\n \"\"\"\n values = np.arange(samples_per_dim) / (samples_per_dim - 1)\n for items in itertools.product(values, repeat = num_dims+1):\n if sum(items) == 1.0:\n yield items\n</code></pre>\n\n<p>Basically, we iterate over all possible combinations of those points, and filter out the invalid ones. This may seem wasteful, but since itertools is written in C, its probably actually faster then your solution. It produces tuples rather then numpy arrays.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T02:15:25.383", "Id": "4402", "Score": "0", "body": "Thanks. Why not use `linspace` instead of `arange`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T02:16:59.347", "Id": "4403", "Score": "0", "body": "Also, have you tested this code? Why don't floating point precision errors cause problems with the comparison to 1.0?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T03:54:57.583", "Id": "4405", "Score": "0", "body": "@Niel, I was not aware of linspace. That would be better. I did test it. I'm not sure why floating point isn't a problem..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T23:43:23.320", "Id": "2861", "ParentId": "2860", "Score": "2" } }, { "body": "<p>Using Winston Ewert's suggestions of using itertools, and using lists instead of numpy arrays internally, here's an alternate solution:</p>\n\n<pre><code>def walk(num_dims, samples_per_dim):\n \"\"\"\n A generator that returns lattice points on an n-simplex.\n \"\"\"\n max_ = samples_per_dim + num_dims - 1\n for c in combinations(range(max_), num_dims):\n c = list(c)\n yield [(y - x - 1) / (samples_per_dim - 1)\n for x, y in izip([-1] + c, c + [max_])]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T07:19:43.093", "Id": "2868", "ParentId": "2860", "Score": "1" } } ]
{ "AcceptedAnswerId": "2868", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T22:41:43.537", "Id": "2860", "Score": "2", "Tags": [ "python", "generator" ], "Title": "Python generator to produce lattice points on an n-simplex." }
2860
<p>I've made a quick <code>finally</code> type in C++:</p> <pre><code>template&lt;class F&gt; class finally_type { public: explicit finally_type(F f) : function(f) {} ~finally_type() { try { function(); } catch (...) {} } private: F function; }; template&lt;class F&gt; finally_type&lt;F&gt; finally(F f) { return finally_type&lt;F&gt;(f); } </code></pre> <p>(Edited to add swallower to prevent exceptions from propagating out of the callback.)</p> <p>With C++0x, it's convenient to use this class as follows:</p> <pre><code>void test() { int* i = new int; auto cleanup = finally([i]() { delete i; }); may_throw(); } </code></pre> <p>Regardless of whether <code>may_throw()</code> throws, the <code>finally</code> ensures that the cleanup code executes when the stack is unwound. The equivalent idiom in C++03 is using a local type:</p> <pre><code>void test() { int* i = new int; struct finally { finally(int* i) : i(i) {} ~finally() { delete i; } int* i; } cleanup(i); may_throw(); } </code></pre> <p>As you can see, the closure must be managed explicitly, with loads of repetitive (and consequently error-prone) code; with a lambda, this process is vastly simplified.</p> <p>Frankly, I don't see much use to it, since if you're interfacing with legacy code, you're probably just going to wrap the types or use a <code>shared_ptr</code> with a custom deleter. You <em>could</em> use it to manage low-level locks in multithreaded code, if that's your fancy for some reason.</p> <p>Anyway, assuming someone does find it useful, is there anything important that I missed?</p>
[]
[ { "body": "<p>Bear in mind that code inside the function called by <code>finally</code> must not allow exceptions to propagate out, or you end up with problems when the destructor is called while cleaning up an exception in the calling code. You might want to put a <code>catch(...)</code> block in the <code>finally_type</code> destructor for that reason.</p>\n\n<p>I agree that the C++98 solution is much uglier, to the point of not being usable. C++98 is never going to be able to capture arbitrary code for execution later. I'm not so sure this is a problem though, since I expect the cleanup code to have to be specialised only per-<em>type</em>, not per-usage. I want the class to be responsible for cleaning itself up, not the client of the class, since the latter can lead to mistakes or redundancy. The most idiomatic solution is to put this cleanup code in the destructor.</p>\n\n<p><strong>Edit</strong>: If you have to support a non-RAII class with an arbitrary cleanup method, then you can make a scoped holder that will call the method for you. It proved more fiddly than I expected, here's the best I could come up with:</p>\n\n<pre><code>class ScopedAction {\n public:\n virtual ~ScopedAction() = 0;\n};\n\nScopedAction::~ScopedAction() {\n}\n\ntemplate&lt;class T, class Arg1, void (T::* p)(Arg1)&gt;\nclass SpecialisedScopedAction : public ScopedAction {\n public:\n SpecialisedScopedAction(T &amp;target, Arg1 &amp;arg) : target_(target), arg_(arg) { }\n ~SpecialisedScopedAction() {\n try {\n (target_.*p)(arg_);\n }\n catch (...)\n {}\n }\n\n private:\n T &amp;target_;\n Arg1 &amp;arg_;\n};\n\nclass ScopedActionHolder {\n public:\n ScopedActionHolder(ScopedAction * action) : action_(action) {}\n ~ScopedActionHolder() {\n delete action_;\n }\n\n private:\n ScopedAction * action_;\n};\n\ntemplate&lt;class T, class Arg1, void (T::* fn)(Arg1)&gt;\nScopedAction * makeScopedAction(T &amp; t, Arg1 &amp; arg) {\n return new SpecialisedScopedAction&lt;T, Arg1, fn&gt;(t, arg);\n}\n</code></pre>\n\n<p>Using the following non-RAII class:</p>\n\n<pre><code>enum TransactionState {\n COMMIT,\n ROLLBACK\n};\n\nclass DBConnection {\n public:\n void finish(TransactionState state) {\n if (state == COMMIT) {\n cout &lt;&lt; \"committing transaction\" &lt;&lt; endl;\n } else {\n cout &lt;&lt; \"rolling back transaction\" &lt;&lt; endl;\n }\n }\n};\n</code></pre>\n\n<p>You can make a scoped object that calls the <code>finish</code> method, binding in a parameter from local scope like this:</p>\n\n<pre><code>void test() {\n DBConnection conn;\n TransactionState tstate = ROLLBACK;\n\n ScopedActionHolder cleanup(makeScopedAction&lt;DBConnection, TransactionState, &amp;DBConnection::finish&gt;(conn, tstate));\n\n cout &lt;&lt; \"Doing something\" &lt;&lt; endl;\n tstate = COMMIT;\n}\n</code></pre>\n\n<p>Having to specify the types as template arguments even though they're implicit in the member function pointer type is annoying, I was hoping to work around this but I've run out of time. Also, the syntax is non-obvious and it'll need a new overload of the <code>makeScopedAction</code> function for every different number of method parameters that needs to be supported.</p>\n\n<p>Come to think about it, <code>std::functional</code> or <code>boost::lambda</code> may both be of some help here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T22:31:16.887", "Id": "4419", "Score": "0", "body": "Interesting. This would benefit greatly from variadic templates, but of course that would defeat the purpose of a non-C++0x solution. It's also an interesting complement to the `finally` I proposed, since a lambda may be punctuation overkill in certain situations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T13:13:05.897", "Id": "4434", "Score": "0", "body": "Yes, lack of variadic templates kills a lot of my neat ideas for templates, such as in my answer to [this question](http://codereview.stackexchange.com/questions/2484/generic-c-exception-catch-handler-macro). I never got round to learning C++0x, maybe I should take a look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T08:44:23.917", "Id": "81894", "Score": "0", "body": "While considering the fault case you now forgot the normal case where the destructor is called when going out of scope without an exception. In this case you would want exceptions to propagate. I think it would be better to not catch exceptions in the wrapper and let the cleanup function handle exceptions or be aware that leaking an exception can lead to termination. (`std::uncaught_exception` might come in handy here)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T14:12:18.540", "Id": "2875", "ParentId": "2864", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T01:39:37.210", "Id": "2864", "Score": "5", "Tags": [ "c++", "c++11", "exception" ], "Title": "An implementation of \"finally\" in C++0x" }
2864
<p>I'm creating a chat UI with jQueryUI:</p> <pre><code>$.widget("ui.chatwindow", { options: { nickname: "obama"; }, setNickname: function(nick){ var self = this; var id_pre = 'wchat_' + self.options.nickname; $('#' + id_pre + '\\:name').text(self.options.nickname); }, setStatus: function(status){ var self = this; var id_pre = 'wchat_' + self.options.nickname; switch(status){ case 1: $('#' + id_pre + '\\:status').removeAttr('class'); $('#' + id_pre + '\\:status').addClass('chat-icon-online'); $('#' + id_pre + '\\:status').attr('title','Online'); break; ... default: break; } ... }, ... } </code></pre> <p>I always write this in every method to change element class or text content:</p> <pre><code>var self = this; var id_pre = 'wchat_' + self.options.nickname; </code></pre> <p>Is this a good or efficient way to code?</p>
[]
[ { "body": "<p>I can't say there's anything <em>technically</em> wrong with doing it that way, and maybe some people who are only familiar with \"self\" in certain languages will get the point, but I think \"this\" is just as readable, and it saves you some code (along with some of us wondering where in the world \"self\" was defined if we're looking at a lot of code where the declaration isn't obvious).</p>\n\n<p>So short of adding some extra work for yourself (and raising a couple of eyebrows), I don't see a big problem with it. Do you need it? No. Will it hurt? Not likely.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T03:46:10.953", "Id": "2879", "ParentId": "2867", "Score": "2" } }, { "body": "<p>I completely agree with Kerri, but there is one good reason one may do this, namely if you need to reference your widget inside a closure or other anonymous function.</p>\n\n<p>Example:</p>\n\n<pre><code> // ...\n setStatus: function(status) {\n var self = this;\n window.setTimeout(function() {\n // If you try to access \"this\" here, if will no longer \n // be referring to your widget. You have to use your \n // variable \"self\" here.\n }, 1000);\n // ...\n }, \n // ... \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T09:43:35.727", "Id": "2906", "ParentId": "2867", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T06:12:59.060", "Id": "2867", "Score": "2", "Tags": [ "javascript", "jquery", "jquery-ui", "chat" ], "Title": "jQuery Chat UI Widget" }
2867
<p>I want to write an article giving a Haskell introduction specifically to Java developers, and would like to get feedback on my implementation. Please keep in mind that I don't want to be "too clever", as too advanced Haskell concepts would only confuse the readers. On the other hand I need to show some really interesting features (e.g. that's why I decided to use <code>Edge a a Double</code> and a type class instance instead of a simple <code>(String, String, Double)</code>), else the readers would ask "And where is the advantage over Java?". So I need a good balance between clarity and "interesting stuff", showing a nice example of Haskell's expressiveness.</p> <pre><code>module Prim ( prim, Edge(..) ) where import Data.List(sort, deleteBy) import Data.Set(member, empty, insert, singleton, Set) data Edge a = Edge a a Double deriving (Eq, Show) instance Ord a =&gt; Ord (Edge a) where compare (Edge a b c) (Edge d e f) = (c, min a b, max a b) `compare` (f, min d e, max d e) prim [] = [] prim edges = loop (sort edges) [] startSet where startSet = singleton (startNode edges) startNode ((Edge node _ _):_) = node loop [] solution _ = solution loop edges solution vertices = let (e,x) = findNextEdge edges vertices vertices' = x `insert` vertices cyclicEdge (Edge a b _) = a `member` vertices' &amp;&amp; b `member` vertices' edges' = filter (not.cyclicEdge) edges in loop edges' (e:solution) vertices' findNextEdge [] vs = error ("Disjunct graph with island " ++ show vs) findNextEdge (e@(Edge a b _):edges) vertices | a `member` vertices = (e,b) | b `member` vertices = (e,a) | otherwise = findNextEdge edges vertices </code></pre> <p>In particular, I'm interested in these concepts:</p> <ul> <li>Type inference</li> <li>Laziness, immutability</li> <li>Currying</li> <li>Pattern matching, guards</li> <li>ADTs and type polymorphism</li> </ul>
[]
[ { "body": "<ul>\n<li>Java developers prefer intention revealing names as opposed to mathematical single letter identifiers. So it might be better to use <code>edge</code> instead of <code>e</code> and so on.</li>\n<li>Most common type parameter name in Java is <code>T</code> as opposed to <code>a</code>, so maybe using at least 't' (if not a normal name like <code>nodeType</code>) to prevent confusion and better explain ADTs.</li>\n<li><code>loop</code> might look like a syntax construct, especially because its definition follows afterwards.</li>\n<li>Just a detail, but <code>initialSet</code> instead of <code>startSet</code> would be clearer to me - same holds for <code>startNode</code>.</li>\n<li>I would replace <code>where</code> with <code>let</code>, because it would make one construct less (although idiomatic one) and it is a convention in mainstream languages to write declarations/definitions before use.</li>\n<li>I would also adjust 'loop' signature, so the solution isn't between input arguments - I wold make it the last argument.</li>\n<li>I wouldn't use the apostrophe ('), although I understand it is common in math and theory of programming, but among backquoutes (`) for infix operators it might be confusing.</li>\n<li>I think it would help if the function composition operator (.) was surrounded with whitespace - it would better show that it is a different kind of '.' than the one in <code>import Data.List(sort, deleteBy)</code>, which might be easier to understand for Java developers.</li>\n</ul>\n\n<p>I am not a Haskell guru and I don't have 10+ years of Java experience, so take this as a personal opinion. It might also help quite a lot to show the same implemented in Java - the benefits of features you describe and syntax constructs would be clearer. Feel free to comment on this answer, I am open to discussion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T20:12:06.527", "Id": "3383", "ParentId": "2870", "Score": "5" } } ]
{ "AcceptedAnswerId": "3383", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T08:15:08.253", "Id": "2870", "Score": "14", "Tags": [ "haskell", "tree" ], "Title": "Prim's algorithm for minimal spanning trees" }
2870
<p>I'm looking for the fastest way to find all neighbours of a vertex in an undirected <code>Graph</code>. Please improve on the code if possible.</p> <pre><code>neighbours[g_Graph, v_] := Module[ {vl = VertexList[g], pos}, pos = Position[vl, v][[1, 1]]; Pick[VertexList[g], AdjacencyMatrix[g][[pos]], 1] ] </code></pre> <p>I need it to work fast both for sparse and dense graphs.</p> <ol> <li>It is essential to the performance of this solution that it uses <code>SparseArray</code>s.</li> <li>This is a bottleneck in my application. Since my graph is constantly changing, trying to precompute neighbours or using memoization will complicate things significantly.</li> </ol> <p>I'd like to stress that speed is essential here. Here's a graph to test on:</p> <pre><code>max = 4000; c = 0.3; tg = RandomGraph[{max, Round[c max^2]}]; neighbours[tg, 1]; // Timing </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T00:51:45.250", "Id": "59399", "Score": "0", "body": "There is a [Neighborhood](http://reference.wolfram.com/mathematica/Combinatorica/ref/Neighborhood.html) function in the Combinatorica package.\nI would expect their implementation to be as fast as possible.\nHave you compared it to yours in terms of performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T07:45:42.883", "Id": "59400", "Score": "0", "body": "Yes, someone else suggested it in a now deleted reply. Unexpectedly and unfortunately `Neighborhood` is much slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T08:14:42.650", "Id": "59401", "Score": "0", "body": "Another idea is to use [EdgeList](http://reference.wolfram.com/mathematica/ref/EdgeList.html). I wish I knew how Mathematica represents graphs internally, then there'd be some insight into what is faster. There are also other things similar to AdjacencyMatrix you could try like ToAdjacencyLists, IncidenceMatrix, ToUnorderedPairs, but I don't have any insight into which one would be faster." } ]
[ { "body": "<p>As of Mathematica 9.0 we have the function <a href=\"https://reference.wolfram.com/language/ref/AdjacencyList.html\" rel=\"nofollow\"><code>AdjacencyList[g,v]</code></a>.\nSince this is built into Mathematica, I would assume that it is the fastest implementation.</p>\n\n<pre><code>In[1]:= g = CompleteGraph[7];\nIn[2]:= AdjacencyList[g, 4]\nOut[2]= {1, 2, 3, 5, 6, 7}\nIn[3]:= g = CompleteGraph[{3,4}];\nIn[4]:= EdgeList[g]\nOut[4]= {1 &lt;-&gt; 4, 1 &lt;-&gt; 5, 1 &lt;-&gt; 6, 1 &lt;-&gt; 7, 2 &lt;-&gt; 4, 2 &lt;-&gt; 5, 2 &lt;-&gt; 6, 2 &lt;-&gt; 7, 3 &lt;-&gt; 4, 3 &lt;-&gt; 5, 3 &lt;-&gt; 6, 3 &lt;-&gt; 7}\nIn[5]:= AdjacencyList[g, 5]\nOut[5]= {1, 2, 3}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-20T19:17:02.830", "Id": "105192", "ParentId": "2871", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T09:07:44.807", "Id": "2871", "Score": "4", "Tags": [ "graph", "wolfram-mathematica" ], "Title": "Fastest way to find all neighbours of a vertex in a graph" }
2871
<p>This code is executed very often, so I'm wondering if it's already ideal or if it's possible to optimize it further.</p> <pre><code>var highlightLinks = function(e) { var anchors = e.target.getElementsByTagName("a"); let file = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties) .get("ProfD", Components.interfaces.nsIFile); file.append("test.sqlite"); var storageService = Components.classes["@mozilla.org/storage/service;1"] .getService(Components.interfaces.mozIStorageService); var conn = storageService.openDatabase(file); var statement = conn.createStatement("select * from links where url=?1"); for (var i = 0; i &lt; anchors.length; i++) { statement.bindStringParameter(0, anchors[i].href); statement.executeAsync({ anchorIndex: i, handleResult: function(aResultSet) { for (let row = aResultSet.getNextRow(); row; row = aResultSet.getNextRow()) { let value = row.getResultByName("url"); if (value == anchors[this.anchorIndex]) { anchors[this.anchorIndex].innerHTML += "+"; } } }, handleError: function(aError) { print("Error: " + aError.message); }, handleCompletion: function(aReason) { if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) print("Query canceled or aborted!"); } }); } statement.finalize(); conn.close(); } window.addEventListener("DOMContentLoaded", highlightLinks, false); </code></pre>
[]
[ { "body": "<p>I believe you could improve your code by using prototypes like this:</p>\n\n<pre><code>function handler(anchorIndex, anchor) {\n this.anchorIndex = anchorIndex;\n this.anchor = anchor;\n}\n\nhandler.prototype = {\n handleResult: function(aResultSet) {\n for (let row = aResultSet.getNextRow();\n row;\n row = aResultSet.getNextRow()) {\n\n let value = row.getResultByName(\"url\");\n if (value == anchor) {\n anchor.innerHTML += \"+\";\n }\n }\n },\n\n handleError: function(aError) {\n print(\"Error: \" + aError.message);\n },\n\n handleCompletion: function(aReason) {\n if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {\n print(\"Query canceled or aborted!\");\n }\n }\n};\n</code></pre>\n\n<p>Instead of creating a new object, which has to create new instances of the same functions, you create those functions once. This will improve performance and reduce memory usage across the board verified using <a href=\"http://jsperf.com/new-function-vs-object\">http://jsperf.com/new-function-vs-object</a></p>\n\n<p>Your for loop would be drastically reduced to look like</p>\n\n<pre><code>for (var i = 0; i &lt; anchors.length; i++) {\n statement.bindStringParameter(0, anchors[i].href);\n statement.executeAsync(new handler(i, anchors[i]));\n}\n</code></pre>\n\n<p><strong>EDIT:</strong>\nYou'll find this method of creating new instances of objects is faster in IE7-9 by ~3x, and roughly 2x as fast in FF5. My dev Chrome shows strange results in that the original method is 20% as fast as IE, yet shows ~155x improvement (10x faster than all other browsers) when using the prototype way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T14:24:20.953", "Id": "3787", "ParentId": "2872", "Score": "7" } } ]
{ "AcceptedAnswerId": "3787", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T11:42:01.003", "Id": "2872", "Score": "3", "Tags": [ "javascript", "performance", "firefox" ], "Title": "Firefox link-highlighting extension" }
2872
<p>I'm working on the registration process for new users of a small web app, and as this is largely a learning project I'm doing it from scratch.</p> <p>Here is my user class: <strong>Class_user.php</strong> </p> <pre><code>&lt;?php class User { // The class variables are the same and have the same name as the db fields. private $userID; // Must be incremental + unique. Also used as salt. private $userName; // Must be unique. private $hashedPassword; private $userEmail; function __construct($userID, $userName, $hashedPassword, $userEmail){ $this-&gt;userID=$userID; $this-&gt;userName=$userName; $this-&gt;hashedPassword=$hashedPassword; $this-&gt;userEmail=$userEmail; } function getUserID(){ return $this-&gt;userID; } function getUserName() { return $this-&gt;userName; } function getHashedPassword() { return $this-&gt;hashedPassword; } function getUserEmail() { return $this-&gt;userEmail; } } ?&gt; </code></pre> <p>Here is my model for the user - <strong>Model_User.php</strong>: </p> <pre><code>&lt;?php require_once('Class_DB.php'); require_once('Class_User.php'); require_once('DAO_User.php'); class Model_user{ // Object that represents a connection to the user DB private $dbInstance; function __construct($dbInstance){ // Using Dependency Injection passing a Class_DB object rather than global variable. $this-&gt;dbInstance=$dbInstance; } function insertNewUser($user, $userPassword){ // INCOMPLETE $userDAO=new DAO_User($this-&gt;dbInstance); $insertedUser=$userDAO-&gt;createNewUser($user, $userPassword); $userPassword=""; // We clear the user's password from memory. if ($insertedUser){ // User was correctly inserted in db return true; // Should return the $user object. } else { return false; } } } ?&gt; </code></pre> <p>Here is the key snippet from my user registration controller, <strong>Controller_Register.php</strong> </p> <pre><code>&lt;?php require_once("Controller.php"); require_once("Model_User.php"); require_once("General.php"); class Controller_Register extends Controller { protected $page='UI_Register.php'; function execute($view){ // Several lines to make sure the form is filled adequately. While (!$userInserted){ // As long as the user isn't correctly inserted... $userName=$_POST["userName"]; $userEmail=$_POST["userEmail"]; $userPassword=$_POST["userPassword"]; $_POST["userPassword"]=""; // We don't keep the pw in memory. $user=new user("", $userName, "", $userEmail); // User ID will be generated by the db, and the hashed pw has not been generated at this point. $userInserted=$userDBConnection-&gt;insertNewUser($user,$userPassword); // We insert the user name not knowing what the autoincremented user ID is. $userPassword=""; // We don't keep the pw in memory. } $_POST["password"]=""; // We clear the user's password from memory. if ($userInserted){// The value is true if the registration was succesful. $msg=new Message("Congratulations ".$_POST['userName']."! You are now registered."); } } return $view; } ?&gt; </code></pre> <p>Finally, here is my user DAO code, with the key item I would like guidance on, the registration - <strong>DAO_User.php</strong> </p> <pre><code>&lt;?php require_once('Class_User.php'); require_once('Class_DB.php'); require_once('General.php'); class DAO_User { private $dbInstance; // This is an instance of Class_DB to be injected in the functions. function __construct($dbInstance){ $this-&gt;dbInstance=$dbInstance; // Using Dependency Injection passing a Class_DB object rather than global variable. } function createNewUser($user, $userPassword){ // The $user object only has a userName and a userEmail at this point. $dbConnection=$this-&gt;dbInstance-&gt;createConnexion(); // This connection is local, so automatically closed after the function is completed. $inserted=false; while (!$inserted){ // This insert a new user, without any value for pw, and generates an autoincrement user ID on the db side. $query=$dbConnection-&gt;prepare("INSERT INTO users (userName, userEmail) VALUES (?,?)"); // userID is generated via autoincrement - therefore not known at time of insertion. $query-&gt;bindValue(1, $user-&gt;userName); $query-&gt;bindValue(2, $user-&gt;userEmail); $inserted=$query-&gt;execute(); //True if succesful, False if not. } $query=$dbConnection-&gt;prepare("SELECT LAST_INSERT_ID()"); // This allows us to retrieve the user ID as generated by the db. $userIDquery=$query-&gt;execute(); $result=$userIDquery-&gt;fetch(PDO::FETCH_ASSOC); // returns an array indexed by column name as returned in result set - here column name is "userID" in the DB $userID=$result["userID"]; $user-&gt;userID=$userID; // We modify the user ID of the $user object to be the autoincremented number generated by the db. $hashedPassword=stringHashing($userPassword,$user-&gt;userID); $userPassword=""; $user-&gt;hashedPassword=hashedPassword; $hashedPWinserted=false; while (!$hashedPWinserted){ // This modifies the user table in db to add hashed PW. $query=$dbConnection-&gt;prepare("UPDATE users SET hashedPassword=? WHERE userID=?"); $query-&gt;bindValue(1, $user-&gt;hashedPassword); $query-&gt;bindValue(2, $user-&gt;userID); } return $user; } } ?&gt; </code></pre> <p>The <strong>General.php</strong> code contains the <code>stringHashing</code> function that receives a string and a salt as parameter and and returns the salted string. I'm not sure where it should live in an MVC framework.</p> <p>My <code>users</code> table is a MySQL table with 4 fields:<br> - userID (INT(10), not null, autoincrement, PK) - also used as a salt for PW hashing<br> - userName (varchar(50), not null)<br> - hashedPassword (char(128), can be null)<br> - userEmail (varchar(255), can be null) </p> <p>Some specific questions I have, mostly on the <code>createNewUser</code> function:<br> - Are the db transactions correctly and efficiently done?<br> - Should I split some functionalities outside of this function?<br> - Should I limit the use of intermediate variables?<br> - Does the function accomplish the goals I want it to do, i.e., insert in the db a new user with an autoincremented user ID generated by the db, and then a hashed password? </p> <p>Also interested in any other piece of feedback people may have, especially with regards to readability (e.g., are my commentaries too verbose and obvious) and understandability of my code, as well as best practice object programming (e.g., I suppose I should modify my <code>$user</code> object with a setter rather than <code>$user-&gt;userID=$userID;</code>).</p> <p><strong>UPDATE</strong> When I run this code, I get no error, but I also don't get any record in the db.</p>
[]
[ { "body": "<p>Too much code for a simple thing...why don't you consider working with a framework like <a href=\"http://www.codeigniter.com\" rel=\"nofollow\">CodeIgniter</a>?</p>\n\n<p>Try placing some echoes on your code and see where it is stopping. It will be easier to help you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T14:18:17.860", "Id": "34743", "Score": "2", "body": "\"this is largely a learning project I'm doing it from scratch\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T19:46:54.953", "Id": "2889", "ParentId": "2877", "Score": "0" } }, { "body": "<p>In your User class : add the <strong>setters</strong> !<br />\nYou cannot modify a value from outside the class (ex: $user->userID = $userId)<br />\nTry it : <a href=\"http://ideone.com/We2Lh\" rel=\"nofollow\">http://ideone.com/We2Lh</a></p>\n\n<p>At the end of <strong>Model_User</strong>.php, replace </p>\n\n<pre><code>if ($insertedUser){ // User was correctly inserted in db\n return true; // Should return the $user object.\n} else {\n return false;\n}\n</code></pre>\n\n<p>By</p>\n\n<pre><code>return $insertedUser;\n</code></pre>\n\n<p>In yout <strong>Controller</strong> : </p>\n\n<p>Remove the <code>While (!$userInserted) {</code>. What will appened if the insertNewUser method always fail ? an infinite loop, an maybe you can crash your server.</p>\n\n<p>My way to write this code :</p>\n\n<pre><code>function execute($view) {\n\n // check and sanitize values\n $user = new user($userName, $userEmail); // Create a specific constructor. Empty values are ...\n $userInserted=$userDBConnection-&gt;insertNewUser($user,$userPassword);\n\n if ($userInserted) {\n $msg = new Message(\"Congratulations \".$_POST['userName'].\"! You are now registered.\");\n } else {\n $msg = new Message(\"Erreur during subscription. Please retry.\");\n }\n\n // send $msg to the view\n // ...\n}\n</code></pre>\n\n<p>If there is an error, it's not necessary to retry immediatly. Errors won't miraculously fix themselves !</p>\n\n<p><code>$_POST[\"password\"]=\"\";</code> : Useless, the parameters will be reset at the next request.</p>\n\n<p>Your <strong>DAO</strong> is very complicated.</p>\n\n<p>Remove all <code>while</code>, and handle possible errors (you can use boolean, <strong>exceptions</strong> ...).<br />\nYou can use two private methods to create and set the password.</p>\n\n<p>Generally, yout code is too much commented for me.<br />\nExemple :</p>\n\n<pre><code>private $userName; // Must be unique.\n=&gt; Check this in your DB, a comment is useless\n</code></pre>\n\n<p>Don't write <strong>obvious</strong> comment :</p>\n\n<pre><code>if ($insertedUser){ // User was correctly inserted in db\n</code></pre>\n\n<p>Don't try to explain the How or the What, comment the <strong>Why</strong>. The 'How' and the 'What' could be understand by reading your code, but you can't undestand the objective of a snippet if it's complicated.</p>\n\n<p>Add an <strong>unique index</strong> to userName.</p>\n\n<p>Finally, think of <strong>aerating</strong> your code ! New lines are free ^^</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-09T20:23:37.713", "Id": "3992", "ParentId": "2877", "Score": "2" } } ]
{ "AcceptedAnswerId": "3992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T23:14:16.453", "Id": "2877", "Score": "3", "Tags": [ "beginner", "php" ], "Title": "PHP - create a new user into a db using MVC framework" }
2877
<p>I have two kinds of lexical analyses of sentences that I need to process. One type of data comes in a "tagged" format, and the other comes in a "parsed" format.</p> <hr> <h2>Tagged</h2> <p>The input (<code>@subsentences</code>) looks like:</p> <pre><code>5.4_CD Passive_NNP Processes_NNP of_IN Membrane_NNP Transport_NNP 85_CD We_PRP have_VBP examined_VBN membrane_NN structure_NN and_CC how_WRB it_PRP is_VBZ used_VBN to_TO perform_VB one_CD membrane_NN function_NN :_: the_DT binding_JJ of_IN one_CD cell_NN to_TO another_DT ._. </code></pre> <h3>Desired output</h3> <p><code>5.4 Passive Processes of Membrane Transport 85 We have examined membrane stru....</code></p> <h3>My code</h3> <pre><code>@finalsentence = split(/_\S+/,$subsentences[$j]); </code></pre> <hr> <h2>Parsed</h2> <pre><code> Parsing [sent. 1 len. 31]: nsubj(85-7, Processes-3) nn(Transport-6, Membrane-5) prep_of(Processes-3, Transport-6) nsubj(examined-10, We-8) nsubjpass(used-17, it-15) xsubj(perform-19, it-15) conj_and(examined-10, used-17) xcomp(used-17, perform-19) dobj(perform-19, function-22) prep_of(binding-25, cell-28) &lt;- refer to this for examples below </code></pre> <h3>Desired output (for the last line)</h3> <ul> <li>the sent. number (ie. <code>sent. 1</code> )</li> <li>the grammar function (ie. <code>prep_of</code> )</li> <li>the first dependency word (ie. <code>binding</code> ) </li> <li>the second dependency word (ie. <code>cell</code> )</li> </ul> <h3>My code</h3> <p>Here is how <em>I</em> do it, but when I check for word boundaries (\b), <em>sometimes</em> they're not defined and on top of that, it's pretty crude:</p> <p>For the sent. number:</p> <pre><code>@parsesentcounter = split (/.*sent\.\s/, $typeddependencies[$i]); @parsesentcounter = split (/\s/, $typeddependencies[$i]); </code></pre> <p>This (crude method) leaves the sent. number (<code>sent. 1</code>) at $parsesentcounter[2]</p> <p>For the grammar function:</p> <pre><code>@grammarfunction = split(/\(\S+\s\S+\s/,$typeddependencies[$i]); </code></pre> <p><em>This leaves the grammar function(<code>prep_of</code>) at <code>$grammarfunction[0]</code></em></p> <p>For the dependency words, I do it in a few steps (I think I get lost a bit here):</p> <pre><code>@dependencywords = split (/,\s+/,$typeddependencies[$i]); ## Take out all commas, there was also a space associated @dependencywords = split (/-\S+\s+/,$typeddependencies[$i]); ## Take out all -digits and space </code></pre> <p><em>This leaves the second dependency word(<code>cell</code>) at <code>$dependencywords[1]</code>.</em></p> <p>Then for first dependency word:</p> <pre><code>@firstdependencyword = split(/.*subj\w*.|.*obj\w*.|.*prep\w*\(|.*xcomp\w*\(|.*agent\(|purpcl\(|.*conj_and\(/,$dependencywords[0]); </code></pre> <p><em>This leaves the first dependency word (<code>binding</code>) at <code>$firstdependencyword[1]</code></em></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T03:14:21.827", "Id": "4457", "Score": "0", "body": "Perhaps: instead of splitting, using =~ / ().../ and then having $1 be the output I need?\n\nEx: ` = $1 if ($line =~ /^Parsing \\[(sent. \\d+) len. \\d+\\]/);`" } ]
[ { "body": "<p>Match and substitute are far better suited for this problem than split().\nTo delete all of the _XX things, use a substitute global <code>s/(_\\S+)//g;</code>.\nSo generating your desired output is actually easy.</p>\n\n<p>To see demo of this and how to parse your report, see the code below. Note that if the left hand side contains variables in a list context like:<code>($gramFunc, $dep1, $dep2)</code> then they will be assigned $1,$2,$3 from the match respectively. I check if $dep2 is defined to mean that the match succeeded because if that variable is defined, then the variables $gramFunc and $dep1 are too!</p>\n\n<p>This line <code>$sentNum = $1 if /\\[sent\\.\\s*(\\d+)/;</code> has the same meaning as:</p>\n\n<pre><code>if (/\\[sent\\.\\s*(\\d+)/)\n{\n $sentNum = $1;\n}\n</code></pre>\n\n<p>I cannot assign to $sentNum directly in this case because I want to know if the match worked or not. $1 is undefined if the match fails and the scalar value of <code>/\\[sent\\.\\s*(\\d+)/</code> will be zero. I presume that more such \"[sent\" lines will appear in the report that you are trying to parse. This statement just updates as necessary the current sent # for the report.</p>\n\n<p>Code:</p>\n\n<pre><code>#!/usr/bin/perl -w\nuse strict;\n\nmy $str = '5.4_CD Passive_NNP Processes_NNP of_IN Membrane_NNP Transport_NNP 85_CD We_PRP have_VBP examined_VBN membrane_NN structure_NN and_CC how_WRB it_PRP is_VBZ used_VBN to_TO perform_VB one_CD membrane_NN function_NN :_: the_DT binding_JJ of_IN one_CD cell_NN to_TO another_DT ._.';\n\n$str =~ s/(_\\S+)//g; # deletes all of the \"_XX\" tokens\nprint $str, \"\\n\";\n\nmy $sentNum = 0;\nwhile (&lt;DATA&gt;)\n{\n $sentNum = $1 if /\\[sent\\.\\s*(\\d+)/;\n\n my ($gramFunc, $dep1, $dep2) = $_ =~ /\\s+(\\w+)\\((\\w+).*?(\\w+)-/;\n if (defined $dep2)\n {\n printf \"sent num=$sentNum %-10s %-15s %-15s\\n\", $gramFunc, $dep1, $dep2;\n }\n}\n\n=program output\n5.4 Passive Processes of Membrane Transport 85 We have examined membrane structure and how it is used to perform one membrane function : the binding of one cell to another .\nsent num=1 nsubj 85 Processes \nsent num=1 nn Transport Membrane \nsent num=1 prep_of Processes Transport \nsent num=1 nsubj examined We \nsent num=1 nsubjpass used it \nsent num=1 xsubj perform it \nsent num=1 conj_and examined used \nsent num=1 xcomp used perform \nsent num=1 dobj perform function \nsent num=1 prep_of binding cell \n=cut\n\n\n__DATA__\nParsing [sent. 1 len. 31]:\n nsubj(85-7, Processes-3)\n nn(Transport-6, Membrane-5)\n prep_of(Processes-3, Transport-6)\n nsubj(examined-10, We-8)\n nsubjpass(used-17, it-15)\n xsubj(perform-19, it-15)\n conj_and(examined-10, used-17)\n xcomp(used-17, perform-19)\n dobj(perform-19, function-22)\n prep_of(binding-25, cell-28) &lt;- refer to this for examples below\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T01:29:30.757", "Id": "3288", "ParentId": "2881", "Score": "1" } } ]
{ "AcceptedAnswerId": "3288", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T05:51:46.120", "Id": "2881", "Score": "2", "Tags": [ "parsing", "perl", "natural-language-processing" ], "Title": "Processing lexical analyses of sentences using the Perl split function" }
2881
<p>I am currently doing Encoding on Dropdownlist in our project.</p> <p>Could you please review and provide your comments about the following approach? After the encoding on dropdown, if there are any special characters it is displaying in the form of encoded characters, please let me know is there any better approach than this.</p> <pre><code>// raising the databound event to to encoding protected void ddlCountry_DataBound(object sender, EventArgs e) { if (ddlCountry.Items.Count &gt; 0) { foreach (ListItem list in ddlCountry.Items) { list.Text = EncodeDropDownItem(list.Text); } } } //below are the methods to do encoding //encoding with antixss's htmlencode method private string EncodeDropDownItem(string DropdownText) { return Replacecharacters(AntiXss.HtmlEncode(DropdownText)); } //below method will replace the antixsstags with normal character. private string Replacecharacters(string value) { string dropdowntext; StringBuilder sb = new StringBuilder(value); sb.Replace("&amp;#38;", "&amp;"); sb.Replace("&amp;#60;", "&lt;"); sb.Replace("&amp;#62;", "&gt;"); sb.Replace("&amp;#34;", "\""); sb.Replace("&amp;#92;", "\\"); return dropdowntext = sb.ToString(); } </code></pre>
[]
[ { "body": "<p>A few comments - </p>\n\n<p>It seems that while your code should work fine as is, it could be improved in the following ways:</p>\n\n<p>A. It seems like you have three methods here when only one or two would be necessary. You may have your reasons for doing this, but the \"middle-man\" method \"EncodeDropDownItem\" seems superfluous.</p>\n\n<p>B. The way you are hard-coding the calls to sb.replace, one at a time and with target/replacement values \"inlined\" might be more effective if they were preformed within a looping structure, with the Axss tags and replacement values retrieved from a custom dictionary. The hard-coded Axss tags and related character representations could then be encapsulated within that custom dictionary class, and re-used in other contexts if necessary. </p>\n\n<p>You may have your reasons for structuring your methods the way you have. However, I make the below suggestions for your code. Note that I am not able to test this, but hopefully you or some other forum readers will catch anything I screw up here . . .</p>\n\n<p>FIRST - a custom dictionary for the Axss tags/values:</p>\n\n<pre><code> class AntiAxssDictionary : Dictionary&lt;String, String&gt;\n {\n public void AntiAxssDictionary()\n {\n this.Add(\"&amp;#38;\", \"&amp;\");\n this.Add(\"&amp;#60;\", \"&lt;\");\n this.Add(\"&amp;#62;\", \"&gt;\");\n this.Add(\"&amp;#34;\", \"\\\"\");\n this.Add(\"&amp;#92;\", \"\\\\\");\n }\n }\n</code></pre>\n\n<p>THEN, a minor rearrangement of your methods (this might be a matter of taste, or function, but this is how I would do it, given what little I know about your code):</p>\n\n<pre><code> // raising the databound event to to encoding\n protected void ddlCountry_DataBound(object sender, EventArgs e)\n {\n if (ddlCountry.Items.Count &gt; 0)\n {\n //Initialize an AntiAxssDictionary object:\n AntiAxssDictionary tokenProvider = new AntiAxssDictionary();\n\n foreach (ListItem list in ddlCountry.Items)\n {\n // Encode the AntiAxss string here:\n StringBuilder sb = new StringBuilder(AntiXss.HtmlEncode(list.Text));\n\n // Iterate through the Axss tags stored as keys in the dictionary:\n foreach (String token in tokenProvider.Keys)\n {\n // Attempt a replacement for each of the possible\n // values in the Axss dictionary:\n sb.Replace(token, tokenProvider[token]);\n }\n\n // Assign the new value to the list.text property:\n list.Text = sb.ToString;\n }\n }\n }\n</code></pre>\n\n<p>Hopefully I didn't butcher anything too badly here. I am in the midst of migrating from vb.net to C#, and learning Java at the same time. Hope that helps, and I will be interested to hear commentary and critique from other forum members. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T06:33:10.090", "Id": "3000", "ParentId": "2882", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T08:47:51.160", "Id": "2882", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "Encoding on Dropdownlist items" }
2882
<p>I wanted to launch a bash script (read: bash not sh script) as a root not as the user calling it, however bash ignore <code>setuid</code> on scripts, so I chose to write a very small script that takes a script/arguments and call it with <code>setuid</code> set.</p> <p>This worked well and I went even further to verify that the script has <code>setuid</code> set on, executable and <code>setuid()</code> called on the owner of the file and not as root, to avoid any misuse of the program and I ended up with the program below.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; int main(int argc, char **argv) { char *command; int i, file_owner, size = 0; struct stat status_buf; ushort file_mode; // Check argc if (argc &lt; 2) { printf("Usage: %s &lt;script&gt; [arguments]\n", argv[0]); return 1; } // Make sure the script does exist if(fopen(argv[1], "r") == NULL) { printf("The file %s does not exist.\n", argv[1]); return 1; } // Get the attributes of the file stat(argv[1], &amp;status_buf); // Get the permissions of the file file_mode = status_buf.st_mode; // Make sure it's executable and it's setuid if(file_mode &gt;&gt; 6 != 567) { printf("The file %s should be executable and should have setuid set, please chmod it 0106755.\n", argv[1]); return 1; } // Get the owner of the script file_owner = status_buf.st_uid; // setuid setuid(file_owner); // Generate the command for (i = 1; i &lt; argc; i++) { size += strlen(argv[i]); } command = (char *) malloc( (size + argc + 11) * sizeof(char) ); sprintf(command, "/bin/bash %s", argv[1]); if (argc &gt; 2) { for (i = 2; i &lt; argc; i++) { sprintf(command, "%s %s", command, argv[i]); } } // Execute the command system(command); // free memory free(command); return 0; } </code></pre> <p>The exercise was not only to solve my problem, but it was also a way to get more into C, so what do you suggest? Is there anything I should improve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T09:58:09.577", "Id": "4430", "Score": "3", "body": "Next time don't double post, just use the flag tool on your [original post](http://stackoverflow.com/questions/6290670/need-help-improving-a-small-c-program) and ask a moderator to migrate it to the suggested site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T10:40:01.587", "Id": "4433", "Score": "0", "body": "I'll make sure to do that next time, thanks for the tip" } ]
[ { "body": "<p>One thing I'd do is </p>\n\n<p>change </p>\n\n<pre><code>sprintf(command, \"%s %s\", command, argv[i]);\n</code></pre>\n\n<p>to use strcat</p>\n\n<p>while this does work on a number of implementations, it's not considered \"safe\"</p>\n\n<p>refer <a href=\"https://stackoverflow.com/questions/1283354/is-sprintfbuffer-s-buffer-safe\">https://stackoverflow.com/questions/1283354/is-sprintfbuffer-s-buffer-safe</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T09:33:29.777", "Id": "4472", "Score": "2", "body": "How about using `strncat()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T21:44:11.200", "Id": "4530", "Score": "0", "body": "thank you, I've already changed the script to use fork()/exec() instead of looping on the command variable myself, modified script is just above." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T23:54:46.817", "Id": "2897", "ParentId": "2883", "Score": "0" } }, { "body": "<ol>\n<li><p>Check for errors in <code>stat</code>, <code>setuid</code>, <code>fork</code>, and <code>execvp</code>, to name a few. If the exec fails in the child you should call <code>exit</code>.</p></li>\n<li><p>Do you really want the <b><code>p</code></b> in <code>execvp</code>? This is not guaranteed to be the same as the <code>argv[1]</code> you just <code>stat</code>-ed. If <code>argv[1]</code> is <code>ls</code> your <code>stat</code> will look for a file at <code>./ls</code> and it will likely find the program in <code>/bin</code>. I would use <code>execve</code> and either do that <code>PATH</code> lookup yourself or simply omit that part and require the user to specify a full path for something in <code>PATH</code> (eg. <code>/bin/ls</code> instead of just <code>ls</code>).</p></li>\n<li><p>The <code>stat</code> + observe state + <code>exec</code> thing is a race condition. Another process can change the attributes on the file in that timing window. This may or may not be important to you. Given that this is a security-ish program I would say it may very well be.</p></li>\n<li><p>Instead of returning 0, you might want to return the child process's exit code (which you can get with <code>waitpid</code>.) You might also want to return nonzero when the functions I mention in #1 fail. This way a shell script or something calling you programmatically can determine success or failure.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T21:43:20.717", "Id": "4529", "Score": "0", "body": "That was very very helpful, thank you.. I would like to know more about #3, how could I prevent anyone from changing the file's attributes before calling exec, to avoid someone tempering with the attributes while the script is running? should I lock the file ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T23:49:36.787", "Id": "4531", "Score": "0", "body": "I don't know if there is a good way around it for this. I don't think `flock` makes sense here either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T12:42:57.773", "Id": "4538", "Score": "0", "body": "I added V3 in my original post, I modified it following #1. #2 and #4, I still have to figure out how to fix #3" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T09:06:55.610", "Id": "2936", "ParentId": "2883", "Score": "2" } }, { "body": "<p>If I understand you correctly you would install your program (edit V3) like this</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ gcc -o edit_v3 edit_v3.c\n$ ls -l edit_v3\n-rwxrwxr-x 1 erik erik 7698 2012-04-15 12:22 edit_v3\n$ sudo chown root.root edit_v3\n$ sudo chmod 4755 edit_v3\n$ ls -l edit_v3\n-rwsr-xr-x 1 root root 7698 2012-04-15 12:22 edit_v3\n</code></pre>\n\n<p>But a user could then easily get root access</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ ls -l /bin/su\n-rwsr-xr-x 1 root root 31116 2011-06-24 11:37 /bin/su\n$ ./edit_v3 /bin/su\n# id\nuid=0(root) gid=0(root) grupper=0(root),116(pulse),117(pulse-access)\n</code></pre>\n\n<p>It is difficult to write secure setuid programs. Over the years a lot of security vulnerabilities have been found in such program.</p>\n\n<p>Instead of writing your own setuid program, you could also use <strong>sudo</strong>. You would then have to edit the configuration file <strong>/etc/sudoers</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-14T17:52:12.507", "Id": "18852", "Score": "0", "body": "Actually it is one of the reasons why I abandoned the idea entirely, I wanted some way to provision server configuration (i.e Nginx conf files) but I finally settled on a more Capistrano/Chef solution as it's easier and well a lot safer than having any kind of security holes on the server. Thanks anyway :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-15T10:57:36.787", "Id": "10905", "ParentId": "2883", "Score": "1" } } ]
{ "AcceptedAnswerId": "2936", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T09:51:30.983", "Id": "2883", "Score": "3", "Tags": [ "c", "bash" ], "Title": "Calling a script with a setuid set" }
2883
<p>I'm trying to create an app for the Palm Pre. It is a prayer app, more specifically a rosary app. <em>If you are not a Catholic, a rosary is kind of like a necklace on which you count beads.</em> </p> <p><strong>What I'm trying to do:</strong></p> <ul> <li>You click on one of 4 buttons to select one of 4 sets of "mysteries".</li> <li><p>The page then displays </p> <ul> <li>the title of the set of mysteries (except in a few cases)</li> <li>the title of the individual mystery</li> <li>the prayer that goes with it </li> <li>the bead you are on</li> </ul></li> <li><p>Each page has a button, "Next Bead", which you click to advance to the next prayer and bead.</p></li> </ul> <p>The routine goes like this:</p> <ol> <li>Before the mysteries <ul> <li>Apostles Creed, Our Father, three Hail Marys, Glory Be, and Fatima prayer</li> </ul></li> <li><p>Then, for each individual mystery </p> <ul> <li>Our Father, ten Hail Marys, Glory Be, and Fatima prayer </li> <li>this cycle will repeat 5 times for each of 5 mysteries.</li> </ul></li> <li><p>After the mysteries - Hail Holy Queen</p></li> </ol> <p><strong>What I'm concerned about:</strong></p> <ul> <li><p>First, I'm not sure I have the best set up for the buttons at the beginning. With the phone SDK, the phone will have to 'listen' for which button is pressed. Did I set this up right?</p></li> <li><p>Second, I have all of these if statements set up to pick which prayer occurs with which bead. Is this the most efficient way to do this?</p></li> </ul> <p>All thoughts are appreciated.</p> <pre><code>&lt;script type="text/javascript"&gt; var chaplet=new Array("The Joyful Mysteries","The Luminous Mysteries","The Sorrowful Mysteries","The Glorious Mysteries"); var mystery=new Array(); mystery[0]=new Array("Annunc","Visit","The Nativ","Present","Temple"); mystery[1]=new Array("Baptism","Wedding", "Kingdom","Transfig","Eucharist"); mystery[2]=new Array("Agony","Scourging","Crowning","Carrying", "Crucif"); mystery[3]=new Array("Resurr","Ascension","Spirit","Assumption","Coronation"); var creed="I believe..." var ourFather="Hallowed be" var hailMary="Blessed are thou" var gloryBe="As it was" var fatima="Oh my Jesus" var hailHolyQueen="To thee do we cry" var dec=0; var beadCount=0; var mys=0; var bead=0; function nextBead() { eventSrcID=(event.srcElement)?event.srcElement.id:'undefined'; if (eventSrcID=='joy') mys=0; if (eventSrcID=='lum') mys=1; if (eventSrcID=='sor') mys=2; if (eventSrcID=='glo') mys=3; if (beadCount==0) { div1.innerHTML="Apostles Creed"; div2.innerHTML=""; div3.innerHTML="&lt;p&gt;"+creed+"&lt;/p&gt;"; div4.innerHTML="Cross"; } else if (beadCount==1) { div1.innerHTML="Our Father"; div2.innerHTML=""; div3.innerHTML="&lt;p&gt;"+ourFather+"&lt;/p&gt;"; div4.innerHTML="Decade 0 Bead "+beadCount; }; else if (beadCount&lt;=4) { div1.innerHTML="For Faith, Hope and Charity"; div2.innerHTML=""; div3.innerHTML="&lt;p&gt;"+hailMary+"&lt;/p&gt;"; div4.innerHTML="Decade 0 Bead "+beadCount; }; else if (beadCount==5) { div1.innerHTML="Glory Be"; div2.innerHTML=""; div3.innerHTML="&lt;p&gt;"+gloryBe+"&lt;/p&gt;"; div4.innerHTML="Decade 0 Bead "+beadCount; }; else if (beadCount==6) { div1.innerHTML="Fatima Prayer"; div3.innerHTML="&lt;p&gt;"+fatima+"&lt;/p&gt;"; div4.innerHTML="Decade 0 Bead "+(beadCount-1); }; else if (beadCount==72) { div1.innerHTML="Hail Holy Queen"; div2.innerHTML=""; div3.innerHTML="&lt;p&gt;"+hailHolyQueen+"&lt;/p&gt;"; div4.innerHTML="Medal"; }; else if (beadCount&gt;6 &amp;&amp; beadCount&lt;72) { div1.innerHTML="&lt;p&gt;"+chaplet[mys]+"&lt;/p&gt;"; div2.innerHTML="&lt;p&gt;"+mystery[mys][dec]+"&lt;/p&gt;"; if (bead==0) { div3.innerHTML="&lt;p&gt;"+ourFather+"&lt;/p&gt;"; div4.innerHTML="&lt;p&gt;Decade "+(dec+1)+" Bead "+bead+"&lt;/p&gt;"; }; else if (bead&lt;=10) { div3.innerHTML="&lt;p&gt;"+hailMary+"&lt;/p&gt;"; div4.innerHTML="&lt;p&gt;Decade "+(dec+1)+" Bead "+bead+"&lt;/p&gt;"; }; else if (bead==11) { div3.innerHTML="&lt;p&gt;"+gloryBe+"&lt;/p&gt;"; div4.innerHTML="&lt;p&gt;Decade "+(dec+1)+" Bead "+bead+"&lt;/p&gt;"; }; else if (bead==12) { div3.innerHTML="&lt;p&gt;"+fatima+"&lt;/p&gt;"; div4.innerHTML="&lt;p&gt;Decade "+(dec+1)+" Bead "+(bead-1)+"&lt;/p&gt;"; }; bead++; if (bead==13) bead=0; if (bead==0) dec=dec+1; }; beadCount++; div5.innerHTML="&lt;input type='button' value='Next Bead' onclick='nextBead()' /&gt;"; }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="div1"&gt; &lt;input type="button" id="joy" value="The Joyful Mysteries" onclick="nextBead ()" /&gt;&lt;br /&gt; &lt;/div&gt; &lt;div id="div2"&gt; &lt;input type="button" id="lum" value="The Luminous Mysteries" onclick="nextBead ()" /&gt;&lt;br /&gt; &lt;/div&gt; &lt;div id="div3"&gt; &lt;input type="button" id="sor" value="The Sorrowful Mysteries" onclick="nextBead ()" /&gt;&lt;br /&gt; &lt;/div&gt; &lt;div id="div4"&gt; &lt;input type="button" id="glo" value="The Glorious Mysteries" onclick="nextBead ()" /&gt;&lt;br /&gt; &lt;/div&gt; &lt;div id="div5"&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T15:42:53.513", "Id": "4436", "Score": "2", "body": "I'd rather not answer this one :O, but I'll give you one hint: **switch**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-31T16:03:24.423", "Id": "6747", "Score": "0", "body": "That's a fun comment @Steven Jeuris :p" } ]
[ { "body": "<p>You may want to consider indexing some of your variables into an array, with the contents of the array being additional arrays that have the strings that you'll then set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T21:32:29.440", "Id": "2891", "ParentId": "2885", "Score": "1" } }, { "body": "<p>IMHO the code really needs a lot of work.</p>\n\n<ul>\n<li><p>Use array literals to construct your arrays: </p>\n\n<pre><code>var chaplet = [\"The Joyful Mysteries\",\"The Luminous Mysteries\" /* ... */ ];\nvar mystery = [\n [\"Annunc\",\"Visit\",\"The Nativ\",\"Present\",\"Temple\"],\n [\"Baptism\",\"Wedding\", \"Kingdom\",\"Transfig\",\"Eucharist\"]\n // ...\n];\n</code></pre></li>\n<li><p>There is no point in putting strings into variables if you don't use them multiple times. There <strong>is</strong> a point if you want to internationalize the App. In that case put <strong>all</strong> strings into a data structure, that can easily replaced with different languages:</p>\n\n<pre><code>var strings = {\n joyful_mysteries: \"The Joyful Mysteries\",\n luminous_mysteries: \"The Luminous Mysteries\",\n // etc.\n};\n</code></pre></li>\n<li><p><code>div1</code>, <code>div2</code>, etc. are very bad choices for ids. Use meaningful names.</p></li>\n<li><p>Don't write the <code>&lt;p&gt;</code> elements. Leave them out, or use them instead of <code>div</code>s directly in your HTML. If you use them to change the distances between the elements, then use the style sheet for that instead.</p></li>\n<li><p>Put the strings for divs 1 and 2 and beads one to seven and for div3 for all beads into arrays, too. And look into not repeating the texts and code of div4 either.</p></li>\n</ul>\n\n<p>There is much more that could be suggested, but you should work on these points first, and then post a new question, when you've done that.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p>BTW, something completely else: Have you actually run your code? I just tried it for the first time, and it has several syntax errors (extra <code>;</code> before <code>else</code>).</p>\n\n<p>Also you seem to use the Internet Explorer event model. I'm not familiar with Palm Pre, but I doubt it uses the IE model and I believe it would be better to use the standard DOM model. Don't use IE for testing, or you will learn it's non-standard behavior.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T18:55:15.920", "Id": "4558", "Score": "0", "body": "Hi, thanks for your answer. As you can probably tell, I am a total beginner. Question about the divs. They were set up to hold 1. the set of mysteries; 2. the individual mystery; 3. the prayer, and 4. the bead count. However, I first use the divs to hold the selection buttons to pick the set of mysteries to do. How do I achieve the result without putting the buttons into the divs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T12:50:28.410", "Id": "4566", "Score": "0", "body": "I'm not quite sure what you want to achieve, but I'd say, put the buttons in a separate div and hide it when you don't need them. See also my edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T09:35:09.533", "Id": "2905", "ParentId": "2885", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T13:59:32.813", "Id": "2885", "Score": "5", "Tags": [ "javascript" ], "Title": "Rosary app for the Palm Pre" }
2885
<p>I have a query like this <code>"abc=1, def=2, ghi=3"</code> and I need to parse it into arrays like this <code>keys = [abc, def, ghi] and values = [1,2,3]</code></p> <p>currently my code is like this</p> <pre><code>String[] terms = query.split(","); int termsCount = terms.length; String[] keys = new String[termsCount]; String[] values = new Object[termsCount]; for(int i=0; i&lt;termsCount; i++) { if(terms[i].contains("=")) { keys[i] = terms[i].split("=")[0]; values[i] = terms[i].split("=")[1]; } } </code></pre> <p>sometimes, the query might be empty or may not be well formed - I need to take care of that scenarios too.</p> <p>Am I doing this right? Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T22:00:51.637", "Id": "33030", "Score": "0", "body": "`String[] values = new Object[termsCount];` should be `String[] values = new String[termsCount];`. Alternatively, you could chuck the whole arrays thing and do what the posters below suggest." } ]
[ { "body": "<p>The code as it is, is fine. The biggest point is that you should perform the <code>.split(\"=\")</code> only once:</p>\n\n<pre><code>String[] parts = terms[i].split(\"=\");\nkeys[i] = parts[0];\nvalues[i] = parts[1];\n</code></pre>\n\n<p>However there is a more general point: Why are you using arrays? </p>\n\n<p>It's very unusual to use arrays at all in Java, especially in this case where you say yourself the input my be not well formed, possibly leaving you with gaps in the array, which you'll need to work around later. You should at least use <code>List</code>s. Or even more fitting would be a <code>Map</code> (if the \"keys\" are unique):</p>\n\n<pre><code>String[] terms = query.split(\",\");\nMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(terms.length);\n\nfor (String term in terms)\n{\n if(term.contains(\"=\"))\n {\n String[] parts = term.split(\"=\");\n map.add(parts[0], parts[1]);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T15:36:00.950", "Id": "4435", "Score": "0", "body": "Wow, simultaneous post. :) +1, the map might make more sense, depending on the context." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T15:35:05.697", "Id": "2887", "ParentId": "2886", "Score": "4" } }, { "body": "<p>No reason to <code>split</code> twice. Split once and store the result. Also better do an additional check after splitting.</p>\n\n<pre><code>String[] split = terms[ i ].split( \"=\" );\nif ( split.length == 2 )\n{\n ...\n}\n</code></pre>\n\n<p>Lastly, I wouldn't use an array to store the results in. As you said, it might not be filled up entirely since some values might be parsed incorrectly. Use a <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/List.html\" rel=\"nofollow\">generic <code>List&lt;RetrievedValue&gt;</code></a> to store the results in. <code>RetrievedValue</code> could be a simple class holding both values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T07:02:57.540", "Id": "4462", "Score": "0", "body": "Good point about checking the split length. I should have though of that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T15:35:13.627", "Id": "2888", "ParentId": "2886", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T14:34:23.483", "Id": "2886", "Score": "5", "Tags": [ "java", "parsing" ], "Title": "Code review - parse a query to arrays" }
2886
<p>Is this code Pythonic?</p> <pre><code>def emit_decorator(method, signal_name): def decorated(self, *args, **kwargs): retval = method(self, *args, **kwargs) getattr(self, signal_name).emit() return retval return decorated class Model(base.Transformer, Node): """ Transformer subclass that implements the Model of the Model-View-Controller paradigm. """ def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) modelChanged = pyqtSignal() def create_view(self, parent=None): return View(self, parent) for x in ('importance_changed', 'evidence_changed', ): setattr(Model, x, emit_decorator(getattr(Model, x), 'modelChanged')) </code></pre> <hr> <p>Final decorator code:</p> <pre><code>from functools import update_wrapper def method_emit_decorator(signal_name): def method_decorator(method): def decorated(self, *args, **kwargs): retval = method(self, *args, **kwargs) getattr(self, signal_name).emit() return retval return update_wrapper(decorated, method) return method_decorator def class_emit_decorator(signal_name_to_method_names_dict): def class_decorator(cls): retval = cls for signal_name, method_names in ( signal_name_to_method_names_dict.items()): for method_name in method_names: method = method_emit_decorator(signal_name)( getattr(cls, method_name)) setattr(retval, method_name, method) return retval return class_decorator </code></pre>
[]
[ { "body": "<p>Modifying the class after defining it smells. That is, its not necessarily a bad idea but one should explore options before resorting to it.</p>\n\n<p>When \"decorating\" a function you should use the functools.wraps decorator. It will make the decorated function look more like the original.</p>\n\n<p>The code you are replacing looks like:</p>\n\n<pre><code>def importance_changed(self):\n return_value = super(Model, self).importance_changed()\n self.modelChanged.emit()\n return return_value\n</code></pre>\n\n<p>Your code is harder to read and longer then just writing those two functions. Its not really worth implementing what you've done just for two functions. However, if you have a lot of functions then the situation changes.</p>\n\n<p>Your emit_decorator function isn't a decorator. Dectorators have to take exactly one argument, (the function they are wrapping) to be used with the @syntax.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:07:10.720", "Id": "4440", "Score": "0", "body": "Thanks for the great tips! I already have four such functions, so I thought this would be an easy way to save on boilerplate. I don't know of any way of doing this without modifying the class after defining it. Do you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:22:14.860", "Id": "4441", "Score": "0", "body": "@Neil G, I do, but they are uglier then what you are doing. I might think about defining a class dectorator that connects all _changed() function to a modelChanged() signal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T23:47:14.273", "Id": "4445", "Score": "0", "body": "I was just thinking along the same lines. Thanks a lot for your input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T06:46:55.663", "Id": "4515", "Score": "0", "body": "I have taken all of your suggestions into account and produced two decorators." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:02:28.413", "Id": "2893", "ParentId": "2890", "Score": "3" } } ]
{ "AcceptedAnswerId": "2893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T20:23:27.413", "Id": "2890", "Score": "5", "Tags": [ "python" ], "Title": "Python subclass method decoration" }
2890
<p>Is there a better way to have a minimal Python plugin mechanism than the following?</p> <p>(This was inspired from <a href="https://stackoverflow.com/questions/487971/is-there-a-standard-way-to-list-names-of-python-modules-in-a-package">this post</a>.)</p> <pre><code>import sys import pkgutil import os.path import plugins pluginsPath = os.path.dirname(plugins.__file__) pluginModules = [name for _, name, _ in pkgutil.iter_modules([pluginsPath])] dictOfPlugins = {} for plugin in pluginModules: thePluginModuleName = "plugins."+plugin result = __import__(thePluginModuleName) dictOfPlugins[plugin] = sys.modules[thePluginModuleName] </code></pre> <p>(This does assume that all your plugins are in a directory called "plugins" and thus are modules in that package, and that that directory has a blank __init__.py file in it.)</p> <p>If you wanted to look for a particular plugin, the name would be a key in the <code>dictOfPlugins</code>, and the module object itself would be the value. Assuming you knew what the interface to your Python plugin modules would be, this would seem to do the job. Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T07:12:54.747", "Id": "4795", "Score": "0", "body": "I personally would go with the route of having the individual plugin hook themselves into the \"plugins\" module. Then you wouldn't have to assume they are anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T23:48:04.927", "Id": "4942", "Score": "0", "body": "@James How would you go about ensuring that the code within the plugin that would hook itself in got called?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T01:18:02.630", "Id": "4944", "Score": "1", "body": "something similar to the way you create template tags/filters in django? have a `plugins.register()` method and call that after the plugin declaration. (e.g. `plugins.register('pluginModuleName')` or `plugins.register(pluginModule)`. Does that make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T11:36:19.007", "Id": "4950", "Score": "0", "body": "@James that almost makes sense (and would reduce a few lines of this), but it seems to presuppose that all plugin code is in someplace where it is executed - which kind of means that we need to assume that they are somewhere, since we can't really execute everything everywhere - or am I not understanding you correctly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T23:12:46.630", "Id": "4955", "Score": "0", "body": "You lost me somewhere. I mean that when you start up your project you would define which plugins you'd want to use. Then you'd access them via the plugins module? Thats where I get a bit vague. I'm not 100% sure how you'd do that." } ]
[ { "body": "<p>Check out how Django apps work:</p>\n\n<ul>\n<li>Plugins are genuine Python packages, so the standard tools can be used to install them</li>\n<li>Plugins that are actually used must be in the PYTHONPATH and listed (only the package name) in the configuration.</li>\n<li>There are scripts to help create, test, ... plugins</li>\n<li>The plugin structure is extensible in all possible ways.</li>\n<li>Plugins are reloaded when they change in development mode.</li>\n</ul>\n\n<p>I'm not saying that you should use Django if you're not doing web development, but you can inspire your plugin system on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-24T20:36:54.037", "Id": "329966", "Score": "0", "body": "totally agree, this was very helpful suggestion. You can checkout the loading mechanism itself @ https://docs.djangoproject.com/en/1.11/_modules/django/utils/module_loading/#import_string" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T08:09:49.913", "Id": "4666", "ParentId": "2892", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T21:45:00.437", "Id": "2892", "Score": "11", "Tags": [ "python", "plugin", "modules" ], "Title": "Minimal Python plugin mechanism" }
2892
<p>I've tagged this as homework because it was originally a school project, it was accepted but I'm not satisfied with the code.</p> <p>I've used cramers rule to find the intersection of 3 lines in three dimensional space given the <code>x</code>, <code>y</code> and <code>z</code> coefficients but the code is hideous.</p> <pre><code>def trinomial(): print "Trinomials require 3 equations with three variables each." firstX = input ("Please enter the coeficcient of X in the first equation: ") firstY = input ("Please enter the coefficient of Y in the first equation: ") firstZ = input ("Please enter the coefficient of Z in the first equation: ") firstA = input ("and what's after the = sign?") secondX = input ("Please enter the coefficient of X in the second equation: ") secondY = input ("Please enter the coefficient of Y in the second equation: ") secondZ = input ("Please enter the coefficient of Z in the second equation: ") secondA = input ("And what's after the = sign?") thirdX = input ("Please enter the coefficient of X in the third equation: ") thirdY = input ("Please enter the coefficient of Y in the third equation: ") thirdZ = input ("Please enter the coefficient of Z in the third equation: ") thirdA = input ("And what's after the = sign?") D= firstX*secondY*thirdZ+firstY*secondZ*thirdX+firstZ*secondX*thirdY-thirdX*secondY*firstZ- thirdY*secondZ*firstX-thirdZ*secondX*firstY DX = firstA*secondY*thirdZ+firstY*secondZ*thirdA+firstZ*secondA*thirdY-thirdA*secondY*firstZ-thirdY*secondZ*firstA-thirdZ*secondA*firstY DY = firstX*secondA*thirdZ+firstA*secondZ*thirdX+firstZ*secondX*thirdA-thirdX*secondA*firstZ-thirdA*secondZ*firstX-thirdZ*secondX*firstA DZ = firstX*secondY*thirdA+firstY*secondA*thirdX+firstA*secondX*thirdY-thirdX*secondY*firstA-thirdY*secondA*firstX-thirdA*secondX*firstY #the next two if statements evaluate the D's, or determinants, to see if it's an inconsistant or identical systerm #if it's not, then it does the math to solve the equation if D == 0: print "Determinant is 0 evaluate for identical or inconsistant systems." if DX ==0 and DY == 0 and DZ == 0: print "System is dependant, there are infinite solutions" print else: print "System is inconsistant, there are no solutions" print if D != 0: AX = DX/D AY = DY/D AZ= DZ/D print "the solution to the set of equations is ("+str(AX)+","+str(AY)+","+str(AZ)+")." print </code></pre> <p>I'm sorry for the huge wall of text, the code works, and the solutions are correct, I'd just like to know if there's a neater way of doing this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:16:46.467", "Id": "4443", "Score": "0", "body": "Definitely there is a cleaner way. This way, it is not extensible to higher numbers without modification. Check out the determinant algorithms using recursion. (See http://wiki.tcl.tk/11095)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T23:09:16.603", "Id": "4444", "Score": "0", "body": "is it actually possible to make an inconsistent system in this program? The number of variables = the number of unknowns." } ]
[ { "body": "<ol>\n<li>Instead of having variables firstX, secondX, thirdX, replace them with a list X</li>\n<li>Don't put input and calculations in the same function, separate them</li>\n<li><p>You do:</p>\n\n<p>if D == 0:\n some stuff\n if D != 0:\n other stuff</p></li>\n</ol>\n\n<p>use else instead</p>\n\n<ol>\n<li>Your three lines calculating D, DX, DY, DZ are very similar. Make it a function.</li>\n<li>The terms being subtractd parallel the ones being added. Extract the pair into a function.</li>\n</ol>\n\n<p>Here is my result:</p>\n\n<pre><code>DEPENDENT = 0\nINCONSISTENT = 1\nGOOD = 2\n\ndef determinant(X, Y, Z):\n def term(x, y, z):\n return X[x]*Y[y]*Z[z] - X[z]*Y[y]*Z[z]\n return term(0, 1, 2) + term(2, 0, 1) + term(1,2,0)\n\ndef trinomial(X, Y, Z, A):\n\n D = determinant(X, Y, Z)\n DX = determinant(A, Y, Z)\n DY = determinant(X, A, Z)\n DZ = determinant(X, Y, A)\n#the next two if statements evaluate the D's, or determinants, to see if it's an inconsistant or identical systerm\n#if it's not, then it does the math to solve the equation\n if D == 0:\n if DX == 0 and DY == 0 and DZ == 0:\n return DEPENDENT, None\n else:\n return INCONSISTENT, None\n else:\n return GOOD, [DX/D, DY/D, DZ/D]\n\n\ndef main():\n print \"Trinomials require 3 equations with three variables each.\"\n X.append( input (\"Please enter the coeficcient of X in the first equation: \") )\n Y.append( input (\"Please enter the coefficient of Y in the first equation: \") )\n Z.append( input (\"Please enter the coefficient of Z in the first equation: \") )\n A.append( = input (\"and what's after the = sign?\") )\n\n X.append( input (\"Please enter the coeficcient of X in the second equation: \") )\n Y.append( input (\"Please enter the coefficient of Y in the second equation: \") )\n Z.append( input (\"Please enter the coefficient of Z in the second equation: \") )\n A.append( = input (\"and what's after the = sign?\") )\n\n X.append( input (\"Please enter the coeficcient of X in the third equation: \") )\n Y.append( input (\"Please enter the coefficient of Y in the third equation: \") )\n Z.append( input (\"Please enter the coefficient of Z in the third equation: \") )\n A.append( = input (\"and what's after the = sign?\") )\n\n result, answer = trinomial(X, Y, Z, A)\n if result == DEPENDENT:\n print \"System is dependant, there are infinite solutions\"\n print\n elif result == INCONSISTENT:\n print \"System is inconsistant, there are no solutions\"\n print\n else:\n print \"the solution to the set of equations is (\"+ \",\".join(map(str, answer)) + \").\"\n print\n</code></pre>\n\n<p>But if you do any amount of python programming with this stuff you'll want to learn how to use numpy, which make your code:</p>\n\n<pre><code>def trinomial(X, Y, Z, A):\n system = numpy.array([X, Y, Z]).T\n unknowns = numpy.array([A])\n\n return numpy.linalg.solve(system, unknowns)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T06:50:47.843", "Id": "4516", "Score": "1", "body": "solve probably has better numerical stability." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T23:05:45.060", "Id": "2896", "ParentId": "2895", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:10:48.773", "Id": "2895", "Score": "3", "Tags": [ "python", "homework" ], "Title": "python: less ugly solution to the intersection of 3 lines in 3 dimensional space" }
2895
<p>How can I refactor this code? I know it's repetitive but I'm not sure how to fix it.</p> <pre><code>$(function() { $('#category-1-button a').bind('click', function() { $(this).css({opacity:'1'}); $('#category-2-button a,#category-3-button a').css({opacity:'0.4'}); $('#blog-headers').css({backgroundPosition: '0 0'}); $('#category_2,#category_3').hide(0, function() { $('#category_1').show(0); }); }); }); $(function() { $('#category-2-button a').bind('click', function() { $(this).css({opacity:'1'}); $('#category-1-button a,#category-3-button a').css({opacity:'0.4'}); $('#blog-headers').css({backgroundPosition: '0 -144px'}); $('#category_1,#category_3').hide(0, function() { $('#category_2').show(0); }); }); }); $(function() { $('#category-3-button a').bind('click', function() { $(this).css({opacity:'1'}); $('#category-1-button a,#category-2-button a').css({opacity:'0.4'}); $('#blog-headers').css({backgroundPosition: '0 -288px'}); $('#category_1,#category_2').hide(0, function() { $('#category_3').show(0); }); }); }); </code></pre>
[]
[ { "body": "<p>Give each <code>#category-n-button</code> a class like <code>category_button</code>.</p>\n\n<p>Bind the handler in the <a href=\"http://api.jquery.com/each/\" rel=\"nofollow\"><code>each()</code><sup><i>[docs]</i></sup></a> method so that you can use the index argument to calculate the background position.</p>\n\n<p>Use <code>this</code> to reference the element that received the event in the click handler.</p>\n\n<p>Use the <a href=\"http://api.jquery.com/not/\" rel=\"nofollow\"><code>not()</code><sup><i>[docs]</i></sup></a> method to exclude the <code>this</code> element from the other category buttons when setting the opacity.</p>\n\n<p>Use the <a href=\"http://api.jquery.com/filter/\" rel=\"nofollow\"><code>filter()</code><sup><i>[docs]</i></sup></a> method to show the category element that pertains to the index of <code>.each()</code> + 1.</p>\n\n<pre><code>$(function() {\n var categories = $('[id^=\"category_\"]');\n var category_buttons_a = $('.category_button a').each(function( idx ) {\n $(this).bind('click', function() {\n $(this).css({opacity:'1'});\n category_buttons_a.not(this).css({opacity:'0.4'});\n $('#blog-headers').css({backgroundPosition: '0 ' + (idx * -144) + 'px'});\n categories.hide().filter( '#category_' + (idx + 1) ).show();\n });\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:25:09.780", "Id": "4450", "Score": "1", "body": "This is clearly the better answer. I don't know if your use of partial matching in the id selector reduces performance, but my answer's `if` statements and node comparisons definitely do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:26:57.700", "Id": "4451", "Score": "0", "body": "@Justin: Yes, in browsers that don't support `querySelectorAll`, that initial partial ID selection will be slow, but since it only occurs once, then is cached, the overall impact is small." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:27:58.167", "Id": "4452", "Score": "0", "body": "...I really should have cached the `$('#blog-headers')` selection as well. I hate re-running selectors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T05:01:54.697", "Id": "4460", "Score": "0", "body": "Really nice answer, and nice tips (especially the `not` and `filter`). Thanks for sharing! Hey! This could be a recruiting test for my company! ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T09:50:37.653", "Id": "4473", "Score": "0", "body": "You can improve performance a little by prefixing the element name to your `$('.category_button a')` selector. In those circumstances Sizzle will use `getElementsByTagName(...)` to filter before attempting a class match, instead of having to check each DOM node specifically. You should also do this for your attribute selector `$('[id^=\"category_\"]')` too, and if at all possible, pass in a context (a point from which Sizzle will search)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T14:05:17.940", "Id": "4474", "Score": "0", "body": "@Matthew Abbott: Yes that's true, though it probably makes the most difference in browsers that don't support `querySelectorAll`. And then it will really just affect `'[id^=\"category_\"]'`, because with the `'.category_button a'` selector, I'm pretty sure Sizzle first selects all `<a>` elements, then traverses through their ancestors to see if they have one with the `category_button` class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T00:00:03.720", "Id": "4532", "Score": "0", "body": "incredible answer, sorry I was away for a couple days. thank you guys so much!!!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:11:16.733", "Id": "2901", "ParentId": "2900", "Score": "14" } }, { "body": "<p>The following will work right away. I did the following:</p>\n\n<ol>\n<li>Changed your <code>bind()</code> to a <code>click()</code>, which is more precise.</li>\n<li>Always set the opacity of all relevant links except <code>this</code> to 0 and then set the current one to 0.4.</li>\n<li>Combined all functions by using an <code>if</code> statement that compares parents. There is a slight performance loss here compared to three different functions.</li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code>$(function() {\n $('#category-1-button a, #category-2-button a, #category-3-button a').click(function () {\n $('#category-1-button a,#category-2-button a,#category-3-button a').not(this).css({opacity:'0.4'});\n $(this).css({opacity:'1'});\n var myParent = $(this).parent();\n if (myParent == $('#category-1-button')) {\n $('#blog-headers').css({backgroundPosition: '0 0'});\n $('#category_3,#category_2').hide(0, function() {\n $('#category_1').show(0);\n });\n } else if (myParent == $('#category-2-button')) {\n $('#blog-headers').css({backgroundPosition: '0 -144px'});\n $('#category_1,#category_3').hide(0, function() {\n $('#category_2').show(0);\n });\n } else if (myParent == $('#category-3-button')) {\n $('#blog-headers').css({backgroundPosition: '0 -288px'});\n $('#category_1,#category_2').hide(0, function() {\n $('#category_3').show(0);\n });\n }\n });\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> I borrowed the <code>.not(this)</code> from patrick dw's comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:22:34.503", "Id": "4453", "Score": "0", "body": "I think you put the `.not(this)` in the wrong spot. I imagine you meant to place it before the `.css()` call instead of before `.click()`. Thanks for the credit though. :o)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:26:14.490", "Id": "4454", "Score": "0", "body": "@patrick, I updated that probably less than a minute before your comment. Thanks, though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:29:48.713", "Id": "4455", "Score": "0", "body": "@Justin: Ah, I must have been looking at a stale version." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:13:52.807", "Id": "2902", "ParentId": "2900", "Score": "1" } }, { "body": "<p>I believe I've covered all the bases with this one.</p>\n\n<pre><code>(function($){\n\"use strict\";\nvar $categoryButtonLinks;\n\n$categoryButtonLinks = $('#category-1-button a, #category-2-button a, #category-3-button a').click(clickCategoryButtonLink);\n\n$categories = $('#category_1, #category_2, #category_3');\n\nfunction clickCategoryButtonLink(e)\n{\n var $this, $category, index, offset;\n $this = $(this).css('opacity', '1');\n index = $categoryButtonLinks.index($this);\n offset = -144 * index;\n index += 1;\n $category = $('#category_'+index);\n $categoryButtonLinks.not($this).css('opacity', '0.4');\n $('#blog-headers').css('background-position', '0 ' + offset + 'px' );\n $categories.not($category).hide(0, function(){\n $category.show(0);\n });\n}\n\n})(jQuery);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T02:23:39.710", "Id": "2903", "ParentId": "2900", "Score": "1" } }, { "body": "<p>patrick dw's answer is great (+1), but I'd like to suggest an alternative, namely refactoring all the dynamic styling out into the style sheet. While it does make te style sheet longer, especially due to the \"repeated\" selectors, it does have the (IMHO very important) advantage to put all the styles where they belong.</p>\n\n<p>Assuming the category buttons look like this:</p>\n\n<pre><code>&lt;div id=\"class=\"category-1-button\" class=\"category_button\"&gt;\n &lt;a href=\"#Category_1\"&gt;Category 1&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Notice the reference to the category in the <code>href</code>. If done right, this also can have the advantage, that the links would work without JavaScript (not that anyone cares about that nowadays...)</p>\n\n<p>And give the categories a common class, too (e.g. \"category\").</p>\n\n<h3>CSS</h3>\n\n<pre><code>.category_button a {\n opacity: 0.4;\n}\n\n.category {\n display: none;\n }\n\n/* The following rules/selectors could/should be generated by a script */\n.category_1_selected #category-1-button a,\n.category_2_selected #category-2-button a,\n.category_3_selected #category-3-button a {\n opacity: 1;\n}\n\n.category_1_selected #category_1,\n.category_2_selected #category_2,\n.category_3_selected #category_3 {\n display: block;\n}\n\n.category_1_selected #blog-headers {\n background-position: 0 0;\n }\n\n.category_2_selected #blog-headers {\n background-position: 0 -144px;\n }\n\n.category_3_selected #blog-headers {\n background-position: 0 -288px;\n }\n</code></pre>\n\n<h3>JavaScript</h3>\n\n<pre><code>$(function() {\n var category_buttons_a = $('.category_button a').click(function() {\n // I'm putting the class on the body as an example, but any other element the\n // surrounds the buttons, categorys and the blog header is fine.\n $(\"body\").removeClass().addClass(this.href.slice(1) + \"_selected\");\n });\n});\n</code></pre>\n\n<hr>\n\n<p>One remark on the HTML of the links: I based it on how I assume your links look like and IMHO it's wrong to do it like that. Instead it would be better to put the <code>class</code> (and if necessary the <code>id</code>) directly on the link and not on it's parent element:</p>\n\n<pre><code>&lt;div&gt;\n &lt;a href=\"#Category_1\" id=\"class=\"category-1-button\" class=\"category_button\"&gt;Category 1&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T08:50:59.210", "Id": "2904", "ParentId": "2900", "Score": "1" } } ]
{ "AcceptedAnswerId": "2902", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T01:58:37.033", "Id": "2900", "Score": "6", "Tags": [ "javascript", "jquery" ], "Title": "Showing one category and hiding two others when one of three buttons is clicked" }
2900
<p>I'm making a function that multiplies all numbers between an "a" input and a "b" input with <code>do</code> loop. If you please, check my function and say what's wrong since I don't know loops very well in Scheme.</p> <pre><code>(define (pi-function x y) (let ((result y)) (do ((limI x (+ x 1))) ((= limI y) result) (set! result (* result limI))))) </code></pre>
[]
[ { "body": "<p>You can use a <code>do</code> loop without using <code>set!</code>.</p>\n\n<pre><code>(define (product-of-range x y)\n (do ((result 1 (* result i))\n (i x (+ i 1)))\n ((&gt; i y) result)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T19:38:12.967", "Id": "4466", "Score": "0", "body": "But that doesn't work, when I call (product 1 3) it returns 3, but it should return 6. That function only multiply x for y. What should do, f.e. (product 1 3)\n(* 1 2)\n(* 2 3)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T19:38:47.623", "Id": "4467", "Score": "0", "body": "@gn66: It returns 6 for me. Notice that I updated the function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T19:32:37.017", "Id": "2909", "ParentId": "2908", "Score": "3" } } ]
{ "AcceptedAnswerId": "2909", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-10T19:15:50.217", "Id": "2908", "Score": "1", "Tags": [ "homework", "scheme", "mathematics" ], "Title": "Function that multiplies all numbers between \"a\" and \"b\" with do loop" }
2908
<blockquote> <p>Using C#, create a class which gets an action (parameter-less delegate) in its construction and has a single public method <code>bool execute()</code> which does the following:</p> <ul> <li><p>Executes the action only if no other thread is currently executing the action</p></li> <li><p>If another thread is already executing, wait until thread is finished before returning (but without executing action again)</p></li> <li><p>Return true if current thread executes that action, otherwise return false.</p></li> </ul> </blockquote> <p></p> <pre><code>public delegate bool Action(); private static int ThreadsCount = 100; //initialize threads count static void Main(string[] args) { Action act = Execute; bool t = act(); Console.WriteLine(t); Console.ReadLine(); } static bool Execute() { bool retVal = false; Thread thread = Thread.CurrentThread; string s = thread.Name; if (s == null) { test(); retVal = true; } else { ThreadsCount = ThreadsCount - 1; if (ThreadsCount &lt; 1) { //if all threads finished executing do whatever you wanna do here.. Console.WriteLine("C# language"); test(); retVal = true; } else { retVal = false; } } return retVal; } private static void test() { Console.WriteLine("C# language"); } </code></pre> <p>Is the above piece of code correct? Please give me your feedback.</p> <p>Please don't think that this is just exercise. This question was asked by one of the interviewers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T08:25:42.340", "Id": "4471", "Score": "0", "body": "`wait until thread finished before returning` - I do not see any code which will do it. `create class which get an action (parameter less delegate) in its construction` - you didn't show any class or constructor in your code. It's hard to review your code, it has some weird logic (`Thread.CurrentThread.Name == null`) and I do not see what this code should do." } ]
[ { "body": "<p>You need to look at how you can make the <code>Execute</code> method both thread-safe and true to the requirements of the method. You say that it only should return true in the case where the delegate is actually called, but you need to make sure that only one thread can call it at a time. That's where <code>lock</code> comes in. You could potentially do something like:</p>\n\n<pre><code>public class SingleCallAction\n{\n private readonly object sync = new object();\n private readonly Action action;\n private bool executed;\n\n public SingleCallAction(Action action)\n {\n if (action == null)\n throw new ArgumentNullException(\"action\");\n\n this.action = action;\n }\n\n public bool Execute()\n {\n if (!executed)\n {\n lock(sync)\n {\n if (!executed)\n {\n action();\n executed = true;\n return true;\n }\n }\n }\n\n return false;\n }\n}\n</code></pre>\n\n<p>Now, what this class provides is a wrapper around an <code>Action</code> delegate. We use <code>Action</code> because it supports both delegate assignment, or lambda assignment.</p>\n\n<p>The <code>Execute</code> method will first check to see if it has previously been executed (if it has, it will jump down to the <code>return false;</code> as its not the thread that has executed the delegate.</p>\n\n<p>If if hasn't executed, it will <code>lock</code> the <code>sync</code> object to prevent any other threads from executing the inner code block. The compiler is generating <code>Monitor.Enter</code> and <code>Monitor.Exit</code> calls here for you, worth a read up!</p>\n\n<p>After the lock, we check whether the <code>executed</code> flag is set again. This allows us to prevent race conditions for competing threads. Don't worry about race conditions when dealing with the <code>executed</code> flag, as variable reads/writes are always atomic operations (mostly).</p>\n\n<p>If we are the first thread to be executing the delegate, we can then execute it <code>action()</code>, set the flag as executed, and return true.</p>\n\n<p>Any subsequent calls will always result in false.</p>\n\n<p>To use in code:</p>\n\n<pre><code>var action = new SingleCallAction(() =&gt; Console.WriteLine(\"Executed\"));\n\nvar thread1 = new Thread(() =&gt; Console.WriteLine(action.Execute()));\nvar thread2 = new Thread(() =&gt; Console.WriteLine(action.Execute()));\n\nthread1.Start();\nthread2.Start();\n</code></pre>\n\n<p>Should result in:</p>\n\n<pre><code>Executed\nTrue\nFalse\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:46:29.220", "Id": "4509", "Score": "0", "body": "Assuming that we use the memory model of the ECMA specification, your code is not guaranteed to wait until the action is executed. You must have a memory barrier before setting `executed` true. Otherwise the code can be reordered (by compiler, jit-compiler or processor) and the `executed` might be set before `action()` is called. Anyway, +1 for a good answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T09:36:40.837", "Id": "2912", "ParentId": "2910", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T04:01:34.367", "Id": "2910", "Score": "3", "Tags": [ "c#", "interview-questions", "multithreading" ], "Title": "Determining if current thread is executing" }
2910
<p>I have written this Perl code, and there is still more to add, however I was hoping that I could get some opinions on whether it could be written better.</p> <p>Specifically, there is a central <code>if</code>-<code>elsif</code> structure. Should I make this a subroutine or not? What's best practice? </p> <p>Also, look at the 2nd block of code, and let me know if it's worth it to change this to a subroutine (either put entire <code>if</code>-<code>else</code> into sub, or just the inner portion).</p> <p>Generally, I'm just wondering if there are some better tricks to get the same job done. Perhaps using a array of hashes instead of array of arrays? For easier read. Would this prevent eq matches from appearing?</p> <p>First, the declarations:</p> <pre><code>#!/usr/bin/perl use strict; use warnings FATAL =&gt; "all"; require 'verbTenseChanger.pl'; ## -JUST FOR TESTING- ## my $chapter_section = "chpt"."31_4"; my $search_key = "move"; my $category_id = "all"; # --- Files --- # open(my $parse_corpus, '&lt;', "parsed${chapter_section}.txt") or die $!; # --- Different forms of the Searchword --- # my @temp_changeverbforms = map changeVerbForm( $search_key, 0, $_ ), 1..4; my @verbforms; push (@verbforms, $search_key);# Watch extra for loop foreach my $temp_changeverbforms (@temp_changeverbforms) { push (@verbforms, $temp_changeverbforms) unless ($temp_changeverbforms eq ""); } # --- Variables for required info from parser --- # my @entirechapter = &lt;$parse_corpus&gt;; my $chapternumber; my $sentencenumber; my $sentence; my $grammar_relation; my $argument1; my $argument2; my @all_matches; my $entirechapter = join ('',@entirechapter); ##Flatten file (make one big string) #To get each sent. and info in one string: my @sentblocks = split (/Parsing\s/,$entirechapter);##Remove "Parsing" which is on the line of the chptnumber $chapternumber = $sentblocks[1]; ## file: chpt... will always be at [1] # --- Retrieve necessary info from text --- # #Loop through all the sentences, and for each check every form of searchverb foreach my $sentblock (@sentblocks) { foreach my $verbform (@verbforms) { ##"next" skips to next iteration of loop, substitute for an over-arching if statement next unless ($sentblock =~ /\b$verbform\b/i); ##Ensure the sentence contains the searchkey next unless ($sentblock =~ /\(VB\w*\s+\b$verbform\b\)\s+/i); ##Ensure searchkey is a verb #Sent.number and Sentence: next unless ($sentblock =~ /\[(sent. \d+) len. \d+\]: \[(.+)\]/); ##Remember, talking about the whole block here $sentencenumber = $1; $sentence = $2; $sentence =~ s/, / /g; </code></pre> <p>Here is the <code>if</code>-<code>elsif</code> that may or may not be converted to a subroutine:</p> <pre><code> #Dependencies (relations and arguments): if ($category_id eq "all") { my @lines = split ("\n",$sentblock); ##Split by a newline foreach my $line (@lines) { my @matches; next unless ($line =~ /\b$verbform\b/i); ##Ensure dependency contains searchword ##NEXT LINE IS DIFFERENCE: next unless ($line =~ /subj\w*\(|obj\w*\(|prep\w*\(|xcomp\w*\(|agent\w*\(|purpcl\w*\(|conj_and\w*\(/); ##Ensure dependency only contains desired grammar relations next unless ($line =~ /(\w+)\((\w+)\-\d+\,\s(\w+)\-\d+\)/); ##Ensure dependency is a dependency AND get info from it $grammar_relation = $1; $argument1 = $2; $argument2 = $3; next if ($argument1 eq $argument2); ##Ensure 1st and 2nd argument aren't the same next if ($grammar_relation =~ /xcomp/i and $argument2 !~ /\b$verbform\b/i); ##Ensure for xcomp the searchword is the 2nd argument next if ($argument1 =~ /^\S$/ or $argument2 =~ /^\S$/); ##Exclude if argument is only 1 character push(@matches, $chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2); ##All here, so either all get pushed or none (no holes in array) push @all_matches, \@matches; } } elsif ($category_id eq "subj") { my @lines = split ("\n",$sentblock); ##Split by a newline foreach my $line (@lines) { my @matches; next unless ($line =~ /\b$verbform\b/i); ##Ensure dependency contains searchword next unless ($line =~ /subj\w*\(|agent\w*\(/); ##Ensure dependency only contains desired grammar relations next unless ($line =~ /(\w+)\((\w+)\-\d+\,\s(\w+)\-\d+\)/); ##Ensure dependency is a dependency AND get info from it $grammar_relation = $1; $argument1 = $2; $argument2 = $3; next if ($argument1 eq $argument2); ##Ensure 1st and 2nd argument aren't the same next if ($argument1 =~ /^\S$/ or $argument2 =~ /^\S$/); ##Exclude if argument is only 1 character push(@matches, $chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2); push @all_matches, \@matches; } } elsif ($category_id eq "xcomp") { my @lines = split ("\n",$sentblock); ##Split by a newline foreach my $line (@lines) { my @matches; next unless ($line =~ /\b$verbform\b/i); ##Ensure dependency contains searchword next unless ($line =~ /xcomp\w*\(|conj_and\w*\(|prep_by\w*\(|purpcl\w*\(/); ##Ensure dependency only contains desired grammar relations next unless ($line =~ /(\w+)\((\w+)\-\d+\,\s(\w+)\-\d+\)/); ##Ensure dependency is a dependency AND get info from it $grammar_relation = $1; $argument1 = $2; $argument2 = $3; next if ($argument1 eq $argument2); ##Ensure 1st and 2nd argument aren't the same next if ($grammar_relation =~ /xcomp/i and $argument2 !~ /\b$verbform\b/i); ##Ensure for xcomp the searchword is the 2nd argument next if ($argument1 =~ /^\S$/ or $argument2 =~ /^\S$/); ##Exclude if argument is only 1 character push(@matches, $chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2); push @all_matches, \@matches; } } elsif ($category_id eq "obj" or $category_id eq "prep") { my @lines = split ("\n",$sentblock); ##Split by a newline foreach my $line (@lines) { my @matches; next unless ($line =~ /\b$verbform\b/i); ##Ensure dependency contains searchword next unless ($line =~ /$category_id\w*\(/); ##Ensure dependency only contains desired grammar relations next unless ($line =~ /(\w+)\((\w+)\-\d+\,\s(\w+)\-\d+\)/); ##Ensure dependency is a dependency AND get info from it $grammar_relation = $1; $argument1 = $2; $argument2 = $3; next if ($argument1 eq $argument2); ##Ensure 1st and 2nd argument aren't the same next if ($argument1 =~ /^\S$/ or $argument2 =~ /^\S$/); ##Exclude if argument is only 1 character push(@matches, $chapternumber, $sentencenumber, $sentence, $grammar_relation, $argument1, $argument2); push @all_matches, \@matches; } } } } #To make the if elsif into subroutine: Name:get_all_matches Pass In: ($sentblock, $verbform, $chapternumber, $sentencenumber, $sentence) Return: @allmatches (if needed, return reference) </code></pre> <p>And then to print:</p> <pre><code># --- Loop through all Matches --- # for my $arrayref (@all_matches) { #for my $item (@$arrayref) { print @$arrayref, "\n\n\n"; #} } #Sort by what?? 1.grammar_relation 2.arguments 3.alphabetical #But how to print heading only once? use hash? # How to sort by frequency (ie. sort by the number sentences with the same grammar_relation AND arg1 AND arg2) </code></pre> <p>You can ignore the comments of the last one, or give me some bonus pointers from experience. Later, I have to sort the results. Would the sorting be done before that last step?</p> <p>Here's the format of the input if you're <em>really</em> inclined on understanding the code:</p> <blockquote> <p>Parsing file: chpt31_4.txt <br></p> <p>Parsing [sent. 15 len. 9]: [These, animals, move, slowly, or, not, at, all, .]<br></p> <p>(ROOT<br> (S<br> (NP (DT These) (NNS animals))<br> (VP (VBP move)<br> (ADVP (RB slowly)<br> (CC or)<br> (RB not))<br> (ADVP (IN at) (DT all)))<br> (. .)))<br></p> <p>det(animals-2, These-1)<br> nsubj(move-3, animals-2)<br> advmod(move-3, slowly-4)<br> advmod(move-3, not-6)<br> conj_or(slowly-4, not-6)<br> advmod(move-3, at-7)<br> pobj(at-7, all-8)<br></p> </blockquote>
[]
[ { "body": "<p>You, sir, need a <a href=\"http://www.perl.com/pub/2003/08/07/design2.html\" rel=\"nofollow\">Strategy</a> pattern -- at least to resolve your if->elseif problem. I find a Gang of Four style reference like <a href=\"http://www.blackwasp.co.uk/Strategy.aspx\" rel=\"nofollow\">http://www.blackwasp.co.uk/Strategy.aspx</a> to be a little easier on the brain for initial consumption of a new pattern than the perl deep-dive, but YMMV.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-12T12:57:11.487", "Id": "4479", "Score": "0", "body": "This is really interesting stuff, it does seem like an algorithm would be helpful. However... I just started learning Perl, so haven't gotten to objects yet, so it may take a while. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-12T13:13:22.260", "Id": "4480", "Score": "0", "body": "Just to clarify, a 'Design Pattern' is how you organize an algorithm, they don't generally solve issues except those of clarity / code quality. Martin Fowler and Kent Beck have some excellent books on code quality, notably in the areas of Design Patterns and Refactoring. Glad to help :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-12T00:03:17.317", "Id": "2919", "ParentId": "2911", "Score": "2" } }, { "body": "<p>Fewer temp variables make code much more readable:</p>\n\n<pre><code># --- Loop through all Matches --- #\nprint @{$_}, \"\\n\\n\\n\" for @all_matches;\n</code></pre>\n\n<p>The output of map is an array. Learn to chain array-outputting functions into other array-outputting functions to further reduce temp var clutter:</p>\n\n<pre><code># --- Different forms of the Searchword --- #\nmy @verbforms = (\n $search_key,\n (\n grep { $_ ne '' }\n map { changeVerbForm( $search_key, 0, $_ ) } (1..4);\n )\n );\n</code></pre>\n\n<p>See the <a href=\"http://www.stonehenge.com/merlyn/UnixReview/col64.html\" rel=\"nofollow\">Schwartzian Transform</a> for the most commonly used idiom of this idea.</p>\n\n<p>Use || and &amp;&amp; to reduce number of statements:</p>\n\n<pre><code>next if $arg1 eq $arg2 || $arg1 =~ /^\\S$/ || $arg2 =~ /^\\S$/;\n</code></pre>\n\n<p>I sense ternary operators may also service you well, but I'm out of time!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T21:01:13.303", "Id": "4543", "Score": "0", "body": "Does: `my @verbforms = (\n $search_key, \n map { changeVerbForm( $search_key, 0, $_ ) || (); } 1..4\n);` do the same thing? It seems to work the same on the outside...\n\nWould having all the next statements in one line increase or decrease efficiency??\n\nAnd wow, the ternary operator seems really powerful. Again is it less efficient than a standard if-else condition??\n\nThanks a lot for your time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T06:19:31.423", "Id": "2959", "ParentId": "2911", "Score": "2" } } ]
{ "AcceptedAnswerId": "2919", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T05:24:00.373", "Id": "2911", "Score": "3", "Tags": [ "parsing", "perl", "subroutine" ], "Title": "Verb tense parser" }
2911
<p>Conditional parsing (aka read some tokens and return true or false).</p> <p>As a solution to <a href="https://stackoverflow.com/questions/6228935/processing-conditional-statements">this SO question</a>, I wrote following code:</p> <pre><code>bool nectar_loader::resolve_conditional( const std::function&lt;bool(const string&amp;)&gt; &amp;config_contains ) { bool result = true; // My very own recursive implementation /* - each set of parenthesis is handled recursively - logical AND: + - logical OR: | - logical NOT: ! - two bools: "result" and "current" - "result" keeps global result, and is modified by "+" - "current" keeps results for "|" and "!" - syntax checking for invalid */ bool previous_was_operator = true; bool current = false; // keep track of current state string token; while( next_token(token) ) { conditional_operator op; if( map_value(conditional_operator_map, token, op) ) { if( previous_was_operator ) { if( op == conditional_operator::not_op ) current ^= current; // negate next else { syntax_error( "Conditional operators \'+\', \'|\', \')\', and \'(\' must be followed by a CONFIG string." ); break; } } else { switch(op) { case conditional_operator::right_parenthesis: // TODO: allow conditionals without outer parenthesis of the form (a+b)|(c) return result; case conditional_operator::left_parenthesis: // recurse return resolve_conditional( config_contains ); case conditional_operator::plus_op: result = result &amp;&amp; current; // "current" -&gt; "result" if( !result ) // negative when an element of a "+" expression current = false; // reset "current" break; case conditional_operator::or_op: // combine with "current" case conditional_operator::not_op: // unreachable throw runtime_error( "Internal logic error in nectar_loader::resolve_conditional" ); } } previous_was_operator = true; } else if( !previous_was_operator ) { syntax_error( "In a conditional all CONFIG strings must be seperated by a conditional operator \'+\', \'|\', \')\', or \'(\'." ); break; } else // previous was operator, so now we have a CONFIG string { // check CONFIG string, and perform a logical OR // TODO: check effect of "!" current = current || config_contains(token); } } return result; } </code></pre> <p><code>next_token()</code> reads the next token, and returns <code>false</code> if this fails. <code>syntax_error</code> sets a global error status with message which is checked after calling this function. <code>map_value</code> returns true if the token can be converted to an <code>enum class</code> value (so if it is a conditional operator as defined by me). This algorithm is more flexible than a shunting yard (due to my future plans).</p> <p>I have not tested this extremely well, but what do you think?</p>
[]
[ { "body": "<p>A few comments:</p>\n\n<pre><code>bool nectar_loader::resolve_conditional( const std::function&lt;bool(const string&amp;)&gt; &amp;config_contains )\n</code></pre>\n\n<p>I'd generally prefer to turn this into a template, and pass the correct function type (and if I used <code>std::function</code> at all, use it only internally to store something):</p>\n\n<pre><code>template &lt;class func&gt; \nbool nextar_loader::resolve_conditional(func &amp;config_contains) {\n\n\n\n bool result = true;\n // My very own recursive implementation\n /*\n - each set of parenthesis is handled recursively\n - logical AND: +\n - logical OR: |\n - logical NOT: !\n - two bools: \"result\" and \"current\"\n - \"result\" keeps global result, and is modified by \"+\"\n - \"current\" keeps results for \"|\" and \"!\"\n - syntax checking for invalid\n */\n</code></pre>\n\n<p>I'd prefer to move the block comment to just above the function header. I'd also prefer more descriptive names than <code>result</code> and <code>current</code>. Given their use, I'd consider names more like \"expression_value\" and \"subexpression_value\".</p>\n\n<pre><code> bool previous_was_operator = true;\n bool current = false; // keep track of current state\n</code></pre>\n\n<p>This comment seems to add nothing to our understanding of the code. I'd consider something more like: \"// Assume current sub-expression is invalid until parsed.\" (assuming that's really why you've initialized it to <code>false</code>).</p>\n\n<pre><code> string token;\n while( next_token(token) )\n {\n conditional_operator op;\n if( map_value(conditional_operator_map, token, op) )\n {\n if( previous_was_operator )\n {\n if( op == conditional_operator::not_op )\n current ^= current; // negate next\n</code></pre>\n\n<p>Again, the comment seems to do little to assist understanding of the code. I'd probably start by pointing out that an expression like <code>a op1 op2 b</code> is valid if and only if <code>op2</code> is a unary operator (of which this grammar apparently only supports one).</p>\n\n<pre><code> case conditional_operator::plus_op:\n result = result &amp;&amp; current; // \"current\" -&gt; \"result\"\n</code></pre>\n\n<p>Given that you're using it as an <code>and</code>, I'd name this <code>conditional_operator::and_op</code> (or something similar). Then name should reflect the logical meaning of the operator, not the fact that it happens to be (mis-)represented with the <code>+</code> character.</p>\n\n<pre><code> if( !result ) // negative when an element of a \"+\" expression\n current = false; // reset \"current\"\n</code></pre>\n\n<p>This <code>if</code> statement appears redundant (at least to me). You've just set <code>result</code> to the logical <code>and</code> of <code>current</code> and <code>result</code>, so it will be <code>true</code> if and only if both inputs were already true. </p>\n\n<pre><code>result = current = (current &amp;&amp; result);\n</code></pre>\n\n<p>So, both end up true if and only if both started out true. If either started out false, both end up false.</p>\n\n<pre><code> break;\n case conditional_operator::or_op: // combine with \"current\"\n\n case conditional_operator::not_op: // unreachable\n throw runtime_error( \"Internal logic error in nectar_loader::resolve_conditional\" );\n</code></pre>\n\n<p>This looks rather like a bug. Did you really intend that <code>or_op</code> would throw an exception as unreachable, or should there be a <code>break</code> after the <code>or_op</code> case?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T04:51:46.263", "Id": "45185", "ParentId": "2914", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T15:55:06.080", "Id": "2914", "Score": "3", "Tags": [ "c++", "parsing" ], "Title": "Conditional parsing, non-standard approach" }
2914
<p>I tried to implement a definitive, reliable URL query string parser that handles every corner case:</p> <ul> <li>it tries to be efficient by avoiding regex</li> <li>it takes full URLs or just query strings (as long as the query string begins with a question mark)</li> <li>it ignores the hash value</li> <li>it handles multiple equal parameter names</li> <li>it handles parameter names that equal built-in JavaScript methods and keywords</li> </ul> <p>What do you think - did I miss something? </p> <pre><code>function parseURLParams(url) { if (url === null) return; var queryStart = url.indexOf("?") + 1, queryEnd = url.indexOf("#") + 1 || url.length + 1, query = url.slice(queryStart, queryEnd - 1); if (query === url || query === "") return; var params = {}, nvPairs = query.replace(/\+/g, " ").split("&amp;"); for (var i=0; i&lt;nvPairs.length; i++) { var nv = nvPairs[i], eq = nv.indexOf("=") + 1 || nv.length + 1, n = decodeURIComponent( nv.slice(0, eq - 1) ), v = decodeURIComponent( nv.slice(eq) ); if ( n !== "" ) { if ( !Object.prototype.hasOwnProperty.call(params, n) ) { params[n] = []; } params[n].push(v); } } return params; } </code></pre> <p>It returns an object of arrays for parsed URLs with query strings and <code>undefined</code> if a query string could not be identified.</p> <p>I used this in an <a href="https://stackoverflow.com/q/814613/18771">answer over at SO</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T11:53:08.073", "Id": "4493", "Score": "0", "body": "Deleted my answer - I missed that line, sorry! :-) You might still want to take a look at [my other answer over at SO](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript/2880929#2880929). Interesting how those questions are so similar, posted less than a month apart and the votes are astoundingly different. I blame the `[jquery]` tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T11:57:21.270", "Id": "4494", "Score": "1", "body": "@Andy: Thanks for the cross-reference. I think the jQuery tag might have had an influence. ;) Especially since the 200+ votes answer is essentially flawed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T12:27:09.507", "Id": "4495", "Score": "0", "body": "@Andy: And, I'm sorry to say, so is your's. ;) Here's an improved version in your spirit: http://jsfiddle.net/Tomalak/APXH3/ :-) (It still has the problem of not handling multiple parameters of the same name)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T12:41:52.577", "Id": "4496", "Score": "0", "body": "@Tomalak: Now you have me intrigued :-P what is the flaw you spotted? Near as I can tell, the only difference is that you perform a global replace for `+` on the entire string (which may be more efficient), and you've allowed for a string to be passed instead of using the current URL, but I can't spot any differences beyond those. I decided not to bloat my answer by supporting dupe parameters, as that practice is a rare one. However, I did link to a proof-of-concept example that would parse the URL in a similar style to how PHP would handle it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T13:06:48.783", "Id": "4499", "Score": "0", "body": "@Andy Oh, you're right. If you just work on `window.location.search` and ignore duplicate params, your original version is fine, too. I was testing with full URLs; your key/value regex did not work with them. So, uhm... At least your approach could be more simplified (no nested function `d()`). :-P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T13:14:31.653", "Id": "4500", "Score": "0", "body": "@Tomalak: I'll take it under consideration for my next edit ;-)" } ]
[ { "body": "<p>Is it bug free? No.</p>\n\n<p>These two corner-cases have been missed:</p>\n\n<ol>\n<li>parameter values containing '=', i.e. 'example.com?foo==bar' (double equals) or '?foo=k=v'</li>\n<li>cannot handle parameters called 'toString' and 'valueOf' (amongst others.)</li>\n</ol>\n\n<p>The first may well count as malformed URL, but Chrome handles it and pass through == unencoded in <code>location.search</code>. To handle this, go back to basic <code>indexOf</code> usage.</p>\n\n<p>The second problem's just pedantic really. You could try and work around it using <code>!params.hasOwnProperty(n)</code> instead of <code>!(n in params)</code>, but you'll still get stuck if someone passes a parameter called <code>hasOwnProperty</code>. The only way I see around this is to fall back to some dire array-based collection populated something like:</p>\n\n<pre><code>var keys = [], params = [];\nfor (...) {\n var n = ..., v = ...;\n var i = keys.indexOf(n);\n if (i &gt;= 0) {\n if (!(params[i] instanceof Array)) {\n params[i] = [params[i]];\n }\n params.push(v);\n } else {\n params[i] = v;\n keys.push(n);\n }\n}\n</code></pre>\n\n<p>I guess you'd then have to resort to returning an array of arrays rather than an object. i.e. each element of the array returned would either be <code>[key, value]</code> or <code>[key, [values]]</code>, although client <em>might</em> find it easier to work with if you returned something like <code>[key, value1, value2, ...]</code> (which caters nicely for properties without values.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:30:56.537", "Id": "4508", "Score": "0", "body": "Wow, great answer. :-) I'll come up with an improved version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T20:18:01.103", "Id": "4510", "Score": "0", "body": "See modified answer. I've decided not to go down the array-of-arrays route as this is highly impractical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T06:28:48.413", "Id": "4513", "Score": "0", "body": "I like the way you handle and call hasOwnProperty - very nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T06:42:08.240", "Id": "4514", "Score": "0", "body": "Of course it would still be broken \"downstream\" - the object returned would have its `hasOwnProperty` overwritten. But the function would not break. Anything else that comes to mind? Efficiency-wise maybe? It seems a little bloated to me..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T08:42:49.897", "Id": "12444", "Score": "0", "body": "Try `Object.prototype.hasOwnProperty.call(params, n)`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T18:51:46.580", "Id": "2931", "ParentId": "2924", "Score": "2" } }, { "body": "<p>you could do a null check on the url argument because the following will throw an exception.</p>\n\n<pre><code>parseURLParams(null);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T06:32:34.713", "Id": "4535", "Score": "0", "body": "Good point. Done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T22:49:45.820", "Id": "2956", "ParentId": "2924", "Score": "2" } }, { "body": "<p>Seems a tiny bit over-engineered. Something like this should work just as well, and addresses searlea's points in his answer:</p>\n\n<pre><code>function parseURLParams(url) {\n var out = {}; \n (url.split('?')[1] || url).split('#')[0].split('&amp;').forEach(function(p) { \n var kv = p.match(/([^=]*)=?(.*)/), \n k = decodeURIComponent(kv[1]), \n v = decodeURIComponent(kv[2] || ''); \n hasOwnProperty.call(out, k) ? out[k].push(v) : out[k] = [v]; \n });\n return out;\n}\n</code></pre>\n\n<p>The regex match is only needed if you want to support equals signs in values, otherwise you can use <code>split</code> and the indices 0 and 1.</p>\n\n<p>The main (only?) difference is that pretty much any string will be treated as a viable query -- if there are no equals signs or ampersands, it's a query with just one key and no value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T02:52:23.493", "Id": "39481", "Score": "1", "body": "Yikes, just realized how old this question is =/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T03:01:59.200", "Id": "39482", "Score": "0", "body": "Hm. That's a little too compressed for my tastes. I like less \"clever\" code. Oh and `forEach()` is not portable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T03:46:10.057", "Id": "39483", "Score": "0", "body": "Fair enough. I felt the same way about `forEach` and ES5-only features for a long time, but I figure we're at the point by now where ES5 is \"normal\" and anything else is \"legacy,\" and can be shimmed or whatever if legacy support is needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T03:52:52.893", "Id": "39484", "Score": "0", "body": "Right, adding `forEach()` to the array prototype if necessary is not very difficult, you just have to remember to do it. I suppose most people use some sort of JS library anyway." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T02:45:10.230", "Id": "25464", "ParentId": "2924", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T09:05:02.157", "Id": "2924", "Score": "5", "Tags": [ "javascript", "parsing" ], "Title": "Is this query-string parser bug-free?" }
2924
<p>Please review this Android UnitConverter App which has been designed using Strategy Pattern.</p> <pre><code>public class UnitConverter extends Activity implements OnClickListener, AdapterView.OnItemSelectedListener { /** Called when the activity is first created. */ private Spinner SpinnerUnit; private EditText inputValue; private Spinner SpinnerFrom; private Spinner SpinnerTo; private Button ButtonConvert; private EditText ResultView; ArrayAdapter&lt;String&gt; unitarray; ArrayAdapter&lt;String&gt; unitarrayadapter; private Strategy currentStrategy; private String unitfrom; private String unitto; private static UnitConverter instance; //this is to test the Git repository @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SpinnerUnit = (Spinner)findViewById(R.id.SpinnerUnit); SpinnerUnit.setOnItemSelectedListener(this); unitarray=new ArrayAdapter&lt;String&gt;(this,android.R.layout.simple_spinner_item); unitarray. setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SpinnerUnit.setAdapter(unitarray); unitarray.add(getResources().getString(R.string.unit1)); unitarray.add(getResources().getString(R.string.unit2)); unitarray.add(getResources().getString(R.string.unit3)); unitarray.add(getResources().getString(R.string.unit4)); unitarray.add(getResources().getString(R.string.unit5)); unitarray.add(getResources().getString(R.string.unit6)); unitarray.add(getResources().getString(R.string.unit7)); unitarray.add(getResources().getString(R.string.unit8)); unitarray.setNotifyOnChange(true); SpinnerFrom = (Spinner)findViewById(R.id.SpinnerFrom); SpinnerFrom.setOnItemSelectedListener(this); SpinnerTo = (Spinner)findViewById(R.id.SpinnerTo); SpinnerTo.setOnItemSelectedListener(this); unitarrayadapter = new ArrayAdapter&lt;String&gt;(this,android.R.layout.simple_spinner_item); unitarrayadapter. setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); SpinnerFrom.setAdapter(unitarrayadapter); SpinnerTo.setAdapter(unitarrayadapter); unitarrayadapter.setNotifyOnChange(true); ResultView = (EditText)findViewById(R.id.TextViewResult); ResultView.setClickable(false); ButtonConvert = (Button)findViewById(R.id.Button01); ButtonConvert.setOnClickListener(this); inputValue = (EditText)findViewById(R.id.EditTextValue); //initialization currentStrategy = new TemperatureStrategy(); instance = this; } public static UnitConverter getInstance(){ return instance; } public void onItemSelected(AdapterView&lt;?&gt; parent){ } public void onNothingSelected(AdapterView&lt;?&gt; parent){ } public void onItemSelected(AdapterView&lt;?&gt; parent, View v, int position, long id){ if(v.getParent() == SpinnerUnit){ switch(position){ case 0: setStrategy(new TemperatureStrategy()); break; case 1: setStrategy( new WeightStrategy()); break; case 2: setStrategy(new LengthStrategy()); break; case 3: setStrategy(new PowerStrategy()); break; case 4: setStrategy(new EnergyStrategy()); break; case 5: setStrategy(new VelocityStrategy()); break; case 6: setStrategy(new AreaStrategy()); break; case 7: setStrategy(new VolumeStrategy()); break; } fillFromToSpinner(position); SpinnerFrom.setSelection(0); SpinnerTo.setSelection(0); //If only first spinner is selected and //the from and to spinners are not clicked at all unitfrom = (String)(SpinnerFrom.getItemAtPosition(0).toString()); unitto = (String)(SpinnerTo.getItemAtPosition(0).toString()); //reset the result ResultView.setText(""); } else if(v.getParent() == SpinnerFrom){ unitfrom = (String)(SpinnerFrom.getSelectedItem().toString()); } else if(v.getParent() == SpinnerTo){ unitto = (String)(SpinnerTo.getSelectedItem().toString()); } } private void fillFromToSpinner(int position){ switch(position) { case 0: fillSpinnerWithTempUnit(); break; case 1: fillSpinnerWithWeightUnit(); break; case 2: fillSpinnerWithLengthUnit(); break; case 3: fillSpinnerWithPowerUnit(); break; case 4: fillSpinnerWithenErgyUnit(); break; case 5: fillSpinnerWithVelocityUnit(); break; case 6: fillSpinnerWithAreaUnit(); break; case 7: fillSpinnerWithVolumeUnit(); break; } } private void fillSpinnerWithTempUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.temperatureunitc)); unitarrayadapter.add(getResources().getString(R.string.temperatureunitf)); unitarrayadapter.notifyDataSetChanged(); } private void fillSpinnerWithWeightUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.weightunitkg)); unitarrayadapter.add(getResources().getString(R.string.weightunitgm)); unitarrayadapter.add(getResources().getString(R.string.weightunitlb)); unitarrayadapter.add(getResources().getString(R.string.weightunitounce)); unitarrayadapter.add(getResources().getString(R.string.weightunitmg)); unitarrayadapter.notifyDataSetChanged(); } private void fillSpinnerWithLengthUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.lengthunitmile)); unitarrayadapter.add(getResources().getString(R.string.lengthunitkm)); unitarrayadapter.add(getResources().getString(R.string.lengthunitm)); unitarrayadapter.add(getResources().getString(R.string.lengthunitcm)); unitarrayadapter.add(getResources().getString(R.string.lengthunitmm)); unitarrayadapter.add(getResources().getString(R.string.lengthunitinch)); unitarrayadapter.add(getResources().getString(R.string.lengthunitfeet)); } private void fillSpinnerWithPowerUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.powerunitwatts)); unitarrayadapter.add(getResources().getString(R.string.powerunithorseposer)); unitarrayadapter.add(getResources().getString(R.string.powerunitkilowatts)); } private void fillSpinnerWithenErgyUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.energyunitcalories)); unitarrayadapter.add(getResources().getString(R.string.energyunitjoules)); unitarrayadapter.add(getResources(). getString(R.string.energyunitkilocalories)); } private void fillSpinnerWithVelocityUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.velocityunitkmph)); unitarrayadapter.add(getResources().getString(R.string.velocityunitmilesperh)); unitarrayadapter.add(getResources().getString(R.string.velocityunitmeterpers)); unitarrayadapter.add(getResources().getString(R.string.velocityunitfeetpers)); } private void fillSpinnerWithAreaUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.areaunitsqkm)); unitarrayadapter.add(getResources().getString(R.string.areaunitsqmiles)); unitarrayadapter.add(getResources().getString(R.string.areaunitsqm)); unitarrayadapter.add(getResources().getString(R.string.areaunitsqcm)); unitarrayadapter.add(getResources().getString(R.string.areaunitsqmm)); unitarrayadapter.add(getResources().getString(R.string.areaunitsqyard)); } private void fillSpinnerWithVolumeUnit(){ unitarrayadapter.clear(); unitarrayadapter.add(getResources().getString(R.string.volumeunitlitres)); unitarrayadapter.add(getResources().getString(R.string.volumeunitmillilitres)); unitarrayadapter.add(getResources().getString(R.string.volumeunitcubicm)); unitarrayadapter.add(getResources().getString(R.string.volumeunitcubiccm)); unitarrayadapter.add(getResources().getString(R.string.volumeunitcubicmm)); unitarrayadapter.add(getResources().getString(R.string.volumeunitcubicfeet)); } public void onClick(View v){ if(v == ButtonConvert){ if(!inputValue.getText().toString().equals("")){ double in = Double.parseDouble(inputValue.getText().toString()); double result = currentStrategy.Convert(unitfrom, unitto, in); ResultView.setText(Double.toString(result)); } else { ResultView.setText(""); } } } private void setStrategy(Strategy s){ currentStrategy = s; } } </code></pre> <p>The <code>Strategy</code> interface:</p> <pre><code>package training.android.trainingunitconverter; public interface Strategy { public double Convert(String from, String to, double input); } </code></pre> <p>And the different strategies for different Units like the following:</p> <pre><code>package training.android.trainingunitconverter; public class TemperatureStrategy implements Strategy { public double Convert(String from, String to, double input) { // TODO Auto-generated method stub if((from.equals( UnitConverter.getInstance().getApplicationContext().getResources(). getString(R.string.temperatureunitc)) &amp;&amp; to.equals((UnitConverter.getInstance().getApplicationContext(). getResources().getString(R.string.temperatureunitf))))){ double ret = (double)((input*9/5)+32); return ret; } if((from.equals(UnitConverter.getInstance().getApplicationContext(). getResources().getString(R.string.temperatureunitf)) &amp;&amp; to.equals((UnitConverter.getInstance().getApplicationContext(). getResources().getString(R.string.temperatureunitc))))){ double ret = (double)((input-32)*5/9); return ret; } if(from.equals(to)){ return input; } return 0.0; } } </code></pre> <p>Similarly for other strategies...</p> <p>The source code can also be downloaded from <a href="https://github.com/sommukhopadhyay/UnitConverter" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-03T21:08:38.530", "Id": "85832", "Score": "0", "body": "Never am able to point this out on SO, so I am so happy to *finally* be able to mention this: **Whenever Eclipse creates methods, delete the auto-generated method stub comment**. It has no place of being there whatsoever!" } ]
[ { "body": "<p>As the comment says, you should post the code, possibly in smaller parts. Until then some general suggestions:</p>\n\n<ul>\n<li>Clean up the indentation. You are mixing spaces and tabs.</li>\n<li>Clean up the variable/method names. By convention Java variables and method names start with a small letter and use camel case. For example, <code>fillspinnerwithtempunit</code> is difficult to read. <code>fillSpinnerWithTempUnit</code> would be better.</li>\n<li>Speaking of which: All the <code>fillspinnerwith...</code> methods are unnecessary. Add a method to your Strategy interface and get the list of units from the Strategy implementations. That will also get rid of the the second of the two switchs, which both switch over exactly the same values.</li>\n<li>The first switch should be replaced by an Array of class references.</li>\n<li>All the repetitive <code>...add(getResources().getString(...</code> blocks should be loops instead.</li>\n<li>You have all the units string in the resource file, but they are hard coded in the Strategies, too. If the resources are ever translated (that's why they are resources in the first place), then your app will break.</li>\n</ul>\n\n<p>There are many other problems with your code, but this should be a good start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T08:04:51.053", "Id": "4561", "Score": "0", "body": "github repos at https://github.com/sommukhopadhyay/UnitConverter has been updated... the app has been completely refactored for multilingual resources..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T12:38:40.943", "Id": "4565", "Score": "0", "body": "Work on the other points - and move the Strategies into separate file again. It's completely unusable to have everything in one file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-19T13:58:01.400", "Id": "4567", "Score": "0", "body": "RoToRa, suggest me a way to do that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:52:18.743", "Id": "5081", "Score": "0", "body": "Hi RoToRa, thank you for your valuable input... i have re-factored it again... this time the strategy class is not an inner class of the main Activity... instead i am maintaining a static reference of the instance of the main activity class throughout the package... and through this reference i am accessing the resources... and its working perfectly..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T11:03:30.243", "Id": "2938", "ParentId": "2928", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T15:05:57.073", "Id": "2928", "Score": "4", "Tags": [ "java", "android", "converting" ], "Title": "Unit Converter App" }
2928
<p>Please review the sales tax problem which has been designed using strategy pattern.</p> <p><strong>The Problem:</strong></p> <blockquote> <p>Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions. Also the Sales Tax should be rounded off to the nearest 0.05.</p> </blockquote> <h1>Item.h</h1> <pre><code>/* * Item.h * * Created on: Jun 7, 2011 * Author: som */ #ifndef ITEM_H_ #define ITEM_H_ class SalesTax; //This represents the Items which don't have an Import duty or any sales tax class Item { public: //Constructors Item(); Item(SalesTax *aSalesTax); //Interface Functions for Item //To calculate the price after tax and import duty virtual void CalculateTotalPrice(); //To calculate the total tax and import duty virtual void CalculateTotalTax(); //To set the price of the Items void SetPrice(double aPrice); //To get the price of the Items before tax double getPrice(); //To get the price of the items after tax double getTotalPrice(); //To get the total tax and import duty of the items double getTax(); //Data protected: //Works as the Strategy of the Sales Tax problem. //If in future the tax calculation becomes more complicated for different Items //we will just have to change this Strategy. We can also subclass this Strategy class //for future expansion of the tax calculation strategy SalesTax *iSalesTax; //Data protected: //These are the basic properties of any Item. //Hence these are made protected members so that the subclasses of Item can inherit //these properties double iPrice; double iTotalPrice; double iTotalTax; }; //This class represents the Items which have only Import Duty class ImportedItem : virtual public Item { public: //Constructors ImportedItem(); //This constructor helps to create Items having only Import duty ImportedItem(SalesTax *aSalesTax, double aImportDuty); //Override virtual void CalculateTotalTax(); protected: double iImportDuty; }; //This class represents the Items which have only Sales Tax but no Import Duty class NonFoodBookMedicalItem : virtual public Item { public: //Constructors NonFoodBookMedicalItem(); //This constructor helps to create Items having only Sales tax NonFoodBookMedicalItem(SalesTax *aSalesTax, double aRate); //Override virtual void CalculateTotalTax(); protected: double iRate; }; //This class represents the Items which have got both Import Duty as well as sales Tax class NormalItem: public ImportedItem, public NonFoodBookMedicalItem { public: NormalItem(); //This constructor helps to create Items having both Sales tax and Import duty NormalItem(SalesTax *aSalesTax, double aRate, double aImportDuty); //Override virtual void CalculateTotalTax(); }; #endif /* ITEM_H_ */ </code></pre> <h1>Item.cpp</h1> <pre><code>/* * Item.cpp * * Created on: Jun 7, 2011 * Author: som */ #include "SalesTax.h" #include "Item.h" Item::Item() {} Item::Item(SalesTax *aSalesTax): iSalesTax(aSalesTax), iPrice(0), iTotalPrice(0), iTotalTax(0) { } void Item::CalculateTotalPrice() { iTotalPrice = iPrice + iTotalTax; } double Item::getTotalPrice() { return iTotalPrice; } void Item::CalculateTotalTax() { iTotalTax = iSalesTax-&gt;ComputeSalesTax(iPrice, 0, 0); } void Item::SetPrice(double aPrice) { iPrice = aPrice; } double Item::getPrice() { return iPrice; } double Item::getTax() { return iTotalTax; } ImportedItem::ImportedItem() {} ImportedItem::ImportedItem(SalesTax *aSalesTax, double aImportDuty): Item(aSalesTax) { iImportDuty = aImportDuty; } void ImportedItem::CalculateTotalTax() { iTotalTax = iSalesTax-&gt;ComputeSalesTax(iPrice, 0, iImportDuty); } NonFoodBookMedicalItem::NonFoodBookMedicalItem() {} NonFoodBookMedicalItem::NonFoodBookMedicalItem(SalesTax *aSalesTax, double aRate): Item(aSalesTax) { iRate = aRate; } void NonFoodBookMedicalItem::CalculateTotalTax() { iTotalTax = iSalesTax-&gt;ComputeSalesTax(iPrice, iRate, 0); } NormalItem::NormalItem() {} NormalItem::NormalItem(SalesTax *aSalesTax, double aRate, double aImportDuty): Item(aSalesTax) { iRate = aRate; iImportDuty = aImportDuty; } void NormalItem::CalculateTotalTax() { iTotalTax = iSalesTax-&gt;ComputeSalesTax(iPrice, iRate, iImportDuty); } </code></pre> <h1>ItemCreator.h</h1> <pre><code>/* * ItemCreator.h * * Created on: Jun 7, 2011 * Author: som */ #ifndef ITEMCREATOR_H_ #define ITEMCREATOR_H_ #include "Item.h" const int ITEM_WITH_NOSALESTAX_AND_IMPORTDUTY = 1; const int ITEM_WITH_NOSALESTAX_ONLY_IMPORTDUTY = 2; const int ITEM_WITH_ONLY_SALESTAX_AND_NOIMPORTDUTY = 3; const int ITEM_WITH_BOTH_SALESTAX_AND_IMPORTDUTY = 4; const double SALES_TAX_RATE = 10; const double IMPORT_DUTY_RATE = 5; class Not_A_Standard_Item_Type_Exception { public: void printerrormsg(); }; class ItemCreator { public: virtual Item *Create(int aItemId); }; #endif /* ITEMCREATOR_H_ */ </code></pre> <h1>ItemCreator.cpp</h1> <pre><code>/* * ItemCreator.cpp * * Created on: Jun 7, 2011 * Author: som */ #include "ItemCreator.h" #include "Item.h" #include "SalesTax.h" #include &lt;iostream&gt; using namespace std; void Not_A_Standard_Item_Type_Exception::printerrormsg() { cout &lt;&lt; "Not the right Item Type..." &lt;&lt; endl; } Item *ItemCreator::Create(int aItemId) { SalesTax *st = new SalesTax(); switch(aItemId) { case ITEM_WITH_NOSALESTAX_AND_IMPORTDUTY: return new Item(st); break; case ITEM_WITH_NOSALESTAX_ONLY_IMPORTDUTY: return new ImportedItem(st, IMPORT_DUTY_RATE); break; case ITEM_WITH_ONLY_SALESTAX_AND_NOIMPORTDUTY: return new NonFoodBookMedicalItem(st, SALES_TAX_RATE); break; case ITEM_WITH_BOTH_SALESTAX_AND_IMPORTDUTY: return new NormalItem(st, SALES_TAX_RATE, IMPORT_DUTY_RATE); break; default: throw Not_A_Standard_Item_Type_Exception(); } } </code></pre> <h2>SalesTax.h</h2> <pre><code>/* * SalesTax.h * * Created on: Jun 7, 2011 * Author: som */ #ifndef SALESTAX_H_ #define SALESTAX_H_ //This class works as the Strategy of the Sales tax problem class SalesTax { public: //Default constructor SalesTax(); //This function helps to compute the Sales Tax virtual double ComputeSalesTax(double aPrice, double aRate, double aImportduty); private: //This is an helper function which will round off the sales tax double RoundOff(double aTax); }; #endif /* SALESTAX_H_ */ </code></pre> <h2>SalesTax.cpp</h2> <pre><code>/* * SalesTax.cpp * * Created on: Jun 7, 2011 * Author: som */ #include "SalesTax.h" SalesTax::SalesTax() {} double SalesTax::ComputeSalesTax(double aPrice, double aRate, double aImportduty) { double tx = (aPrice * aRate / (double(100))) + (aPrice * aImportduty / (double(100))); return RoundOff(tx); } //private: double SalesTax::RoundOff(double aTax) { int taxTemp = (int)aTax; double decimaltaxTemp = (double)(aTax - (int)taxTemp); int tempy = (int)(1000 * decimaltaxTemp) / 100; int tempz = (int)(1000 * decimaltaxTemp - tempy * 100); int temp = (int)(tempz / 10); int t = tempz % 10; if(t &gt;= 5) temp += 1; return (double)(taxTemp + tempy * (0.1) + temp * (0.01)); } </code></pre> <h2>main.cpp</h2> <pre><code>/* * main.cpp * * Created on: Jun 7, 2011 * Author: som */ #include "SalesTax.h" #include "Item.h" #include "ItemCreator.h" #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { typedef vector&lt;Item *&gt; listOfItem; listOfItem::iterator theIterator; listOfItem Basket; char answer = 'n'; double totalprice = 0; double totaltax = 0; do { int type_of_item; cout &lt;&lt; "Enter the type of Item...1,2,3,4" &lt;&lt; endl; cout &lt;&lt; "1 for ITEM_WITH_NOSALESTAX_AND_NOIMPORTDUTY" &lt;&lt; endl; cout &lt;&lt; "2 for ITEM_WITH_NOSALESTAX_ONLY_IMPORTDUTY" &lt;&lt; endl; cout &lt;&lt; "3 for ITEM_WITH_ONLY_SALESTAX_AND_NOIMPORTDUTY" &lt;&lt; endl; cout &lt;&lt; "4 for ITEM_WITH_BOTH_SALESTAX_AND_IMPORTDUTY" &lt;&lt; endl; cin &gt;&gt; type_of_item; ItemCreator *itemCreator = new ItemCreator(); try { Item *item = itemCreator-&gt;Create(type_of_item); cout &lt;&lt; "Enter the price of the Item" &lt;&lt; endl; double price; cin &gt;&gt; price; item-&gt;SetPrice(price); Basket.push_back(item); } catch(Not_A_Standard_Item_Type_Exception &amp;e) { e.printerrormsg(); } cout &lt;&lt; "Do you want to continue... Y/N" &lt;&lt; endl; cin &gt;&gt; answer; } while(answer == 'y'); theIterator = Basket.begin(); int pos = 0; while(theIterator != Basket.end()) { Basket.at(pos)-&gt;CalculateTotalTax(); totaltax += Basket.at(pos)-&gt;getTax(); Basket.at(pos)-&gt;CalculateTotalPrice(); double price = Basket.at(pos)-&gt;getPrice(); double price_after_tax = Basket.at(pos)-&gt;getTotalPrice(); totalprice += price_after_tax; cout &lt;&lt; "Item" &lt;&lt; pos + 1 &lt;&lt; " price " &lt;&lt; price &lt;&lt; endl; theIterator++; pos++; } cout &lt;&lt; "------------" &lt;&lt; endl; cout &lt;&lt; "Toal tax " &lt;&lt; totaltax &lt;&lt; endl; cout &lt;&lt; "Total price " &lt;&lt; totalprice &lt;&lt; endl; return 1; } </code></pre> <p>While pasting the source code I have found it has become unreadable. Hence please download the source code from <a href="https://github.com/sommukhopadhyay/SalesTax" rel="nofollow">here</a>.</p>
[]
[ { "body": "<p>I would use a diferent aproach instead of all this inheritance, I think it is simpler to use just Item class with Rate and ImportedDuty, on the factory just create and configure each item with the desired values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T17:18:45.447", "Id": "2982", "ParentId": "2929", "Score": "0" } }, { "body": "<pre><code>class NonFoodBookMedicalItem : virtual public Item\n{\n</code></pre>\n\n<p>I don't feel like this is the right approach, for several reasons. For a start, you've baked quite a bit of application logic right into the type name, which will be copied and reused throughout your code. How much work will be involved if the government decides that sales tax should apply to books? Every single usage of it will need to be updated to <code>NonFoodMedicalItem</code>.</p>\n\n<p><em>As an aside: never assume that tax situations won't change. UK Value Added Tax (VAT) was 17.5% for as long as anyone could remember, and everyone's formulae had it hard-coded. Thousands of forms had the VAT rate element pre-printed with 17.5%. This worked fine until the government changed it in the wake of the global financial crisis.</em></p>\n\n<p>Secondly, the naming is just awkward. Is it a non-food item that can be a book or medical item, or is it a non-food, non-book and non-medical item? The ordinary usage of the English language leaves this ambiguous.</p>\n\n<pre><code>class NormalItem: public ImportedItem, public NonFoodBookMedicalItem\n{\n</code></pre>\n\n<p>The public inheritance from <code>ImportedItem</code> here is questionable. Public inheritance in C++ should be used to model the \"is-A\" relationship, i.e. if <code>Foo</code> publically inherits from <code>Bar</code> then it should be the case that every instance of <code>Foo</code> <em>is</em> a <code>Bar</code>. It's clearly not the case that every item is an imported item.</p>\n\n<p>I'm not sure I see why you're using inheritance in the way you are, while at the same time using the strategy pattern. It looks like your aim was to employ the strategy pattern so that each instance delegated its tax calculations to its <code>iSalesTax</code> member object. The type of the object that the <code>iSalesTax</code> object points to can vary at run-time independently of the type of the object itself -- this is how the strategy pattern is supposed to work. But if you do this, I don't see the advantage in having a different static type for each tax situation. Should I be able to replace the <code>iSalesTax</code> in a book item with one that adds sales tax? If so, why declare a different type? If not, why use the strategy pattern?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T11:19:31.927", "Id": "7386", "Score": "0", "body": "hi sorry for replying late. the solution has three level of hierarchies - one is plain item (no sales tax and import duty)...from it imported item without sales tax has been derived...and then item with only sales tax has also been derived from item... the last hierarchy is for an item which has got both sales tax and import duty... in case VAT is added to every item it can be just added in the top most class, that is the item class.i think the nomenclature of the classes is a bit confusing.for a book with sales tax you have the lowest level class in which you can make the import duty zero." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T21:49:14.527", "Id": "3035", "ParentId": "2929", "Score": "4" } }, { "body": "<p>I see a number of things that may help you improve your code. In no particular order, here's what I found:</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. It's especially bad when used within an included file.</p>\n\n<h2>Avoid <code>switch</code> statements within a class</h2>\n\n<p>The <code>ItemCreator</code> class has a big <code>switch</code> statement which does nothing but match arbitrary constants to arbitrary constructors. This is a strong signal that the class hierarchy is faulty. Either the different constructors should be entirely different classes or the arbitrary constants should be solely defined within the context that they're used. </p>\n\n<h2>Rethink the class hierarchy</h2>\n\n<p>The use of a strategy pattern is not inherently faulty here, but the execution could be better. Specifically, each <code>Item</code> has a corresponding <code>SalesTax</code> so what would make sense is to have a set of <code>SalesTax</code> objects, each using the relevant rates and calculations, and that individual <code>Item</code> objects would point to one of the four possible static <code>SalesTax</code> objects. If the tax code changes at some later date, all that will be required is to update references to <code>SalesTax</code> objects. (Alternatively, have a <code>taxType</code> attribute attached to each <code>Item</code> which could be used by a <code>SalesTax</code> object to apply the correct calculation.) If that's done, the <code>Item</code> class interface looks like this:</p>\n\n<pre><code>class Item\n{\npublic:\n Item(double price, const SalesTax &amp;aSalesTax) : iPrice(price), iSalesTax(aSalesTax) {}\n Item(Item &amp;&amp;a) : iPrice(a.iPrice), iSalesTax(a.iSalesTax) {}\n double getPrice() const { return iPrice; }\n double getTax() const { return iSalesTax(iPrice); }\n double getTotalPrice() const { return getPrice() + getTax(); }\n\nprotected:\n double iPrice;\n const SalesTax &amp;iSalesTax;\n};\n</code></pre>\n\n<p>The <code>SalesTax</code> class would look like this:</p>\n\n<pre><code>class SalesTax\n{\npublic:\n SalesTax(double rate) : irate(rate) {};\n double operator()(const double price) const { return RoundOff(price * irate); }\n\nprivate:\n double RoundOff(double aTax) const;\n double irate;\n};\n</code></pre>\n\n<h2>Use rational return values</h2>\n\n<p>It is odd that <code>Item::CalculateTotalTax()</code> return <code>void</code>. It makes more sense for it to return a <code>double</code> that represents the calculated tax. It also doesn't make sense to have a separate <code>CalculateTotalTax</code> and then a <code>getTax</code> function. What if the caller forgets to call them in that sequence? Better would be to have a single call which calculates and returns the tax. The same is true of the <code>CalculateTotalPrice</code> and <code>getPrice</code> functions.</p>\n\n<h2>Declare member functions as <code>const</code></h2>\n\n<p>The <code>getPrice()</code> method doesn't (and shouldn't!) alter the underlying <code>Item</code> object, so it should be declared <code>const</code> to make it clear that it does not alter the object.</p>\n\n<h2>Use iterators fully</h2>\n\n<p>The code within <code>main</code> that calculates the final pricing and taxes, the code uses an iterator to traverse the <code>Basket</code> but then doesn't use it for anything else. Instead, it would be cleaner to use the actual iterator to make it clear what is being iterated and how it's being used. For example, the code could instead be written like this: </p>\n\n<pre><code>int pos = 1;\nfor (listOfItem::iterator it = Basket.begin(); it != Basket.end(); ++it, ++pos)\n{\n totaltax += (*it).getTax();\n double price = (*it).getPrice();\n totalprice += (*it).getTotalPrice();\n std::cout &lt;&lt; \"Item \" &lt;&lt; pos &lt;&lt; \" price \" &lt;&lt; price &lt;&lt; std::endl;\n}\n</code></pre>\n\n<h2>Use consistent naming</h2>\n\n<p>The convention you have mostly followed is one in which the class names begin with an uppercase letter, such as <code>SalesTax</code> and that class instances begin with a lowercase letter, such as <code>st</code>. However, you haven't used them consistently, so there is a <code>Basket</code> variable (which looks like a class name) and it is declared as a <code>listOfItem</code> type (which looks like a variable name).</p>\n\n<h2>Move long const strings to variables</h2>\n\n<p>Removing lengthy constant strings from within your program and assigning them to variables is an easy way to reduce clutter in your source code. For example:</p>\n\n<pre><code>const std::string itemPrompt(\n \"Enter the type of Item...1,2,3,4\\n\" \n \"1 for ITEM_WITH_NOSALESTAX_AND_NOIMPORTDUTY\\n\"\n \"2 for ITEM_WITH_NOSALESTAX_ONLY_IMPORTDUTY\\n\"\n \"3 for ITEM_WITH_ONLY_SALESTAX_AND_NOIMPORTDUTY\\n\" \n \"4 for ITEM_WITH_BOTH_SALESTAX_AND_IMPORTDUTY\\n\" \n);\nconst std::string pricePrompt(\n \"Enter the price of the Item\\n\"\n);\nconst std::string continuePrompt(\n \"Do you want to continue?... (y/n)\\n\"\n);\n</code></pre>\n\n<h2>Don't use <code>std::endl</code> unless you really need to flush the stream</h2>\n\n<p>The difference between <code>std::endl</code> and <code>'\\n'</code> is that <code>std::endl</code> actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.</p>\n\n<h2>Avoid using <code>new</code> and <code>delete</code></h2>\n\n<p>With C++11 and C++14, the use of <code>new</code> and <code>delete</code> is much more rare than it once was. This is because we have things such as smart pointers and RAII, which should be used instead. Whole classes of errors can be eliminated this way. For example, consider this rewritten loop within <code>main</code>:</p>\n\n<pre><code>do\n{\n std::cout &lt;&lt; itemPrompt;\n unsigned type_of_item;\n std::cin &gt;&gt; type_of_item;\n std::cout &lt;&lt; pricePrompt; \n double price;\n std::cin &gt;&gt; price;\n if (--type_of_item &lt; 4) {\n basket.emplace_back(price, tax[type_of_item]);\n }\n std::cout &lt;&lt; continuePrompt;\n std::cin &gt;&gt; answer;\n}\nwhile(answer == 'y');\n</code></pre>\n\n<p>The various tax rates are created like this:</p>\n\n<pre><code>const SalesTax tax[4] = { SalesTax(0), SalesTax(0.05), SalesTax(0.1), SalesTax(0.15) };\n</code></pre>\n\n<h2>Reserve non-zero return values for errors</h2>\n\n<p>The code currently ends with a <code>return 1;</code> but it would be much more typical to reserve non-zero values for error conditions and <code>return 0;</code> for the normal exit. In fact, this idiom is so common that you don't even need to write that line -- it will be generated automatically by the compiler.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-05T15:52:13.833", "Id": "118634", "Score": "0", "body": "Don't `push_back(Item(...))`, `emplace_back(...)` instead :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-05T16:47:47.880", "Id": "118640", "Score": "0", "body": "@Morwenn: absolutely right. I'd included a move constructor for `Item` and then forgot to use it! Answer is now amended - thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-05T05:12:51.837", "Id": "64765", "ParentId": "2929", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T15:16:05.590", "Id": "2929", "Score": "7", "Tags": [ "c++", "design-patterns", "finance" ], "Title": "Sales tax calculator" }
2929
<p>I know exactly how I would handle this in PHP, Python, JS, and AS, but I want to confirm that this is the correct approach to Enums in Java.</p> <p>I have a database view which has a status column. It will only ever have one of four values (in MySQL, I would have made it an enum type column, but the type doesn't <em>really</em> matter in my current context). Each directly maps to one of the values defined below.</p> <pre><code>public enum StatusDefinitions { NOT_STARTED("not started"), IN_PROGRESS("in progress"), COMPLETE("opted out"), OPTED_OUT("complete"); private String desc; private StatusDefinitions(String desc) { this.desc = desc.toLowerCase(); } public String getDescription() { return desc; } public static StatusDefinitions getStatus( String desc ) { desc = desc.toLowerCase(); for( StatusDefinitions it: StatusDefinitions.values() ) { if( it.getDescription().equals( desc ) ) return it; } return StatusDefinitions.NOT_STARTED; } } </code></pre> <p>Now, in my JSP, I loop <code>for(StatusDefinitions it: StatusDefinitions.values())</code> and have selected="selected" based on <code>if(modelObjStatus == it)</code>. When pulling this from/pushing it to the db, I have <code>status = StatusDefinitions.getStatus( rs.getString( "status" ) );</code>. And there is where I have this sensation that I've missed something. Looping through all of the Strings and comparing them seems like I lose the benefit of the Enum. It would almost seem better to have a series of <code>public static final Strings</code>.</p> <p>(Before anyone asks, because of the scope of this particular project, it doesn't make sense to make this an ORM.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T07:19:51.327", "Id": "4517", "Score": "0", "body": "Looks good. I'd probably go with something like `ProjectStatus` or `StatusType`. I don't like naming types plural unless each instance holds multiple things. Each instance of an enum is a single value, so `ProjectStatus.COMPLETE` reads best to me." } ]
[ { "body": "<p>To start with, this is not good:</p>\n\n<pre><code>COMPLETE(\"opted out\"), \nOPTED_OUT(\"complete\");\n</code></pre>\n\n<p>Otherwise, this is pretty standard code. There are two things I'd note:</p>\n\n<ol>\n<li>If <code>desc</code> is coming from the database, you may have a risk of NullPointerException if it comes as null once.</li>\n<li>Instead of looping and searching, you can create a map from description to value once and use it each time. Since your set of values is so small, performance difference is probably minimal, so this is question of taste.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:20:11.607", "Id": "4506", "Score": "0", "body": "LOL. I forgot that noticed that on the actual code, but I never fixed it in the example. This is the one in the java file:\n `OPTED_OUT(\"opted out\"), \n COMPLETE(\"complete\");`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:20:41.170", "Id": "4507", "Score": "0", "body": "But I'll definitely give you a 1+ for the spot" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:17:25.027", "Id": "2933", "ParentId": "2932", "Score": "6" } } ]
{ "AcceptedAnswerId": "2933", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T19:12:42.880", "Id": "2932", "Score": "3", "Tags": [ "java" ], "Title": "Obtaining column status definition" }
2932
<pre><code>public delegate DataTable loadDataTable(); DataTable shops = (cmbShop.Text == "All Shops") ? new loadDataTable(() =&gt; { Program.con.GET_Table_From_DataBase("sh", "select * from shops "); return Program.con.dst.Tables["sh"]; } ).Invoke() : new loadDataTable(() =&gt; { Program.con.GET_Table_From_DataBase("sh", "select * from shops where shopname='" + cmbShop.Text + "' "); return Program.con.dst.Tables["sh"]; } ).Invoke(); </code></pre> <p>I am just setting the value of <code>DataTable shops</code> here.</p> <p>I am learning about lambda expressions, so just for learning purposes, I want to know if this code can be shortened while using lambda expressions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T13:28:17.563", "Id": "4521", "Score": "4", "body": "Why on earth would you use a lambda expression here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T13:28:28.830", "Id": "4522", "Score": "7", "body": "You have a SQL injection vulnerability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T18:06:03.250", "Id": "4525", "Score": "2", "body": "Any code which has `combobox.Text` near `GetTableFromDatabase` can be *optimized*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T05:25:47.627", "Id": "4533", "Score": "0", "body": "@Slakes will you please explain(You have a SQL injection vulnerability)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T13:10:18.730", "Id": "4539", "Score": "2", "body": "http://xkcd.com/327/ http://en.wikipedia.org/wiki/SQL_injection" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-28T00:17:53.777", "Id": "261705", "Score": "0", "body": "To answer the original question, yes they can, e.g. with [this](https://thorium.github.io/Linq.Expression.Optimizer/) or [this](http://nessos.github.io/LinqOptimizer/)." } ]
[ { "body": "<p>You don't need any lambda expressions at all.</p>\n\n<p>You can write</p>\n\n<pre><code>if (cmbShop.Text == \"All Shops\")\n Program.con.GET_Table_From_DataBase(\"sh\", \"select * from shops \");\nelse\n Program.con.GET_Table_From_DataBase(\"sh\", \"select * from shops where shopname='\" + cmbShop.Text + \"' \");\n\nDataTable shops = Program.con.dst.Tables[\"sh\"];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T18:04:55.260", "Id": "4524", "Score": "1", "body": "You can move \neverything except second parameter out of the `if` statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-28T07:34:45.723", "Id": "261716", "Score": "0", "body": "no `{}` - this needs a review ;-P" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T13:28:01.810", "Id": "2945", "ParentId": "2937", "Score": "11" } }, { "body": "<p>Using lambda expressions here are a bit of overkill.</p>\n\n<p>Though I think this goes overboard (imho) on the ternary operator:</p>\n\n<pre><code> Program.con.GET_Table_FromDataBase(\"sh\", string.Format(\"select * from shops{0}\", \n (cmbShop.Text == \"All Shops\") ? string.Empty : string.Format(\" where shopname='\"+cmbShop.Text+\"'\"));\n</code></pre>\n\n<p>As others stated, I would reconsider how you are fetching your data. The current method might leave you exposed for a world of hurt. :) Changing your approach on data access will, more than likely, also change how you are building your queries so a lot of this would be moot.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T22:16:30.570", "Id": "2997", "ParentId": "2937", "Score": "1" } } ]
{ "AcceptedAnswerId": "2945", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T10:44:54.587", "Id": "2937", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Loading either all shops or a specifically named shop from a DataTable" }
2937
<p><a href="http://clojure.org/" rel="nofollow">Clojure</a> is a Lisp dialect which targets the Java Virtual Machine (<a href="http://github.com/richhickey/clojure-clr" rel="nofollow">and the CLR</a>). Its main features include a software transactional memory system for coherent updates to data structures, transparent access to Java libraries, a dynamic REPL development environment, runtime polymorphism, and built-in concurrent programming constructs.</p> <p>Good Clojure resources include</p> <ul> <li>The <a href="http://dev.clojure.org/display/doc/Getting+Started" rel="nofollow">Getting Started</a> wiki (including instructions on IDE / Emacs / Vim setup and build tools).</li> <li>The Clojure <a href="http://groups.google.com/group/clojure" rel="nofollow">Google group</a> archives.</li> <li><a href="http://faustus.webatu.com/clj-quick-ref.html" rel="nofollow">Clojure quick reference</a></li> <li><a href="http://clojure-examples.appspot.com/" rel="nofollow">Clojure Examples Wiki</a> -- a Wiki for collecting structured Clojure usage examples.</li> <li><a href="http://clojuredocs.org/" rel="nofollow">ClojureDocs</a> -- "Community powered Clojure Documentation and Examples".</li> <li><a href="http://disclojure.org/" rel="nofollow">Disclojure</a> -- daily summary of Clojure intertweets.</li> <li><a href="http://planet.clojure.in/" rel="nofollow">Planet Clojure</a> -- the Clojure blog aggregator.</li> <li><a href="http://4clojure.com/" rel="nofollow">4Clojure</a> -- Interactive fill-in-the-blank Clojure problems.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T11:54:14.283", "Id": "2939", "Score": "0", "Tags": null, "Title": null }
2939
Clojure is a Lisp dialect for the Java Virtual Machine. Its main features include a software transactional memory system for coherent updates to data structures, transparent access to Java libraries, a dynamic REPL development environment, runtime polymorphism, and built-in concurrent programming constructs.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T11:54:14.283", "Id": "2940", "Score": "0", "Tags": null, "Title": null }
2940
<p>I'm an experienced programmer, but just a beginner in Python, and would like some input on a small function that's working but which I'm not very happy with.</p> <p>It's used to produce XML tags (strings). The content argument can be a string, a number etc., but if it's a datetime I have to format it properly. Also, if there is no content, the tag should not be rendered (return empty string).</p> <pre><code>def tag(tagName, content): if isinstance(content, datetime): content = content.strftime('%Y%m%d%H%M') else: content = str(content) if content: return "&lt;" + tagName + "&gt;" + content + "&lt;/" + tagName + "&gt;" return "" </code></pre> <p>Please enlighten me!</p>
[]
[ { "body": "<p>Always use an XML library to read or write XML.\nStitching XML together with string concatenation misses the point of using XML.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T12:12:23.527", "Id": "4519", "Score": "0", "body": "If this simple function is all the XML functionality I need, I don't want to learn or take a dependency on a library. The question is not about that though, but would like to know if the function can be refactored into something more pretty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T13:00:33.777", "Id": "4520", "Score": "0", "body": "I'm not sure why you're asking - how could it be simpler or more readable than it is now? But if `content` may contain arbitrary strings, you're already producing invalid XML, so I'd focus on that problem first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T17:16:41.970", "Id": "4523", "Score": "0", "body": "\"how could it be simpler or more readable than it is now?\" I don't know. It's what I'm asking. I know how to make it better in other languages. It feels like there should be better ways, and I'm just wondering if Python provides any nice features I could use here. (My real problem is that I think Python is ugly, and I want someone to show me that it can be beautiful after all. I'm still waiting (-: )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T09:02:30.130", "Id": "4537", "Score": "0", "body": "Maybe you can give an example of what you'd do in a different language. I have no idea what you have in mind." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T12:10:14.793", "Id": "2942", "ParentId": "2941", "Score": "4" } }, { "body": "<p>I'll criticise the general design of the <code>tag</code> function.</p>\n\n<p><code>tag</code> can't accept general input, because that would produce invalid xml. It special-cases empty contents, which prevents it from being generally useful; there is no way to use it to get an empty tag (breaking a weak requirement of good APIs: making simple things possible). It only makes sense as a private part of a slightly larger program that produces valid xml, which you did not include.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T06:57:51.703", "Id": "4536", "Score": "0", "body": "I totally agree. And it is a private part of a slightly larger program, pswinpy: https://github.com/tormaroe/pswinpy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T22:36:17.993", "Id": "4546", "Score": "0", "body": "Well that settles the type-safety question, unfavourably. `content` needs to be properly quoted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T22:33:21.410", "Id": "2954", "ParentId": "2941", "Score": "2" } }, { "body": "<p>Try this:</p>\n\n<pre><code>return \"&lt;%s&gt;%s&lt;/%s&gt;\" % (tagName, content, tagName)\n</code></pre>\n\n<p>e.g:</p>\n\n<pre><code>def tag(tagName, content):\n if isinstance(content, datetime):\n content = content.strftime('%Y%m%d%H%M')\n else:\n content = str(content)\n\n if content:\n return \"&lt;%s&gt;%s&lt;/%s&gt;\" % (tagName, content, tagName)\n\n return \"\"\n</code></pre>\n\n<p>Slightly more attractive if that's what you want?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:36:20.203", "Id": "5000", "Score": "0", "body": "Since there have been no other concrete suggestions actually answering the question I guess 1) there is nothing really wrong or non-idiomatic with my code, and 2) you deserve to get your answer accepted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T21:54:47.633", "Id": "5015", "Score": "0", "body": "To be honest I think text based UI's are an ancient paradigm, but are mostly the best we have in terms of practicality for the moment. There are a whole array of approaches, node based UIs, wiki based UIs, social coding environments, batteries massively included libraries brimming with start convenience functions that might make logic / code elegance more obvious. Maybe it's offtopic or meandering but if you feel dissatisfied in general with the elegance - the problem isn't the language as such, it's the medium. It's steadily evolving." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T23:38:33.910", "Id": "5018", "Score": "0", "body": "Code Bubbles is one such thing I was thinking of: http://www.youtube.com/watch?v=PsPX0nElJ0k" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T18:29:13.587", "Id": "3313", "ParentId": "2941", "Score": "2" } } ]
{ "AcceptedAnswerId": "3313", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T12:05:07.070", "Id": "2941", "Score": "2", "Tags": [ "python", "strings", "xml" ], "Title": "XML-tag function" }
2941
<pre><code> &lt;select name="checkInDay" tabindex="3" onchange="calcDay();" class="ffe selectform" id="checkInDate"&gt; &lt;?php for($i=1;$i&lt;=31;$i++) { $value = $i &lt; 10 ? "0".$i : $i; ?&gt; &lt;option value="&lt;?= $value ?&gt;" &lt;?php if($i == 12) {?&gt; selected="selected" &lt;?php } ?&gt; &gt; &lt;?= $i ?&gt; &lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; </code></pre>
[]
[ { "body": "<p>I suggest to build a function which can be reused for the options:</p>\n\n<pre><code>function select_options($options, $selected = null) {\n $_options = '';\n foreach ($options as $value =&gt; $content) {\n $_options .= sprintf(\"&lt;option value=\\\"%s\\\"%s&gt;%s&lt;/option&gt;\\n\", $value, $value == $selected ? ' selected=\"selected\"' : '', $content);\n }\n\n return $_options;\n}\n</code></pre>\n\n<p>And some PHP \"magic\" for the values generation but it is not really needed:</p>\n\n<pre><code>&lt;?php $values = array_map(create_function('&amp;$v', 'return sprintf(\"%02d\", $v);'), range(1, 31)) ?&gt;\n&lt;select name=\"checkInDay\" tabindex=\"3\" onchange=\"calcDay();\" class=\"ffe selectform\" id=\"checkInDate\"&gt;\n &lt;?php echo select_options(array_combine($values, range (1, 31)), 12) ?&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>But more important than all: in a HTML template, use the <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\">PHP alternative notation</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T13:30:16.907", "Id": "2946", "ParentId": "2943", "Score": "5" } }, { "body": "<p><strong>Remove Magic Numbers</strong></p>\n\n<p>What does \"12\" represent? Why is it the selected value? </p>\n\n<p>Rather than leaving this as-is, I would strongly recommend replacing it with a more descriptive constant.</p>\n\n<p><strong>Business Logic</strong></p>\n\n<p>This may or may not be something worth changing. It really depends on what this drop-down is being used for.</p>\n\n<p>Does it make sense for this drop-down to have 31 numbers listed?</p>\n\n<p>It seems like the option 31 would only make sense for some months, whereas the options 1 - 28 make sense for all months. Is this being used next to Month drop-down? If so, perhaps it should dynamically update based on the month selected. If not, perhaps the options should be from 1 - 28, and then a last option, \"Last Day of Month\". </p>\n\n<p>If you keep it as-is, just be sure to be clear to your users what will happen in a month like February if they select 30.</p>\n\n<p><strong>Short Tags</strong></p>\n\n<p>I would personally avoid the use of short tags.</p>\n\n<p>For more information, see\n<a href=\"https://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use\">https://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use</a></p>\n\n<p><strong>Text Formatting</strong></p>\n\n<p>To pad your number with leading zeros, use a built-in function.</p>\n\n<p>As @spookycoder suggested:</p>\n\n<pre><code>$value = sprintf(\"&lt;option value=\\\"%02d\\\"\", $i);\n</code></pre>\n\n<p><strong>Code Is Read Far More Than It Is Written</strong></p>\n\n<p>Make the code as clear as is possible. As @Keven recommended, use the <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow noreferrer\">PHP alternative notation</a>. </p>\n\n<p><strong>A Matter of Taste</strong></p>\n\n<p>While this is just my preference, I would also consider moving whether or not the option is selected off the HTML option line.</p>\n\n<pre><code>&lt;?php \n if ($day == DEFAULT_CHECK_IN_DAY): // Changed $i to $day and made 12 a const for clarity\n $selected = ' selected=\"selected\"';\n else:\n $selected = '';\n endif;\n?&gt;\n&lt;option value=\"&lt;?php echo sprintf(\"%02d\", $day) ?&gt;\"&lt;?php echo $selected ?&gt;&gt;\n &lt;?php echo $day ?&gt;\n&lt;/option&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T18:48:55.853", "Id": "2971", "ParentId": "2943", "Score": "2" } } ]
{ "AcceptedAnswerId": "2946", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T12:39:12.593", "Id": "2943", "Score": "1", "Tags": [ "php", "datetime", "form" ], "Title": "Generating a selection box for the day of the month" }
2943
<p>i have created simple php engine, i want that this engine used html/php codes from mysql. Here is this php code and please if you find out some mistakes or bugs, please post here. I realy want to use this code for my website but i want to be sure this code safe and bug fixed, so help!</p> <pre><code>&lt;?php session_start(); if (isset($_SESSION['last-update']) and isset($_SESSION['update-num'])){ if ($_SESSION['last-update'] == date('H:i') and $_SESSION['update-num'] &gt; 30){die();} if ($_SESSION['last-update'] == date('H:i')){$_SESSION['update-num'] = $_SESSION['update-num'] + 1;} else {$_SESSION['last-update'] = date('H:i'); $_SESSION['update-num'] = 0;} } else { $_SESSION['last-update'] = date('H:i'); $_SESSION['update-num'] = 0; } include("scripts/dbconnect.php"); mysql_select_db("website"); if (isset($_GET['page'])){ if (strlen($_GET['page']) &gt; 50){die("incodrect URL !");} $result = mysql_query("SELECT * FROM modules WHERE page = ';".mysql_real_escape_string($_GET['page']).";'"); } else { $result = mysql_query("SELECT * FROM modules WHERE page LIKE ';home;'"); } $modules = array('top-header1','top-header2','header','bottom-header','top-body1','top-body2','body-top', 'body-left', 'body-center', 'body-right', 'body-bottom', 'bottom-body', 'footer-top', 'footer', 'bottom-footer'); while($row = mysql_fetch_array($result)){ switch ($row['position']){ case 'top-header1':$modules['top-header1'][] = $row['source']; break; case 'top-header2':$modules['top-header2'][] = $row['source']; break; case 'header':$modules['header'][] = $row['source']; break; case 'bottom-header':$modules['bottom-header'][] = $row['source']; break; case 'top-body1':$modules['top-body1'][] = $row['source']; break; case 'top-body2':$modules['top-body2'][] = $row['source']; break; case 'body-top':$modules['body-top'][] = $row['source']; break; case 'body-left':$modules['body-left'][] = $row['source']; break; case 'body-center':$modules['body-center'][] = $row['source']; break; case 'body-right':$modules['body-right'][] = $row['source']; break; case 'body-bottom':$modules['body-bottom'][] = $row['source']; break; case 'footer-top':$modules['footer-top'][] = $row['source']; break; case 'footer':$modules['footer'][] = $row['source']; break; case 'bottom-footer':$modules['bottom-footer'][] = $row['source']; break; } } mysql_close(); ?&gt; &lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;title&gt;test&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style/style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="root"&gt; &lt;div id="top-header1"&gt;&lt;?php if(isset($modules['top-header1'])){foreach($modules['top-header1'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="top-header2"&gt;&lt;?php if(isset($modules['top-header2'])){foreach($modules['top-header2'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="header"&gt;&lt;?php if(isset($modules['header'])){foreach($modules['header'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="bottom-header"&gt;&lt;?php if(isset($modules['bottom-header'])){foreach($modules['bottom-header'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="top-body1"&gt;&lt;?php if(isset($modules['top-body1'])){foreach($modules['top-body1'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="top-body2"&gt;&lt;?php if(isset($modules['top-body2'])){foreach($modules['top-body2'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="body"&gt; &lt;div id="body-top"&gt;&lt;?php if(isset($modules['body-top'])){foreach($modules['body-top'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="body-left"&gt;&lt;?php if(isset($modules['body-left'])){foreach($modules['body-left'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="body-center"&gt;&lt;?php if(isset($modules['body-center'])){foreach($modules['body-center'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="body-right"&gt;&lt;?php if(isset($modules['body-right'])){foreach($modules['body-right'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="body-bottom"&gt;&lt;?php if(isset($modules['body-bottom'])){foreach($modules['body-bottom'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="footer-top"&gt;&lt;?php if(isset($modules['footer-top'])){foreach($modules['footer-top'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="footer"&gt;&lt;?php if(isset($modules['footer'])){foreach($modules['footer'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="bottom-footer"&gt;&lt;?php if(isset($modules['bottom-footer'])){foreach($modules['bottom-footer'] as $value){eval($value);}} ?&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T00:17:16.313", "Id": "5205", "Score": "2", "body": "What is the point of this *engine*?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-15T10:28:34.797", "Id": "6125", "Score": "0", "body": "also you have spelt `incorrect` wrong" } ]
[ { "body": "<p>I would recommend against storing PHP code for your website in database fields. It will make it very difficult to maintain in the future.</p>\n\n<p>Also, be sure that if someone has an active session from 11:50 PM until 12:05 AM the next day, that your $_SESSION['last-update'] values will work as expected. Timestamps are typically stored as Unix timestamps with date('U'), which corrects this issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T19:09:55.470", "Id": "2972", "ParentId": "2947", "Score": "3" } }, { "body": "<p>Is this supposed to be templating engine? In that case you are doing it wrong. You might want to read <a href=\"http://codeangel.org/articles/simple-php-template-engine.html\" rel=\"nofollow\">this article</a>.</p>\n\n<p>Ass for the code:</p>\n\n<ul>\n<li><p>why there is possible to encounter <code>die()</code> at the top of the code? </p></li>\n<li><p>please, stop using <code>mysql_*</code> functions when writing new code. They are no longer maintained and the community has begun the <a href=\"http://news.php.net/php.internals/53799\" rel=\"nofollow\">deprecation process</a>. See the <a href=\"http://uk.php.net/manual/en/function.mysql-connect.php\" rel=\"nofollow\"><em>red box</em></a>? Instead you should learn how to use <a href=\"http://en.wikipedia.org/wiki/Prepared_statement\" rel=\"nofollow\">prepared statements</a> and utilize either <a href=\"http://php.net/pdo\" rel=\"nofollow\">PDO</a> or <a href=\"http://php.net/mysqli\" rel=\"nofollow\">MySQLi</a>. If you can't decide which, <a href=\"http://php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow\">this article</a> should help you. If you pick PDO, you find a good tutorial <a href=\"http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers\" rel=\"nofollow\">here</a>.</p></li>\n<li><p>the <code>switch</code> statement should be replaced with:</p>\n\n<pre><code>if ( in_array($row['position'], $modules) )\n{\n $modules[ $row['position' ]][] = $row['source']\n}\n</code></pre></li>\n<li><p>do not use <code>eval()</code></p></li>\n<li><p>do not put HTML, PHP and SQL in same file</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T11:44:35.753", "Id": "15611", "ParentId": "2947", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T15:04:23.913", "Id": "2947", "Score": "3", "Tags": [ "php", "mysql" ], "Title": "PHP simple engine" }
2947
<p>I'm sure there's a better more 'jQuery' like way of writing this. In particular the selector <code>$(this).closest('div.login-box')</code> being in there twice. Perhaps it's possible to use <code>$(this)</code>?</p> <pre><code>$('.close-box').click(function () { $(this).closest('div.login-box').slideToggle("400"); if ($(this).closest('div.login-box').attr('id') == "login-forgot") { clearForgottenPasswordInputs(); } }); </code></pre>
[]
[ { "body": "<p>You could combine the calls:</p>\n\n<pre><code>if ($(this).closest('div.login-box')\n .slideToggle(\"400\")\n .attr('id'))\n</code></pre>\n\n<p>However, I do not recommend this.<br>\nAlthough it will work, it's unnecessarily confusing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T21:02:53.030", "Id": "4526", "Score": "0", "body": "I dunno... if he just did `loginbox_id = $(this).closest('div.login-box').slideToggle(\"400\").attr('id');` Then he could just do `if (loginbox_id == \"login-forgot\")` below it. I think it removes any confusion that may occur by placing animation calls inside a boolean statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T21:19:28.953", "Id": "4528", "Score": "1", "body": "@day: Yes. However, it's still confusing to have a mutation and a property access in the same line." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T17:38:45.467", "Id": "2951", "ParentId": "2948", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T16:06:48.173", "Id": "2948", "Score": "1", "Tags": [ "javascript", "jquery", "form" ], "Title": "jQuery handler for closing a login box" }
2948
<p>Mostly for the experience (but also so I could waste hours playing it), I made a simple memory card game in JavaScript. I built it so it has a backbone framework that could be easily extended by stripping off my actual implementation. It's the backbone I'd like reviewed here, and mostly:</p> <ol> <li>My OO - anything wrong; anything that could be improved on?</li> <li>Obvious code efficiency: is there anything that could make it more efficient?</li> <li>Structure: Is the structure of the game a good idea? </li> </ol> <p></p> <pre><code>var Card = (function() { var self = Object.create({}, { val: { value: -1 }, index: { value: -1 }, addTo: { value: function(game) { var random = -1; counter = 0; //break counter to stop infinite loop. :) while ((game.cards[random] !== undefined &amp;&amp; counter &lt;= 100) | random === -1) { random = Math.round(game.cards.length * Math.random()); counter++; } this.index = random; game.cards[random] = this; } }, isMatch: { value: function(game) { if (this.val == game.selected.val) { game.matches++; return true; } return false; } } }); return self; })(); var Game = (function() { var self = Object.create({}, { cards: { value: new Array(30) }, matches: { value: 0 }, init: { value: function(func) { for (i = 0; i &lt; this.cards.length / 2; i++) { var card = Object.create(Card, { val: { value: i } }); var card2 = Object.create(Card, { val: { value: i } }); card.addTo(this); card2.addTo(this); } if (typeof func === 'function') { func(); } } }, selected: { value: null } }); return self; })(); </code></pre> <p>Sorry about the length; that's partly why I want it reviewed. </p> <p>To see how to implement it and the full code, see <a href="http://jsfiddle.net/thomas4g/tqGqq/100/" rel="nofollow">here</a></p> <p><strong>EDIT:</strong> FYI, I realize the game isn't currently extensible. For example, if I wanted there to be multiple types of matches, I can't do that quite yet. I'm pretty sure I know how to add that in, but I wanted to make sure my design structure was solid first.</p>
[]
[ { "body": "<p>I'll start off with some questions, because you are using techniques, that I don't have much experience with.</p>\n\n<ul>\n<li><p>What run time environment are you considering using? (Or in other words, which browsers do you want to support?) <code>Object.create</code> is very, very new and thus support isn't very wide spread.</p></li>\n<li><p>Why do you wrap all properties and methods in their own \"sub-objects\"?</p></li>\n</ul>\n\n<p>Both points together lead to (IMHO) very unwieldy code such as</p>\n\n<blockquote>\n<pre><code>var card = Object.create(Card, {\n val: {\n value: i\n }\n});\n</code></pre>\n</blockquote>\n\n<p>which would be much simpler with \"normal\" objects:</p>\n\n<pre><code>var card = new Card(i);\n</code></pre>\n\n<p>Speaking of which, using such a \"big\" class to represent a simple card sees a bit excessive to me, but if it's just for practice it's ok.</p>\n\n<p>However even for practice the <code>addTo</code> method is badly written. It's probably better to put all cards into the array in order of creation and then shuffle the array. Have a look at <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow\">Fisher-Yates</a> which is considered the \"standard\" algorithm for shuffling.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T12:18:13.360", "Id": "2962", "ParentId": "2949", "Score": "1" } }, { "body": "<p>First I see that both classes depend on each other and are tightly coupled together. Why does a Card object need to know its own index in an Array?</p>\n\n<p>Secondly, the Card object updates the game object, but the game object contains an array of the cards, which means the Game object owns a bunch of Card objects. </p>\n\n<p>If you were to remove the dual dependency, then you could rewrite your isMatch method to be</p>\n\n<pre><code> isMatch: {\n value: function(inCard) {\n return (this.val == inCard.val);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T15:14:49.513", "Id": "2995", "ParentId": "2949", "Score": "2" } } ]
{ "AcceptedAnswerId": "2962", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T17:25:37.750", "Id": "2949", "Score": "3", "Tags": [ "javascript", "object-oriented", "game" ], "Title": "My Memory Game \"Engine\"" }
2949
<p>I have a ActionScript 3 AIR class that I'd like you to check for robustness. I know it's quite a lot of code and It's not required that you review the full code, but maybe you see general problems in the way I handle exceptions or maybe you spot something that could make troubles.</p> <p>The purpose of the Class is to load a local SWF and to run it within the AIR security sandbox. Before doing so, it might update the swf in two ways:</p> <ol> <li><p>either there is a <code>MyApp_update.swf</code> present in the <code>app-storage</code> directory - in this case it should simply replace the current swf by this swf.</p></li> <li><p>if that's not the case, it connects to a server and checks whether a new version is available by downloading a <code>meta-info.xml</code> and comparing the version number on the server with the version number of the local <code>meta-info.xml</code></p></li> </ol> <p>It's important that this part of the code is robust, since the rest of the application we can easily update remotely (in case this class here is doing it's job well).</p> <pre><code>package { import flash.desktop.NativeApplication; import flash.display.Loader; import flash.display.NativeWindow; import flash.display.NativeWindowInitOptions; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.UncaughtErrorEvent; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.ByteArray; public class MyApp_Base extends Sprite { private var _remoteMetaRequest:URLRequest = new URLRequest("http://www.myServer.com/updater_test/my_app_meta.xml") private var _remoteSwfRequest:URLRequest = new URLRequest("http://www.myServer.com/updater_test/MyApp.swf"); private var _localSwfFile:File = new File("app-storage:/application/MyApp.swf"); private var _localSwfUpdateFile:File = new File("app-storage:/application/MyApp_update.swf"); private var _localMetaFile:File = new File("app-storage:/application/my_app_meta.xml"); private var _localMetaXML:XML; private var _remoteMetaXMLString:String; private var _remoteMetaXML:XML; private var _swfLoader:Loader = new Loader(); private var _swfUrlLoader:URLLoader = new URLLoader(); private var _progressBox:LoaderBox = new LoaderBox(); private var _progressWindow:NativeWindow; public function MyApp_Base() { loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError); //check if a local swf update file is present. if so, replace the current version with it, delete the update file and skip checking the server if(_localSwfUpdateFile.exists){ _swfUrlLoader.dataFormat = URLLoaderDataFormat.BINARY; _swfUrlLoader.addEventListener(Event.COMPLETE, updateSwfLoaded); _swfUrlLoader.addEventListener(IOErrorEvent.IO_ERROR, localUpdateError); try{ _swfUrlLoader.load(new URLRequest(_localSwfUpdateFile.nativePath)); } catch(e:Error){ showError("Error", "Error 1 while loading local update file. If this error persists, please contact the application author. \n"+e.message); return; } } else{ //check the server for a new update //load the local Metadata file: var s:FileStream = new FileStream(); try{ s.open(_localMetaFile,FileMode.READ); var xmlString:String = s.readUTFBytes(s.bytesAvailable); _localMetaXML = new XML(xmlString); s.close(); } catch(e:Error){ showWarning("Warning", "There was an Error while loading the file " +_localMetaFile.nativePath +". This could mean that your installation is corrupted. The updateserver is not checked for updates: \n"+e.message); loadAndRunLocalSwf(); return; } //load the remote Metadata file: var urlLoader:URLLoader = new URLLoader(); urlLoader.addEventListener(Event.COMPLETE, remoteXMLLoaded); urlLoader.addEventListener(IOErrorEvent.IO_ERROR, remoteXMLError); try{ urlLoader.load(_remoteMetaRequest); } catch(e:Error){ showWarning("Warning", "There was an Error while loading the file " +_remoteMetaRequest.url +". This error does not affect application execution, but prevents the application from being updated. If this error persists, please contact the application author. \n"+e.message); loadAndRunLocalSwf(); return; } } } private function remoteXMLLoaded(e:Event):void{ if(e.target.bytesLoaded!=e.target.bytesTotal){ trace("internet connection got interrupted during download of remoteXML"); remoteXMLError(null); return; } try{ _remoteMetaXMLString = e.target.data; _remoteMetaXML = new XML(_remoteMetaXMLString); var localVersion:int = _localMetaXML.version; var remoteVersion:int = _remoteMetaXML.version; } catch(e:Error){ showWarning("Warning", "The file " +_remoteMetaRequest.url +" is not correctly formatted. This error does not affect application execution, but prevents the application from being updated. If this error persists, please contact the application author. \n"+e.message); loadAndRunLocalSwf(); return; } if(remoteVersion&gt;localVersion) updateSWF(); else loadAndRunLocalSwf(); } private function remoteXMLError(e:Event):void{ loadAndRunLocalSwf(); } private function updateSWF():void{ _swfUrlLoader.dataFormat = URLLoaderDataFormat.BINARY; _swfUrlLoader.addEventListener(Event.COMPLETE, updateSwfLoaded); _swfUrlLoader.addEventListener(IOErrorEvent.IO_ERROR, remoteSwfError); _swfUrlLoader.addEventListener(ProgressEvent.PROGRESS, onProgressDownload); showProgressWindow("Downloading important software update"); try{ _swfUrlLoader.load(_remoteSwfRequest); } catch(e:Error){ showWarning("Warning", "There was an Error while loading the file " +_remoteSwfRequest.url +". This error does not affect application execution, but prevents the application from being updated. If this error persists, please contact the application author. \n"+e.message); loadAndRunLocalSwf(); return; } } private function remoteSwfError(e:Event):void{ if(_progressWindow){ try{ _swfUrlLoader.close(); _progressWindow.close(); _progressWindow = null; } catch(e:Error){} } loadAndRunLocalSwf(); } private function localUpdateError(e:Event):void{ showError("Error", "Error 2 while loading local update file. If this error persists, please contact the application author. \n"+e.toString); } private function updateSwfLoaded(e:Event):void{ if(e.target.bytesLoaded!=e.target.bytesTotal){ trace("internet connection got interrupted while downloading remote MyApp.swf"); remoteSwfError(null); return; } if(_progressWindow) _progressWindow.close(); _progressWindow = null; var ba:ByteArray = e.target.data; //if old backupfile exists, delete it var backup:File = new File("app-storage:/application/MyApp_backup.swf"); if(backup.exists){ try{ backup.deleteFile(); } catch(e:Error){ showError("Error", "Error while deleting file "+backup.nativePath+" : \n"+e.message); return; } } //make current SWF the backup var appFile:File = new File("app-storage:/application/MyApp.swf"); try{ appFile.moveTo(appFile.parent.resolvePath("MyApp_backup.swf")); } catch(e:Error){ showError("Error", "Error while creating backup of "+ appFile.nativePath+" . Make sure that there is only one instance of the MyApp running. If this error persists, please contact the application author. \n"+e.message); return; } //write the downloaded SWF to the disk var s:FileStream = new FileStream(); try{ appFile = new File("app-storage:/application/MyApp.swf"); s.open(appFile, FileMode.WRITE); s.writeBytes(ba); s.close(); } catch(e:Error){ showError("Error", "Error while writing MyApp.swf to disk. Will try to restore backup. If this error persists, please contact the application author. \n"+e.message); backup = new File("app-storage:/application/MyApp_backup.swf"); backup.moveTo(backup.parent.resolvePath("MyApp.swf")); return; } if(_localSwfUpdateFile.exists){//the update was performed by a local update file try{ _localSwfUpdateFile.deleteFile(); } catch(e:Error){ showError("Error", "Could not delete " + _localSwfUpdateFile.nativePath + ". If this error persists, please contact the application author. \n"+e.message); return; } } else{ //write the downloaded MetaData to the disk try{ s.open(_localMetaFile,FileMode.WRITE); s.writeUTFBytes(_remoteMetaXMLString); s.close(); } catch(e:Error){ showError("Error", "Error while writing "+ _localMetaFile.nativePath+" to disk. Make sure that there is only one instance of the MyApp running. If this error persists, please contact the application author.\n"+e.message); return; } } //run the loaded SWF loadAndRunLocalSwf(); } private function loadAndRunLocalSwf():void{ var context:LoaderContext = new LoaderContext(); context.allowLoadBytesCodeExecution = true; context.applicationDomain = ApplicationDomain.currentDomain; var s:FileStream = new FileStream(); try{ s.open(_localSwfFile,FileMode.READ); var ba:ByteArray = new ByteArray(); s.readBytes(ba); s.close(); _swfLoader.loadBytes(ba,context); } catch(e:Error){ showError("Error", "Error while launching "+_localSwfFile.nativePath+". This could mean that your installation is corrupted. If this error persists, please contact the application author.\n"+e.message); return; } } private function onUncaughtError(e:UncaughtErrorEvent):void { e.preventDefault(); var error:Error = e.error; showWarning("Uncaught Error:", error.message); return; } private function showError(title:String, msg:String):void{ var errorBox:ErrorBox = new ErrorBox(msg); var nativeWinOpt:NativeWindowInitOptions = new NativeWindowInitOptions(); nativeWinOpt.maximizable = false; nativeWinOpt.minimizable = true; nativeWinOpt.resizable = false; var window:NativeWindow = new NativeWindow(nativeWinOpt); window.stage.scaleMode = StageScaleMode.NO_SCALE; window.stage.align = StageAlign.TOP_LEFT; window.width = errorBox.width; window.height = errorBox.height; window.addEventListener(Event.CLOSE, closeApplication); errorBox.addEventListener(Event.CLOSE, closeApplication); window.title = title; window.stage.addChild(errorBox); window.activate(); } private function showWarning(title:String, msg:String):void{ var warningBox:WarningBox = new WarningBox(msg); var nativeWinOpt:NativeWindowInitOptions = new NativeWindowInitOptions(); nativeWinOpt.maximizable = false; nativeWinOpt.minimizable = true; nativeWinOpt.resizable = false; var window:NativeWindow = new NativeWindow(nativeWinOpt); window.stage.scaleMode = StageScaleMode.NO_SCALE; window.stage.align = StageAlign.TOP_LEFT; window.width = warningBox.width; window.height = warningBox.height; window.title = title; window.stage.addChild(warningBox); window.activate(); } private function showProgressWindow(msg:String):void{ _progressBox.setMessage(msg); _progressBox.setProgress(0.0); var nativeWinOpt:NativeWindowInitOptions = new NativeWindowInitOptions(); nativeWinOpt.maximizable = false; nativeWinOpt.minimizable = true; nativeWinOpt.resizable = false; _progressWindow = new NativeWindow(nativeWinOpt); _progressWindow.stage.scaleMode = StageScaleMode.NO_SCALE; _progressWindow.stage.align = StageAlign.TOP_LEFT; _progressWindow.width = _progressBox.width; _progressWindow.height = _progressBox.height; _progressWindow.addEventListener(Event.CLOSE, cancelDownload); _progressBox.addEventListener(Event.CLOSE, cancelDownload); _progressWindow.title = "Downloading..."; _progressWindow.stage.addChild(_progressBox); _progressWindow.activate(); } private function onProgressDownload(e:ProgressEvent):void{ _progressBox.setProgress(e.bytesLoaded/e.bytesTotal); } private function cancelDownload(e:Event):void{ if(_progressWindow){ try{ _swfUrlLoader.close(); _progressWindow.close(); _progressWindow = null; loadAndRunLocalSwf(); } catch(e:Error){} } } private function closeApplication(e:Event):void{ NativeApplication.nativeApplication.exit(); } } } </code></pre>
[]
[ { "body": "<p>After three and a half years, I guess your code turned out to be robust... even although your question went unanswered.</p>\n\n<p>I can't answer your core question, but here are some side remarks:</p>\n\n<hr>\n\n<pre><code> if(remoteVersion&gt;localVersion)\n updateSWF();\n else\n loadAndRunLocalSwf();\n</code></pre>\n\n<p>and</p>\n\n<pre><code> if(_progressWindow)\n _progressWindow.close();\n</code></pre>\n\n<p>Always add curly braces for if-else statements! It's just too easy to forget that they're not there and screw something up.</p>\n\n<hr>\n\n<pre><code> try{\n _remoteMetaXMLString = e.target.data;\n _remoteMetaXML = new XML(_remoteMetaXMLString);\n var localVersion:int = _localMetaXML.version;\n var remoteVersion:int = _remoteMetaXML.version;\n }\n catch(e:Error){\n showWarning(\"Warning\", \"The file \" +_remoteMetaRequest.url +\" is not correctly formatted. This error does not affect application execution, but prevents the application from being updated. If this error persists, please contact the application author. \\n\"+e.message);\n loadAndRunLocalSwf();\n return; \n }\n</code></pre>\n\n<p>You seem to have some inconsistent indentation. See if your IDE supports automated formatting.</p>\n\n<hr>\n\n<pre><code> var ba:ByteArray = e.target.data;\n\n //if old backupfile exists, delete it\n var backup:File = new File(\"app-storage:/application/MyApp_backup.swf\");\n if(backup.exists){\n try{\n backup.deleteFile();\n }\n catch(e:Error){\n showError(\"Error\", \"Error while deleting file \"+backup.nativePath+\" : \\n\"+e.message);\n return;\n }\n }\n\n //make current SWF the backup\n var appFile:File = new File(\"app-storage:/application/MyApp.swf\");\n try{\n appFile.moveTo(appFile.parent.resolvePath(\"MyApp_backup.swf\"));\n }\n catch(e:Error){\n showError(\"Error\", \"Error while creating backup of \"+ appFile.nativePath+\" . Make sure that there is only one instance of the MyApp running. If this error persists, please contact the application author. \\n\"+e.message);\n return;\n }\n\n //write the downloaded SWF to the disk\n var s:FileStream = new FileStream();\n try{\n appFile = new File(\"app-storage:/application/MyApp.swf\");\n s.open(appFile, FileMode.WRITE);\n s.writeBytes(ba);\n</code></pre>\n\n<p>You declare a <code>ByteArray</code>, but then you don't use it until a good 30 lines later. Additionally, you keep redefining <code>e</code> as <code>Error</code>, where it was previously an event.</p>\n\n<p>My compiler gives warning messages for this sort of thing. When you're concerned about the robustness of your code, I recommend you take some time to look at <strong>each and every</strong> warning that pops up for that bit of code. Automated code checking is there to help you, not to be whiny and annoying that you didn't color between the lines.</p>\n\n<hr>\n\n<pre><code> private function updateSwfLoaded(e:Event):void{\n if(e.target.bytesLoaded!=e.target.bytesTotal){\n trace(\"internet connection got interrupted while downloading remote MyApp.swf\");\n remoteSwfError(null);\n return;\n }\n if(_progressWindow)\n _progressWindow.close();\n _progressWindow = null;\n\n var ba:ByteArray = e.target.data;\n\n //if old backupfile exists, delete it\n var backup:File = new File(\"app-storage:/application/MyApp_backup.swf\");\n if(backup.exists){\n try{\n backup.deleteFile();\n }\n catch(e:Error){\n showError(\"Error\", \"Error while deleting file \"+backup.nativePath+\" : \\n\"+e.message);\n return;\n }\n }\n\n //make current SWF the backup\n var appFile:File = new File(\"app-storage:/application/MyApp.swf\");\n try{\n appFile.moveTo(appFile.parent.resolvePath(\"MyApp_backup.swf\"));\n }\n catch(e:Error){\n showError(\"Error\", \"Error while creating backup of \"+ appFile.nativePath+\" . Make sure that there is only one instance of the MyApp running. If this error persists, please contact the application author. \\n\"+e.message);\n return;\n }\n\n //write the downloaded SWF to the disk\n var s:FileStream = new FileStream();\n try{\n appFile = new File(\"app-storage:/application/MyApp.swf\");\n s.open(appFile, FileMode.WRITE);\n s.writeBytes(ba);\n s.close();\n }\n catch(e:Error){\n showError(\"Error\", \"Error while writing MyApp.swf to disk. Will try to restore backup. If this error persists, please contact the application author. \\n\"+e.message);\n backup = new File(\"app-storage:/application/MyApp_backup.swf\");\n backup.moveTo(backup.parent.resolvePath(\"MyApp.swf\"));\n return;\n }\n\n if(_localSwfUpdateFile.exists){//the update was performed by a local update file\n try{\n _localSwfUpdateFile.deleteFile();\n }\n catch(e:Error){\n showError(\"Error\", \"Could not delete \" + _localSwfUpdateFile.nativePath + \". If this error persists, please contact the application author. \\n\"+e.message);\n return;\n }\n }\n else{ \n //write the downloaded MetaData to the disk\n try{\n s.open(_localMetaFile,FileMode.WRITE);\n s.writeUTFBytes(_remoteMetaXMLString);\n s.close();\n }\n catch(e:Error){\n showError(\"Error\", \"Error while writing \"+ _localMetaFile.nativePath+\" to disk. Make sure that there is only one instance of the MyApp running. If this error persists, please contact the application author.\\n\"+e.message);\n return;\n }\n }\n\n //run the loaded SWF\n loadAndRunLocalSwf();\n }\n</code></pre>\n\n<p>Consider splitting this function up into functions like <code>deleteOldBackupFile</code>, <code>backupSwf</code>,\n<code>writeDownloadedSwf</code>...</p>\n\n<p>This would make the code's structure more easy to discern and comprehend.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T16:09:53.923", "Id": "78648", "ParentId": "2952", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T18:51:13.900", "Id": "2952", "Score": "3", "Tags": [ "actionscript-3" ], "Title": "AS3 AIR class robustness check" }
2952
<p>I am terrible with writing JavaScript code that outputs HTML. So, here's how a string literal looks like in a project that I'm working on:</p> <pre><code>tweet = '&lt;div class="h-ui-box"&gt;' + '&lt;table&gt;' + '&lt;tr&gt;' + '&lt;td id="first"&gt;' + '&lt;img src="' + item.profile_image_url + '" alt="' + item.from_user + '" width="56"&gt;' + '&lt;/td&gt;' + '&lt;td&gt;' + '&lt;section&gt;' + '&lt;header&gt;' + '&lt;h1&gt;&lt;a href="http://twitter.com/' + (function(from_user) { return from_user + '"&gt;' + from_user + '&lt;/a&gt;&lt;/h1&gt;'; })(item.from_user) + '&lt;/header&gt;' + '&lt;article&gt;' + item.text.twitterify() + '&lt;/article&gt;' + '&lt;/section&gt;' + '&lt;/td&gt;' + '&lt;/tr&gt;' + '&lt;/table&gt;' + '&lt;footer&gt;&lt;a href="http://twitter.com/' + item.from_user + '/status/' + item.id.toString() + '" target="_blank"&gt;' + item.created_at + '&lt;/a&gt;&lt;/footer&gt;' + '&lt;/div&gt;'; </code></pre> <p>How would I go about to improve this?</p>
[]
[ { "body": "<p>Make yourself a \"template\" that you immediately convert into html (using innerHtml or whatever your framework has handy), then use the dom to fix up the few variable bits. You may use ids to locate the tags that need substitution, if you can guarantee they are unique. Otherwise use XPath.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T22:42:00.440", "Id": "2955", "ParentId": "2953", "Score": "4" } }, { "body": "<p>Writing that much markup dynamically will prove a headache eventually. Put the markup directly into your page, including reasonable default content. It'll be easier for you to read/edit/validate, while ensuring that you're giving something to search engines, screenreaders, and anyone who's got JS turned off. From there, follow Tobu's counsel.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-14T00:46:42.730", "Id": "4079", "ParentId": "2953", "Score": "3" } }, { "body": "<p>This is an area I've done a bit of work in lately.</p>\n\n<p>Initially my requirements were pretty minimal, and so I started using a really basic function that acted on a String (the template) and accepted an Object (containing the data to be presented) as a parameter, like this:</p>\n\n<pre><code>if (!String.prototype.supplant) {\n String.prototype.supplant = function (o) {\n return this.replace(/{([^{}]*)}/g,\n function (a, b) {\n var r = o[b];\n return typeof r === 'string' || typeof r === 'number' ? r : a;\n }\n );\n };\n}\n</code></pre>\n\n<p>(<a href=\"http://javascript.crockford.com/remedial.html\" rel=\"nofollow\">Thanks to Douglas Crockford</a>)</p>\n\n<p>You'd use it like this:</p>\n\n<pre><code>param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};\nurl = \"{media}logo.gif\".supplant(param);\n</code></pre>\n\n<p>So your template is a string of markup, with placeholders named for the properties in the object.\nThis approach is a little tidier than inlining everything, but still doesn't mitigate the slightly dirty feeling of having markup in JS strings.</p>\n\n<p>My requirements then became more complex, requiring some conditional logic within the templates.\nI then discovered jQuery templating (since jQuery is our library of choice) but it unfortunately died in beta, but has fortunately been superseded by <a href=\"https://github.com/BorisMoore/jsrender\" rel=\"nofollow\">JSRender</a>.</p>\n\n<p>JSRender is jQuery-independent, really fast, flexible, and uses templates that are declared as elements in the markup of the page rather than in JS strings.</p>\n\n<p>It has some nifty conditional logic and other handy features.</p>\n\n<p>I'd suggest this would be the way to go.\nDo bear in mind, however, that JSRender is currently pre-beta. I've just started using it for a particular project, and it's working really well for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T03:58:45.543", "Id": "6583", "ParentId": "2953", "Score": "1" } }, { "body": "<p>I've had lots of success with <a href=\"http://api.jquery.com/category/plugins/templates/\" rel=\"nofollow noreferrer\">jquery templates</a> in the past.</p>\n\n<p>For example:</p>\n\n<pre><code>var markup='&lt;tr&gt;&lt;td&gt;${id}&lt;/td&gt;&lt;td&gt;&lt;a href=\"/index/tender/id/${id}\"&gt;${title}&lt;/a&gt;&lt;/td&gt;&lt;td {{if days_left &lt;1}} class=\"label warning\" {{/if}} &gt;${days_left}&lt;/td&gt;&lt;/tr&gt;'; \n\n$.template( \"templateTenders\", markup ); //compile the markup as a jquery.template\n\n//....get json data - via an ajax call \n$.tmpl(\"templateTenders\", data).appendTo( \"#tenderlist\" ); //data is a JSON data object (assoc array) that comes in via ajax.\n</code></pre>\n\n<p><strong>[edit]</strong></p>\n\n<p>I've since moved onto using <a href=\"http://mustache.github.com/\" rel=\"nofollow noreferrer\">mustasche.js</a> which is wonderful.</p>\n\n<p><strong>[edit 2013]</strong></p>\n\n<p>I've since moved onto using handlebar.js(<a href=\"https://stackoverflow.com/questions/4392634/mustache-js-vs-jquery-tmpl/9481181#9481181\">https://stackoverflow.com/questions/4392634/mustache-js-vs-jquery-tmpl/9481181#9481181</a>) which is even more wonderful and a lot faster than mustache.js</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T21:26:47.607", "Id": "10293", "Score": "0", "body": "Please note that, as I've mentioned in my answer to this question, the [jQuery Templates](http://api.jquery.com/category/plugins/templates/) plugin is no longer being developed or maintained, and has been superseded by [JSRender and JSViews](http://www.borismoore.com/2011/10/jquery-templates-and-jsviews-roadmap.html), which are admittedly still pre-beta, but it looks like they will be the way forward." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T11:31:03.657", "Id": "6589", "ParentId": "2953", "Score": "3" } } ]
{ "AcceptedAnswerId": "2955", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T21:55:12.010", "Id": "2953", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "JavaScript string that holds HTML code" }
2953
<p>I have one large view function where a user can Add, Edit, Delete, and Update his education. I am currently doing this all in one view because I haven't yet learned how to split up views by function. Here is what I currently have -- </p> <p>I have a single URL pointing to the view -- </p> <pre><code>url(r'^profile/edit/education/$', 'views.edit_education', name='edit_education') </code></pre> <p>Here is my model/modelform -- </p> <pre><code>class Education(models.Model): school = models.CharField(max_length=100) class_year = models.IntegerField(max_length=4, blank=True, null=True, choices=YEAR) degree = models.CharField(max_length=100, blank=True) user = models.ForeignKey('UserProfile') class EducationForm(ModelForm): class Meta: model = Education exclude = ('user',) </code></pre> <p>Here is my view -- </p> <pre><code>@login_required def edit_education(request, edit=0): """ In the edit profile page, allows a user to edit his education and add multiple school entries. """ profile = request.user.get_profile() education = profile.education_set.order_by('-class_year') # for the template. display all eduation entries # unindented for legibility if request.method == 'POST': if 'Add School' in request.POST.values(): form = EducationForm(data=request.POST, request=request) # passing request to form to do validation based on request.user if form.is_valid(): new_education = form.save(commit=False) new_education.user = profile new_education.save() return redirect('edit_education') if 'Delete' in request.POST.values(): for education_id in [key[7:] for key, value in request.POST.iteritems() if key.startswith('delete')]: Education.objects.get(id=education_id).delete() return redirect('edit_education') if 'Edit' in request.POST.values(): for education_id in [key[5:] for key, value in request.POST.iteritems() if value == 'Edit' and key.startswith('edit')]: edit = 1 school_object = Education.objects.get(id = education_id) form = EducationForm(instance = school_object, request=request) return render_to_response('userprofile/edit_education.html', {'form': form, 'education':education, 'edit': edit, 'education_id': education_id}, context_instance=RequestContext(request)) if 'Cancel' in request.POST.values(): return redirect('edit_education') if 'Save Changes' in request.POST.values(): form = EducationForm(request.POST, request=request, edit=1) if form.is_valid(): Education.objects.get(id=request.POST['education_id']).delete() # is there a way to update instead of delete and re-add? new_education = form.save(commit=False) new_education.user = profile new_education.save() return redirect('edit_education') else: form = EducationForm(request=request) return render_to_response('userprofile/edit_education.html', {'form': form, 'education': education, }, context_instance=RequestContext(request)) </code></pre> <p>And finally, my template -- </p> <pre><code>&lt;h3&gt;Edit education info for {{user.get_full_name}}&lt;/h3&gt; &lt;form action="." method="post"&gt; {% csrf_token %} {% if education %} {% for education in education %} &lt;p&gt;&lt;b&gt;{{ education.school }}&lt;/b&gt; {% if education.class_year %}{{ education.class_year|shorten_year}}, {% endif %} {{ education.degree}} &lt;input type="submit" name="edit_{{education.id}}" value='Edit' /&gt; &lt;input type="submit" name="delete_{{education.id}}" value="Delete" /&gt;&lt;/p&gt; {% endfor %} {% endif %} &lt;table&gt; &lt;input type="hidden" name="education_id" value="{{education_id}}" /&gt; &lt;tr&gt;&lt;td&gt;School:&lt;/td&gt;&lt;td&gt;{{form.school}}{{form.school.errors}}&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Class Year&lt;/td&gt;&lt;td&gt;{{form.class_year}}{{form.class_year.errors}}&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Degree:&lt;/td&gt;&lt;td&gt;{{form.degree}}{{form.degree.errors}}&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;{{form.non_field_errors}}&lt;/tr&gt; &lt;/table&gt; {% if not edit %} &lt;p&gt;&lt;input type="submit" name="add" value="Add School" &gt;&lt;/p&gt; {% else %} &lt;p&gt;&lt;input type="submit" name="save" value="Save Changes" &gt; &lt;input type="submit" name="cancel" value="Cancel" &gt;&lt;/p&gt; {% endif %} &lt;/form&gt; </code></pre> <p>And the end is here. How would I separate one of these actions in the view into separate view functions using separate URLs? One or two examples would be more than enough. Thank you very much for your help.</p>
[]
[ { "body": "<p>Simple way to split it up by block logic (create, edit, remove or else)</p>\n\n<pre><code># app/views.py\ndef create_edit(request, id=None):\n # if id: we should edit instance\n #else: we shoud create new instance\n return ...\n\ndef delete(request, id):\n # remove instance\n return ...\n\n# app/url.py\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('app.views',\n url('^add/$', 'create_edit', name='school-add'),\n url('^(\\d+)/edit/$', 'create_edit', name='school-edit'),\n url('^(\\d+)/delete/$', 'create_edit', name='school-delete'),\n)\n\n# url.py\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('',\n ('^schools/', include('app.urls')),\n)\n</code></pre>\n\n<p>Also I saw you edit method and I think it's wrong.\nyou have to look in <a href=\"https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#the-save-method\" rel=\"nofollow\">Django docs</a></p>\n\n<p>this will be better then removing and adding new object.</p>\n\n<pre><code>inst = Edu.objects.get(id=id)\nform = EduForm(request.POST, intance=inst)\nif form.is_valid():\n form.save()\n</code></pre>\n\n<p><code>Edit</code> and <code>Delete</code> submit buttons you should change to <code>&lt;a href=\"{% url school-edit item.id %}\"&gt;Edit&lt;/a&gt;</code> and <code>&lt;a href=\"{% url school-delete item.id %}\"&gt;Delete&lt;/a&gt;</code> (or handle submit events with jQuery and redirect to correct URL)</p>\n\n<p><code>Cancel</code> button you can change to <code>&lt;a href=\"{% url %}\"&gt;Cancel&lt;/a&gt;</code> and this would be better then you done with <code>redirect()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T11:33:53.117", "Id": "2960", "ParentId": "2957", "Score": "1" } } ]
{ "AcceptedAnswerId": "2960", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T05:11:31.517", "Id": "2957", "Score": "1", "Tags": [ "python", "django" ], "Title": "Separating a view function by action" }
2957
<p>I wanted a good way to move objects back and forth between Lua and C++, and I didn't want to use anything like LuaBind or the other available libraries I could find, so I instead wrote this. It's designed to be similar to the normal Lua API, which has functions like <code>lua_tostring</code> or <code>lua_tonumber</code>, but I wanted to make it 'just work' with whatever type I fed it. Basically for any function that had a variant for different types, I added a templated version of it. e.g. <code>luaW_to&lt;Foo&gt;</code></p> <p><a href="https://bitbucket.org/alexames/luawrapper">https://bitbucket.org/alexames/luawrapper</a></p> <pre><code>// API Summary: // // LuaWrapper is a library designed to help bridge the gab between Lua and // C++. It is designed to be small (a single header file), simple, fast, // and typesafe. It has no external dependencies, and does not need to be // precompiled; the header can simply be dropped into a project and used // immediately. It even supports class inheritance to a certain degree. Objects // can be created in either Lua or C++, and passed back and forth. // // In Lua, the objects are userdata, but through tricky use of metatables, they // can be treated almost identically to tables. // // The main functions of interest are the following: // luaW_is&lt;T&gt; // luaW_to&lt;T&gt; // luaW_check&lt;T&gt; // luaW_push&lt;T&gt; // luaW_register&lt;T&gt; // luaW_hold&lt;T&gt; // luaW_release&lt;T&gt; // luaW_clean&lt;T&gt; // // These functions allow you to manipulate arbitrary classes just like you // would the primitive types (e.g. numbers or strings). When all references // to a userdata removed, the userdata will be deleted. In some cases, this // may not be what you want, such as cases where an object is created in Lua, // then passed to C++ code which owns it from then on. In these cases, you can // call luaW_release, which releases LuaWrapper's hold on the userdata. This // prevents it from being deallocated when all references disappear. When this // is called, you are now responsible for calling luaW_clean manually when you // are done with the object. Conversely, if an object is created in C++, but // would like to pass ownership over to Lua, luaW_hold may be used. // // Additionally, metamethods __ctor and __dtor are provided, and will run when // objects are created or destroyed respectively. Objects can also declare a // list of other tables that they extend, and they will inherit all functions // from that class. // Todo: // Ensure the LuaWrapper table does not collide with other tables // Determine if it is useful to be able to call the destructor on released uds // Add a way to transfer ownership of uds so dtor and cleanup is automatic // Add some sort of serialization #ifndef LUA_WRAPPER_H_ #define LUA_WRAPPER_H_ #include &lt;iostream&gt; extern "C" { #include "lua.h" #include "lauxlib.h" } #define LUAW_BUILDER #define luaW_getregistry(L, s) \ lua_getfield(L, LUA_REGISTRYINDEX, s) #define luaW_setregistry(L, s) \ lua_setfield(L, LUA_REGISTRYINDEX, s) #define LUAW_CTOR_KEY "__ctor" #define LUAW_DTOR_KEY "__dtor" #define LUAW_EXTENDS_KEY "__extends" #define LUAW_STORAGE_KEY "__storage" #define LUAW_COUNT_KEY "__counts" #define LUAW_HOLDS_KEY "__holds" #define LUAW_WRAPPER_KEY "LuaWrapper" #if 0 // For Debugging // Prints the current Lua stack, including the values for some types template &lt;typename T&gt; void luaW_printstack(lua_State* L) { int stack = lua_gettop(L); for (int i = 1; i &lt;= stack; i++) { std::cout &lt;&lt; std::dec &lt;&lt; i &lt;&lt; ": " &lt;&lt; lua_typename(L, lua_type(L, i)); switch(lua_type(L, i)) { case LUA_TBOOLEAN: std::cout &lt;&lt; " " &lt;&lt; lua_toboolean(L, i); break; case LUA_TSTRING: std::cout &lt;&lt; " " &lt;&lt; lua_tostring(L, i); break; case LUA_TNUMBER: std::cout &lt;&lt; " " &lt;&lt; std::dec &lt;&lt; (uintptr_t)lua_tointeger(L, i) &lt;&lt; " (0x" &lt;&lt; std::hex &lt;&lt; lua_tointeger(L, i) &lt;&lt; ")"; break; default: std::cout &lt;&lt; " " &lt;&lt; std::hex &lt;&lt; lua_topointer(L, i); break; } std::cout &lt;&lt; std::endl; } } #define LUAW_TRACE() \ printf("%s:%d:%s\n", __FILE__, __LINE__, __PRETTY_FUNCTION__) #else #define LUAW_TRACE() #endif template &lt;typename T&gt; T* luaW_defaultallocator() { return new T(); } template &lt;typename T&gt; void luaW_defaultdeallocator(T* obj) { delete obj; } // This class is used with luaW_register as an alternative to using the // normal constructor. Sometimes it's just easier to fill in the fields // of a struct than to file in all the arguments in luaW_register, // especially if you just want to set the last one or two. template &lt;typename T&gt; struct LuaWrapperOptions { LuaWrapperOptions( const luaL_reg* table = NULL, const luaL_reg* metatable = NULL, const char** extends = NULL, bool disablenew = false, T* (*allocator)() = luaW_defaultallocator&lt;T&gt;, void (*deallocator)(T*) = luaW_defaultdeallocator&lt;T&gt;) : table(table), metatable(metatable), extends(extends), disablenew(disablenew), allocator(allocator), deallocator(deallocator) { } const luaL_reg* table; const luaL_reg* metatable; const char** extends; bool disablenew; T* (*allocator)(); void (*deallocator)(T*); }; // This class cannot actually to be instantiated. It is used only hold the // table name and other information. template &lt;typename T&gt; class LuaWrapper { public: static const char* classname; static T* (*allocator)(); static void (*deallocator)(T*); private: LuaWrapper(); }; template &lt;typename T&gt; const char* LuaWrapper&lt;T&gt;::classname; template &lt;typename T&gt; T* (*LuaWrapper&lt;T&gt;::allocator)(); template &lt;typename T&gt; void (*LuaWrapper&lt;T&gt;::deallocator)(T*); // [-0, +0, -] // // Analogous to lua_is(boolean|string|*) // // Returns 1 if the value at the given acceptable index is of type T (or if // strict is false, convertable to type T) and 0 otherwise. template &lt;typename T&gt; bool luaW_is(lua_State *L, int index, bool strict = false) { LUAW_TRACE(); bool equal = false; if (lua_touserdata(L, index) &amp;&amp; lua_getmetatable(L, index)) { // ... ud ... udmt luaL_getmetatable(L, LuaWrapper&lt;T&gt;::classname); // ... ud ... udmt Tmt equal = lua_rawequal(L, -1, -2); if (!equal &amp;&amp; !strict) { lua_getfield(L, -2, LUAW_EXTENDS_KEY); // ... ud ... udmt Tmt udmt.__extends for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { // ... ud ... udmt Tmt udmt.__extends k v equal = lua_rawequal(L, -1, -4); if (equal) { lua_pop(L, 2); // ... ud ... udmt Tmt udmt.__extends break; } } lua_pop(L, 1); // ... ud ... udmt Tmt } lua_pop(L, 2); // ... ud ... } return equal; } // [-0, +0, -] // // Analogous to lua_to(boolean|string|*) // // Converts the given acceptable index to a T*. That value must be of type T; // otherwise, returns NULL. template &lt;typename T&gt; T* luaW_to(lua_State* L, int index) { LUAW_TRACE(); T* obj = NULL; if (luaW_is&lt;T&gt;(L, index)) { obj = *(T**)lua_touserdata(L, index); } return obj; } // [-0, +0, -] // // Analogous to luaL_check(boolean|string|*) // // Checks whether the function argument at index is a T and returns this object template &lt;typename T&gt; T* luaW_check(lua_State* L, int index) { LUAW_TRACE(); T* obj = NULL; if (luaW_is&lt;T&gt;(L, index)) { obj = *(T**)lua_touserdata(L, index); } else { luaL_typerror(L, index, LuaWrapper&lt;T&gt;::classname); } return obj; } // [-0, +1, -] // // Analogous to lua_push(boolean|string|*) // // Pushes a userdata of type T onto the stack. If this object already exists in // the Lua environment, it will assign the existing store to it. Otherwise, a // new store will be created for it. template &lt;typename T&gt; void luaW_push(lua_State* L, T* obj) { LUAW_TRACE(); T** ud = (T**)lua_newuserdata(L, sizeof(T*)); // ... obj *ud = obj; luaL_getmetatable(L, LuaWrapper&lt;T&gt;::classname); // ... obj mt lua_setmetatable(L, -2); // ... obj luaW_getregistry(L, LUAW_WRAPPER_KEY); // ... obj LuaWrapper lua_getfield(L, -1, LUAW_COUNT_KEY); // ... obj LuaWrapper LuaWrapper.counts lua_pushlightuserdata(L, obj); // ... obj LuaWrapper LuaWrapper.counts lud lua_gettable(L, -2); // ... obj LuaWrapper LuaWrapper.counts count int count = lua_tointeger(L, -1); lua_pushlightuserdata(L, obj); // ... obj LuaWrapper LuaWrapper.counts count lud lua_pushinteger(L, count+1); // ... obj LuaWrapper LuaWrapper.counts count lud count+1 lua_settable(L, -4); // ... obj LuaWrapper LuaWrapper.counts count lua_pop(L, 3); // ... obj } // Instructs LuaWrapper that it owns the userdata, and can manage its memory. // When all references to the object are removed, Lua is free to garbage // collect it and delete the object. // // Returns true if luaW_hold took hold of the object, and false if it was // already held template &lt;typename T&gt; bool luaW_hold(lua_State* L, T* obj) { LUAW_TRACE(); luaW_getregistry(L, LUAW_WRAPPER_KEY); // ... LuaWrapper lua_getfield(L, -1, LUAW_HOLDS_KEY); // ... LuaWrapper LuaWrapper.holds lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.holds lud lua_rawget(L, -2); // ... LuaWrapper LuaWrapper.holds hold bool held = lua_toboolean(L, -1); // If it's not held, hold it if (!held) { // Apply hold boolean lua_pop(L, 1); // ... LuaWrapper LuaWrapper.holds lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.holds lud lua_pushboolean(L, true); // ... LuaWrapper LuaWrapper.holds lud true lua_rawset(L, -3); // ... LuaWrapper LuaWrapper.holds // Check count, if there's at least one, add a storage table lua_pop(L, 1); // ... LuaWrapper lua_getfield(L, -1, LUAW_COUNT_KEY); // ... LuaWrapper LuaWrapper.counts lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.counts lud lua_rawget(L, -2); // ... LuaWrapper LuaWrapper.counts count if (lua_tointeger(L, -1) &gt; 0) { // Add the storage table if there isn't one already lua_pop(L, 2); lua_getfield(L, -1, LUAW_STORAGE_KEY); // ... LuaWrapper LuaWrapper.storage lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.storage lud lua_rawget(L, -2); // ... LuaWrapper LuaWrapper.storage store if (lua_isnoneornil(L, -1)) { lua_pop(L, 1); // ... LuaWrapper LuaWrapper.storage lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.storage lud lua_newtable(L); // ... LuaWrapper LuaWrapper.storage lud store lua_rawset(L, -3); // ... LuaWrapper LuaWrapper.storage lua_pop(L, 2); // ... } } return true; } lua_pop(L, 3); // ... return false; } // Releases LuaWrapper's hold on an object. This allows the user to remove // all references to an object in Lua and ensure that Lua will not attempt to // garbage collect it. template &lt;typename T&gt; void luaW_release(lua_State* L, T* obj) { LUAW_TRACE(); luaW_getregistry(L, LUAW_WRAPPER_KEY); // ... LuaWrapper lua_getfield(L, -1, LUAW_HOLDS_KEY); // ... LuaWrapper LuaWrapper.holds lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.holds lud lua_pushnil(L); // ... LuaWrapper LuaWrapper.counts lud nil lua_settable(L, -3); // ... LuaWrapper LuaWrapper.counts count lua_pop(L, 1); // ... LuaWrapper } // When luaW_clean is called on an object, values stored on it's Lua store // become no longer accessible. template &lt;typename T&gt; void luaW_clean(lua_State* L, T* obj) { LUAW_TRACE(); lua_getfield(L, -1, LUAW_STORAGE_KEY); // ... LuaWrapper LuaWrapper.storage lua_pushlightuserdata(L, obj); // ... LuaWrapper LuaWrapper.storage lud lua_pushnil(L); // ... LuaWrapper LuaWrapper.storage lud nil lua_settable(L, -3); // ... LuaWrapper LuaWrapper.store lua_pop(L, 2); // ... } // This function is called from Lua, not C++ // // Calls the lua defined constructor ("__ctor") on a userdata. Assumes the // userdata is on top of the stack, and numargs arguments are below it. This // runs the CTOR_KEY function on T's metatable, using the object as the first // argument and whatever else is below it as the rest of the arguments template &lt;typename T&gt; void luaW_constructor(lua_State* L, int numargs) { LUAW_TRACE(); // ... ud lua_getfield(L, -1, LUAW_CTOR_KEY); // ... ud ud.__ctor if (lua_type(L, -1) == LUA_TFUNCTION) { lua_pushvalue(L, -2); // ... ud ud.__ctor ud lua_insert(L, 1); // ud ... ud ud.__ctor lua_insert(L, 2); // ud ud.__ctor ... ud lua_insert(L, 3); // ud ud.__ctor ud ... lua_call(L, numargs+1, 0); // ud } else { lua_pop(L, 1); // ... ud } } // This function is generally called from Lua, not C++ // // Creates an object of type T and calls the constructor on it with the values // on the stack as arguments to it's constructor template &lt;typename T&gt; int luaW_new(lua_State* L) { LUAW_TRACE(); int numargs = lua_gettop(L); T* obj = LuaWrapper&lt;T&gt;::allocator(); luaW_push&lt;T&gt;(L, obj); luaW_hold&lt;T&gt;(L, obj); luaW_constructor&lt;T&gt;(L, numargs); return 1; } #ifdef LUAW_BUILDER // This function is called from Lua, not C++ // // This is an alternative way to construct objects. Instead of using new and a // constructor, you can use a builder instead. A builder is called like this: // // f = Foo.build // { // X = 10; // Y = 20; // } // // This will then create a new Foo object, and then call f:X(10) and f:Y(20) on // that object. The constructor is not called at any point. The keys in this // table are used as function names on the metatable. // // This is sort of experimental, just to see if it ends up being useful. template &lt;typename T&gt; void luaW_builder(lua_State* L) { LUAW_TRACE(); if (lua_type(L, 1) == LUA_TTABLE) { // {} ud for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) { // {} ud k v lua_pushvalue(L, -2); // {} ud k v k lua_gettable(L, -4); // {} ud k v ud[k] lua_pushvalue(L, -4); // {} ud k v ud[k] ud lua_pushvalue(L, -3); // {} ud k v ud[k] ud v lua_call(L, 2, 0); // {} ud k v } // {} ud } } // This function is generally called from Lua, not C++ // // Creates an object of type T and initializes it using its builder to // initialize it template &lt;typename T&gt; int luaW_build(lua_State* L) { LUAW_TRACE(); T* obj = LuaWrapper&lt;T&gt;::allocator(); luaW_push&lt;T&gt;(L, obj); luaW_hold&lt;T&gt;(L, obj); luaW_builder&lt;T&gt;(L); return 1; } #endif // This function is called from Lua, not C++ // // The default metamethod to call when indexing into lua userdata representing // an object of type T. This will fisrt check the userdata's environment table // and if it's not found there it will check the metatable. This is done so // individual userdata can be treated as a table, and can hold thier own // values. template &lt;typename T&gt; int luaW__index(lua_State* L) { LUAW_TRACE(); // obj key T* obj = luaW_to&lt;T&gt;(L, 1); luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj key LuaWrapper lua_getfield(L, -1, LUAW_STORAGE_KEY); // obj key LuaWrapper LuaWrapper.storage lua_pushlightuserdata(L, obj); // obj key LuaWrapper LuaWrapper.table lud lua_rawget(L, -2); // obj key LuaWrapper LuaWrapper.table table if (!lua_isnoneornil(L, -1)) { lua_pushvalue(L, -4); // obj key LuaWrapper LuaWrapper.table table key lua_rawget(L, -2); // obj key LuaWrapper LuaWrapper.table table table[k] if (lua_isnoneornil(L, -1)) { lua_pop(L, 4); // obj key lua_getmetatable(L, -2); // obj key mt lua_pushvalue(L, -2); // obj key mt k lua_rawget(L, -2); // obj key mt mt[k] } } else { lua_pop(L, 3); // obj key lua_getmetatable(L, -2); // obj key mt lua_pushvalue(L, -2); // obj key mt k lua_rawget(L, -2); // obj key mt mt[k] } return 1; } // This function is called from Lua, not C++ // // The default metamethod to call when createing a new index on lua userdata // representing an object of type T. This will index into the the userdata's // environment table that it keeps for personal storage. This is done so // individual userdata can be treated as a table, and can hold thier own // values. template &lt;typename T&gt; int luaW__newindex(lua_State* L) { LUAW_TRACE(); // obj key value T* obj = luaW_to&lt;T&gt;(L, 1); luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj key value LuaWrapper lua_getfield(L, -1, LUAW_STORAGE_KEY); // obj key value LuaWrapper LuaWrapper.storage lua_pushlightuserdata(L, obj); // obj key value LuaWrapper LuaWrapper.storage lud lua_rawget(L, -2); // obj key value LuaWrapper LuaWrapper.storage store if (!lua_isnoneornil(L, -1)) { lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key value lua_rawset(L, -3); // obj key value LuaWrapper LuaWrapper.storage store } return 0; } // This function is called from Lua, not C++ // // The __gc metamethod handles cleaning up userdata. The userdata's reference // count is decremented, and if this is the final reference to the userdata, // the __dtor metamethod is called, its environment table is nil'd and pointer // deleted. template &lt;typename T&gt; int luaW__gc(lua_State* L) { LUAW_TRACE(); // obj T* obj = luaW_to&lt;T&gt;(L, 1); luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj LuaWrapper lua_getfield(L, -1, LUAW_COUNT_KEY); // obj LuaWrapper LuaWrapper.counts lua_pushlightuserdata(L, obj); // obj LuaWrapper LuaWrapper.counts lud lua_gettable(L, -2); // obj LuaWrapper LuaWrapper.counts count int count = lua_tointeger(L, -1); lua_pushlightuserdata(L, obj); // obj LuaWrapper LuaWrapper.counts count lud lua_pushinteger(L, count-1); // obj LuaWrapper LuaWrapper.counts count lud count-1 lua_settable(L, -4); // obj LuaWrapper LuaWrapper.counts count lua_pop(L, 3); // obj LuaWrapper if (obj &amp;&amp; 1 == count) { lua_getfield(L, -1, LUAW_DTOR_KEY); // obj obj.__dtor if (lua_type(L, -1) == LUA_TFUNCTION) { lua_pushvalue(L, -2); // obj obj.__ctor obj lua_call(L, 1, 0); // obj } else { lua_pop(L, 1); // obj } luaW_release&lt;T&gt;(L, obj); luaW_clean&lt;T&gt;(L, obj); delete obj; } return 0; } // Run this to create a table and metatable for your class. You must have a // correctly initialized LuaWrapper&lt;T&gt; for your class in order for this to // properly initilize your class wrapper. This function will also take care of // extending any classes T inherits from by copying the values in the metatable // of the extended class to T's metatable (assuming T's metatable doesn't have // something in that key already). template &lt;typename T&gt; void luaW_register(lua_State* L, const char* classname, const luaL_reg* table, const luaL_reg* metatable, const char** extends = NULL, bool disablenew = false, T* (*allocator)() = luaW_defaultallocator&lt;T&gt;, void (*deallocator)(T*) = luaW_defaultdeallocator&lt;T&gt;) { LUAW_TRACE(); LuaWrapper&lt;T&gt;::classname = classname; LuaWrapper&lt;T&gt;::allocator = allocator; LuaWrapper&lt;T&gt;::deallocator = deallocator; const luaL_reg defaulttable[] = { { "new", luaW_new&lt;T&gt; }, #ifdef LUAW_BUILDER { "build", luaW_build&lt;T&gt; }, #endif { NULL, NULL } }; const luaL_reg defaultmetatable[] = { { "__index", luaW__index&lt;T&gt; }, { "__newindex", luaW__newindex&lt;T&gt; }, { "__gc", luaW__gc&lt;T&gt; }, { NULL, NULL } }; const luaL_reg emptytable[] = { { NULL, NULL } }; table = table ? table : emptytable; metatable = metatable ? metatable : emptytable; // Ensure that the LuaWrapper table is set up luaW_getregistry(L, LUAW_WRAPPER_KEY); // LuaWrapper if (lua_isnil(L, -1)) { lua_newtable(L); // nil {} luaW_setregistry(L, LUAW_WRAPPER_KEY); // nil luaW_getregistry(L, LUAW_WRAPPER_KEY); // nil LuaWrapper lua_newtable(L); // nil LuaWrapper {} lua_setfield(L, -2, LUAW_COUNT_KEY); // nil LuaWrapper lua_newtable(L); // nil LuaWrapper {} lua_setfield(L, -2, LUAW_STORAGE_KEY); // nil LuaWrapper lua_newtable(L); // nil LuaWrapper {} lua_setfield(L, -2, LUAW_HOLDS_KEY); // nil LuaWrapper lua_pop(L, 1); // nil } lua_pop(L, 1); // // Open table if (!disablenew) { luaL_register(L, LuaWrapper&lt;T&gt;::classname, defaulttable); // T luaL_register(L, NULL, table); // T } else { luaL_register(L, LuaWrapper&lt;T&gt;::classname, table); // T } // Open metatable, set up extends table luaL_newmetatable(L, LuaWrapper&lt;T&gt;::classname); // T mt lua_newtable(L); // T mt {} lua_setfield(L, -2, LUAW_EXTENDS_KEY); // T mt luaL_register(L, NULL, defaultmetatable); // T mt luaL_register(L, NULL, metatable); // T mt // Copy key/value pairs from extended metatables for (const char** e = extends; e &amp;&amp; *e; ++e) { luaL_getmetatable(L, *e); // T mt emt if(lua_isnoneornil(L, -1)) { lua_pop(L, 1); // T mt std::cout &lt;&lt; "Error: did not open table " &lt;&lt; *e &lt;&lt; " before " &lt;&lt; LuaWrapper&lt;T&gt;::classname &lt;&lt; std::endl; continue; } lua_getfield(L, -2, LUAW_EXTENDS_KEY); // T mt emt mt.__extends lua_pushvalue(L, -2); // T mt emt mt.__extends emt lua_setfield(L, -2, *e); // T mt emt mt.__extends lua_getfield(L, -2, LUAW_EXTENDS_KEY); // T mt emt mt.__extends emt.__extends for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { // T mt emt mt.__extends emt.__extends k v lua_pushvalue(L, -2); // T mt emt mt.__extends emt.__extends k v k lua_pushvalue(L, -2); // T mt emt mt.__extends emt.__extends k v k lua_rawset(L, -6); // T mt emt mt.__extends emt.__extends k v } lua_pop(L, 2); // T mt emt for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { // T mt emt k v lua_pushvalue(L, -2); // T mt emt k v k lua_gettable(L, -5); // T mt emt k v mt[k] if(lua_isnoneornil(L, -1)) { lua_pop(L, 1); // T mt emt k v lua_pushvalue(L, -2); // T mt emt k v k lua_pushvalue(L, -2); // T mt emt k v k v lua_rawset(L, -6); // T mt emt k v } else { lua_pop(L, 1); // T mt k v } } lua_pop(L, 1); // T mt } lua_setmetatable(L, -2); // T lua_pop(L, 1); // } // Same as above, except sometimes its nice to be able to only have to set the // fields you care about using a struct. template&lt;typename T&gt; void luaW_register(lua_State* L, const char* classname, LuaWrapperOptions&lt;T&gt;&amp; options) { luaW_register(L, classname, options.table, options.metatable, options.extends, options.disablenew, options.allocator, options.deallocator); } #undef luaW_getregistry #undef luaW_setregistry #endif // LUA_WRAPPER_H_ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T19:01:15.247", "Id": "5247", "Score": "0", "body": "Can you elaborate on why this is better than Luabind?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T00:57:25.783", "Id": "5249", "Score": "2", "body": "I don't know if it's better or worse, just different. This aims for simplicity first. LuaBind practically makes up it's own language-within-a-language with it's use of metaprogramming and the [] operator. This is a single header and does not depend on boost or any external library other than iostream (and even that can probably be done away with). It also fits in naturally with the rest of the Lua functions that operate on types so if you know how to use those this is basically the same. I haven't used LuaBind much, but I suspect this requires a little more heavy lifting on your part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T07:54:42.243", "Id": "31050", "Score": "0", "body": "[LuaBridge](https://github.com/vinniefalco/LuaBridge/) doesn't have dependencies and does what you want to do. To print the stack you could also use [this](https://github.com/d-led/luastackcrawler). Both designed for simplicity. In particular, you write \"It is now the programmer's responsibility to run luaW_clean\". This doesn't sound like simplicity and safety of use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T18:54:43.570", "Id": "31073", "Score": "1", "body": "@DmitryLedentsov: This code is over a year old at this point and that requirement has been done away with since then (though I think the documentation might need to be updated to reflect this). LuaBridge looks nice though. Still, I'm happy with LuaWrapper for my projects for the time being." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-05T16:38:59.873", "Id": "175000", "Score": "0", "body": "What is `ud ... udmt Tmt` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T20:22:50.647", "Id": "176160", "Score": "0", "body": "Those are notes to keep track of the stack. ud is userdata, mt is metatable, ... means there could be any number of things on the stack between two things so I have to be careful how I index into it. It's not very formalized, it's just some shorthand notes that make it easy to follow the current stack state." } ]
[ { "body": "<h1><code>#define</code>s</h1>\n\n<p>This is not a good use of <code>#define</code>. This should be a <code>const string</code> instead:</p>\n\n<blockquote>\n<pre><code>#define LUAW_CTOR_KEY \"__ctor\"\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>And this should be a function:</p>\n\n<blockquote>\n<pre><code>#define LUAW_TRACE() \\\n printf(\"%s:%d:%s\\n\", __FILE__, __LINE__, __PRETTY_FUNCTION__)\n</code></pre>\n</blockquote>\n\n<h1>Hardcoded returns:</h1>\n\n<blockquote>\n<pre><code>template &lt;typename T&gt;\nint luaW__newindex(lua_State* L)\n{\n LUAW_TRACE();\n // obj key value\n T* obj = luaW_to&lt;T&gt;(L, 1);\n luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj key value LuaWrapper\n lua_getfield(L, -1, LUAW_STORAGE_KEY); // obj key value LuaWrapper LuaWrapper.storage\n lua_pushlightuserdata(L, obj); // obj key value LuaWrapper LuaWrapper.storage lud\n lua_rawget(L, -2); // obj key value LuaWrapper LuaWrapper.storage store\n if (!lua_isnoneornil(L, -1))\n {\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key value\n lua_rawset(L, -3); // obj key value LuaWrapper LuaWrapper.storage store\n }\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>I'm not sure why you hardcode a <code>0</code> return value there. Is it a default index? Based on it being the only <code>return</code> in the function, it almost looks like a signal of success. If so, this method could possibly return a Boolean or become <code>void</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-14T16:36:05.973", "Id": "177188", "Score": "0", "body": "I'm not sure why this post is suddenly getting so much attention. Regarding LUAW_TRACE(), that can't be a function without requiring the user include the file, line and function as the arguments for every call. The whole point of the macro is the have the line numbers and function magically populated. However, in the current version of the code LUAW_TRACE has been removed anyway. Regarding the hardcoded return value: This is a Lua callback function. It needs to have have the function signature it does, and the return value is how many values off the top of the stack are being returned to Lua." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T18:05:04.397", "Id": "96798", "ParentId": "2958", "Score": "5" } }, { "body": "<p>First thing I would do is standardize indents, from this:</p>\n\n<blockquote>\n<pre><code>void luaW_printstack(lua_State* L)\n{\n int stack = lua_gettop(L);\n for (int i = 1; i &lt;= stack; i++)\n {\n std::cout &lt;&lt; std::dec &lt;&lt; i &lt;&lt; \": \" &lt;&lt; lua_typename(L, lua_type(L, i));\n switch(lua_type(L, i))\n {\n case LUA_TBOOLEAN: std::cout &lt;&lt; \" \" &lt;&lt; lua_toboolean(L, i); break;\n case LUA_TSTRING: std::cout &lt;&lt; \" \" &lt;&lt; lua_tostring(L, i); break;\n case LUA_TNUMBER: std::cout &lt;&lt; \" \" &lt;&lt; std::dec &lt;&lt; (uintptr_t)lua_tointeger(L, i) &lt;&lt; \" (0x\" &lt;&lt; std::hex &lt;&lt; lua_tointeger(L, i) &lt;&lt; \")\"; break;\n default: std::cout &lt;&lt; \" \" &lt;&lt; std::hex &lt;&lt; lua_topointer(L, i); break;\n }\n std::cout &lt;&lt; std::endl;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>To this:</p>\n\n<pre><code>void luaW_printstack(lua_State* L)\n{\n int stack = lua_gettop(L);\n for (int i = 1; i &lt;= stack; i++)\n {\n std::cout &lt;&lt; std::dec &lt;&lt; i &lt;&lt; \": \" &lt;&lt; lua_typename(L, lua_type(L, i));\n switch(lua_type(L, i))\n {\n case LUA_TBOOLEAN: std::cout &lt;&lt; \" \" &lt;&lt; lua_toboolean(L, i); break;\n case LUA_TSTRING: std::cout &lt;&lt; \" \" &lt;&lt; lua_tostring(L, i); break;\n case LUA_TNUMBER: std::cout &lt;&lt; \" \" &lt;&lt; std::dec &lt;&lt; (uintptr_t)lua_tointeger(L, i) &lt;&lt; \" (0x\" &lt;&lt; std::hex &lt;&lt; lua_tointeger(L, i) &lt;&lt; \")\"; break;\n default: std::cout &lt;&lt; \" \" &lt;&lt; std::hex &lt;&lt; lua_topointer(L, i); break;\n }\n std::cout &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>In my opinion this makes it <strong>much</strong> easier to follow. This allows the reader to quickly skim and find the hierarchy of the block they are in much quicker. Generally, when working in languages like the C/C99/C++/C# languages, Python, PHP, Perl, Visual Basic, etc., we assume each line is a statement. (Or no more than a couple.) When many statements are combined on a single line, we start to make mistakes and our assumptions can lead us astray.</p>\n\n<p>Similarly, though less critical, the <code>case</code> statements are generally most readable when broken across lines, though that is up to you.\nI mean like this would be more readable:</p>\n\n<pre><code>switch(lua_type(L, i))\n{\n case LUA_TBOOLEAN:\n std::cout &lt;&lt; \" \" &lt;&lt; lua_toboolean(L, i);\n break;\n case LUA_TSTRING: \n std::cout &lt;&lt; \" \" &lt;&lt; lua_tostring(L, i); \n break;\n case LUA_TNUMBER: \n std::cout &lt;&lt; \" \" &lt;&lt; std::dec &lt;&lt; (uintptr_t)lua_tointeger(L, i) &lt;&lt; \" (0x\" &lt;&lt; std::hex &lt;&lt; lua_tointeger(L, i) &lt;&lt; \")\"; \n break;\n default:\n std::cout &lt;&lt; \" \" &lt;&lt; std::hex &lt;&lt; lua_topointer(L, i);\n break;\n}\n</code></pre>\n\n<p>It allows the reader (and likely programmer) to easily distinguish block-from-block, and thus, each section of code from each other section of code.</p>\n\n<hr>\n\n<p>Pre-processor <code>if</code> statements are very powerful, so when I see something like this:</p>\n\n<blockquote>\n<pre><code>#if 0\n// For Debugging\n// Prints the current Lua stack, including the values for some types\ntemplate &lt;typename T&gt;\n</code></pre>\n</blockquote>\n\n<p>It makes me wonder about the programmers intent? Perhaps, instead, you should define a:</p>\n\n<pre><code>#define LUA_DEBUG\n\n#if LUA_DEBUG\n</code></pre>\n\n<p>Which you can then comment out the <code>#define</code> line to change the effect of it. You could reuse this later, of course, to make things much easier to deal with.\nLater on.</p>\n\n<hr>\n\n<p>These two long lines in this constructor:</p>\n\n<blockquote>\n<pre><code>struct LuaWrapperOptions\n{\n LuaWrapperOptions(\n const luaL_reg* table = NULL, const luaL_reg* metatable = NULL, const char** extends = NULL, bool disablenew = false, T* (*allocator)() = luaW_defaultallocator&lt;T&gt;, void (*deallocator)(T*) = luaW_defaultdeallocator&lt;T&gt;)\n : table(table), metatable(metatable), extends(extends), disablenew(disablenew), allocator(allocator), deallocator(deallocator) { }\n\n const luaL_reg* table;\n const luaL_reg* metatable;\n const char** extends;\n bool disablenew;\n T* (*allocator)();\n void (*deallocator)(T*);\n};\n</code></pre>\n</blockquote>\n\n<p>Are very hard to read, though not on purpose. All those inline default values tend to make it hard to read. (You can't even tell how many there are without going on some deep comma-searching.) Cleaning that up makes it far clearer to follow in the future. Even a small change such as the following helps:</p>\n\n<pre><code>struct LuaWrapperOptions\n{\n LuaWrapperOptions(\n const luaL_reg* table = NULL,\n const luaL_reg* metatable = NULL,\n const char** extends = NULL,\n bool disablenew = false,\n T* (*allocator)() = luaW_defaultallocator&lt;T&gt;,\n void (*deallocator)(T*) = luaW_defaultdeallocator&lt;T&gt;)\n : table(table), metatable(metatable), extends(extends), disablenew(disablenew), allocator(allocator), deallocator(deallocator) { }\n\n const luaL_reg* table;\n const luaL_reg* metatable;\n const char** extends;\n bool disablenew;\n T* (*allocator)();\n void (*deallocator)(T*);\n};\n</code></pre>\n\n<p>This allows the reader to easily tell that there are just a few parameters there. Though, it could be improved <strong>much</strong> more, by breaking things more verbosely, as so:</p>\n\n<pre><code>struct LuaWrapperOptions\n{\n LuaWrapperOptions(\n const luaL_reg* table = NULL,\n const luaL_reg* metatable = NULL,\n const char** extends = NULL,\n bool disablenew = false,\n T* (*allocator)() = luaW_defaultallocator&lt;T&gt;,\n void (*deallocator)(T*) = luaW_defaultdeallocator&lt;T&gt;\n )\n : table(table),\n metatable(metatable),\n extends(extends),\n disablenew(disablenew),\n allocator(allocator),\n deallocator(deallocator)\n { }\n\n const luaL_reg* table;\n const luaL_reg* metatable;\n const char** extends;\n bool disablenew;\n T* (*allocator)();\n void (*deallocator)(T*);\n};\n</code></pre>\n\n<p>Part of the issue with the original line is that with it being extremely long, parts of the code would be hidden even on large screens. Generally, code is easiest to read top-to-bottom, and creating a lot of noise on the side like that disrupts the flow of your eyes. Another issue is that you cannot visibly distinguish bugs on the sides of the code like that, and can often forget about the excess of code that you may be unable to see in the regular viewport.</p>\n\n<hr>\n\n<p>I would also separate the outer-most blocks of code from other code. I.e.:</p>\n\n<blockquote>\n<pre><code>int luaW__newindex(lua_State* L)\n{\n LUAW_TRACE();\n // obj key value\n T* obj = luaW_to&lt;T&gt;(L, 1);\n luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj key value LuaWrapper\n lua_getfield(L, -1, LUAW_STORAGE_KEY); // obj key value LuaWrapper LuaWrapper.storage\n lua_pushlightuserdata(L, obj); // obj key value LuaWrapper LuaWrapper.storage lud\n lua_rawget(L, -2); // obj key value LuaWrapper LuaWrapper.storage store\n if (!lua_isnoneornil(L, -1))\n {\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key value\n lua_rawset(L, -3); // obj key value LuaWrapper LuaWrapper.storage store\n }\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>To:</p>\n\n<pre><code>int luaW__newindex(lua_State* L)\n{\n LUAW_TRACE();\n // obj key value\n T* obj = luaW_to&lt;T&gt;(L, 1);\n luaW_getregistry(L, LUAW_WRAPPER_KEY); // obj key value LuaWrapper\n lua_getfield(L, -1, LUAW_STORAGE_KEY); // obj key value LuaWrapper LuaWrapper.storage\n lua_pushlightuserdata(L, obj); // obj key value LuaWrapper LuaWrapper.storage lud\n lua_rawget(L, -2); // obj key value LuaWrapper LuaWrapper.storage store\n\n if (!lua_isnoneornil(L, -1))\n {\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key\n lua_pushvalue(L, -5); // obj key value LuaWrapper LuaWrapper.storage store key value\n lua_rawset(L, -3); // obj key value LuaWrapper LuaWrapper.storage store\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Again, another personal taste, but it allows you to more easily distinguish blocks from each other. Putting code directly above an <code>if</code>-block like that can give it the impression that it is <em>part of</em> that <code>if</code> block.</p>\n\n<hr>\n\n<p>Another note, as @Hosch250 said, hardcoded returns are generally frowned upon. If you absolutely require them, they should be indicative of a default value, or if they are an error, then an error value.</p>\n\n<p>Your comments seem appropriate, you use them to keep track of things that the code does not necessarily tell you directly. Which is good. Bad comments tend to be those that overly explain the code.</p>\n\n<p>I.e.:</p>\n\n<pre><code>int number = 10; // create an integer\n</code></pre>\n\n<p>Tends to be bad, whereas:</p>\n\n<pre><code>int number = 10; // we have 100 of them, and 10 groups to do it, so each group is 10 objects\n</code></pre>\n\n<p>Is generally a bit better. (Although if the code itself can explain the idea then there are no comments needed.) Your comments tend to be <strong>very</strong> helpful and explanatory. Even the shorthand ones are very helpful, and lead to reasons you do things the way you do.</p>\n\n<p>(Merely examples - results may vary.)</p>\n\n<p>Otherwise, these suggestions should be taken into consideration with the suggestions by @Hosch250. Overall, this is very well-written code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-14T16:41:08.763", "Id": "177190", "Score": "1", "body": "I'm not sure why this 4 year old post is suddenly getting attention :P The code in the repository is much newer than the code posted here. Regarding the function luaW_printstack: that function no longer exists. Nor does the debug code that was hidden in the #if 0. LuaWrapperOptions and its long constructor were also ditched. I disagree about the hardcoded return value: in this case it's necessary. The function is a callback that requires a specific signature where the return value is how many stack elements are to be returned to Lua, and the function mentioned always returns 0 elements to Lua." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-14T17:27:37.113", "Id": "177198", "Score": "1", "body": "@AlexAmes - this post was one of the highest-scoring unanswered questions on the site, and a bounty was offered for to \"clear out\" the unanswered queue. You can thank janos for the attention ;-)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T18:28:55.720", "Id": "96802", "ParentId": "2958", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T05:22:56.163", "Id": "2958", "Score": "27", "Tags": [ "c++", "api", "lua" ], "Title": "C++ API for interfacing with Lua" }
2958
<p>How do I improve this code for reading an epub file? The code is as follow:</p> <pre><code>package org.example.mymenu; import java.awt.print.Book; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; //import java.util.List; //import org.example.mymenu.Book; //import nl.siegmann.epublib.domain.TocReference; //import nl.siegmann.epublib.epub.epubReader; import android.app.Activity; import android.content.res.AssetManager; //import android.graphics.Bitmap; //import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; /** * Log the info of 'assets/books/testbook.epub'. * * @author paul.siegmann * */ public class Eread extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AssetManager assetManager = getAssets(); try { // find InputStream for book InputStream epubInputStream = assetManager .open("/assets/sample.epub"); // Load Book from inputStream Book book = (new Eread()).readEpub(epubInputStream); } catch (IOException e) { Log.e("epublib", e.getMessage()); } } Book readEpub(InputStream epubInputStream) { // TODO Auto-generated method stub Eread epubReader = new Eread(); try { Book book = epubReader.readEpub(new FileInputStream("sample.epub")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T19:59:02.757", "Id": "4542", "Score": "2", "body": "To be honest, I don't know what to review here. There is virtually no notable code there other than the initialization of a Book object. The only thing think I can think of is: handle the exceptions better." } ]
[ { "body": "<ol>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconvtoc-136057.html\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a>, <em>9. Naming Conventions</em>, I'd call the class <code>EpubReader</code>. The name should be a noun, and try to avoid abbreviations which makes the code harder to read.</p></li>\n<li><p>Couldn't the <code>readEpub</code> method be <code>private</code>? Why has it default access?</p></li>\n<li><p>The <code>readEpub</code> does not use the <code>epubInputStream</code> parameter. Why is it read <code>sample.epub</code>? It looks like a test code. Furthermore, this class seems really incomplete. <code>onCreate</code> creates a new <code>Eread</code> instance then calls its <code>readEpub</code> method. The <code>readEpub</code> creates (again!) a new <code>Eread</code> instance (<code>epubReader</code>) then calls its <code>readEpub</code> method. It's an endless loop.</p></li>\n<li><p><code>onCreate</code> is an instance method, so you could call <code>readEpub</code> without creating a new <code>Eread</code> instance:</p>\n\n<pre><code>Book book = readEpub(epubInputStream);\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T08:02:24.933", "Id": "8489", "ParentId": "2966", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T12:57:09.500", "Id": "2966", "Score": "4", "Tags": [ "java", "android" ], "Title": "EPUB reader for Android" }
2966
<p><br/> The following code is mainly concerned with the conversion from byte/bit stream to numericals such as int, unsigned int, short int, unsigned short int, float, and etc. These functions are heavily used in my image data decoding program. I feel an insufferably slow when dealing with bigger image. Would please help me improve my code? Thank you!<br/> <br/></p> <pre><code>const unsigned int POW2[32] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288, 1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912, 1073741824,2147483648 }; // Number of bits per word enum BitCount { BC01=1, BC02=2, BC03=3, BC04=4, BC05=5, BC06=6, BC07=7, BC08=8, BC09=9, BC10=10, BC11=11,BC12=12,BC13=13,BC14=14,BC15=15,BC16=16,BC17=17,BC18=18,BC19=19,BC20=20, BC21=21,BC22=22,BC23=23,BC24=24,BC25=25,BC26=26,BC27=27,BC28=28,BC29=29,BC30=30, BC31=31,BC32=32 }; // Bit position in one byte (8bit) enum BitPosition { BP0=0, BP1=1, BP2=2, BP3=3, BP4=4, BP5=5, BP6=6, BP7=7 }; unsigned int GetNbitsWordBE(unsigned int indexWord, const unsigned char * p, BitCount bitCount) { // Subscript numbering from 0 unsigned int offsetBits = indexWord * bitCount; unsigned int beginByte = offsetBits / 8; BitPosition beginBit = static_cast&lt;BitPosition&gt;(offsetBits % 8); return GetNbitsWordBE(beginByte, beginBit, p, bitCount); } unsigned int GetNbitsWordBE(unsigned int beginByte, BitPosition beginBit, const unsigned char * p, BitCount bitCount) { unsigned int result = 0; const unsigned char * data = p + beginByte; // Branch #1: special case (take up the integral number of bytes) if (beginBit==BP0) { if (bitCount == BC08) return static_cast&lt;unsigned int&gt;(data[0]); else if (bitCount == BC16) return static_cast&lt;unsigned int&gt;(data[1]) + static_cast&lt;unsigned int&gt;(data[0]) * POW2[8]; else if (bitCount == BC24) return static_cast&lt;unsigned int&gt;(data[2]) + static_cast&lt;unsigned int&gt;(data[1]) * POW2[8] + static_cast&lt;unsigned int&gt;(data[0]) * POW2[16]; else if (bitCount == BC32) return static_cast&lt;unsigned int&gt;(data[3]) + static_cast&lt;unsigned int&gt;(data[2]) * POW2[8] + static_cast&lt;unsigned int&gt;(data[1]) * POW2[16] + static_cast&lt;unsigned int&gt;(data[0]) * POW2[24]; else ; // Do nothing } // Compute as big as 32-bit number. // 32-bit number can occupy as much as 5 bytes because it's highly possible // that the first bit is not the first bit of the first byte. unsigned int arRadio[5] = {0,0,0,0,0}; unsigned int arValue[5] = {0,0,0,0,0}; unsigned int occupiedBytesCount = static_cast&lt;unsigned int&gt;( ceil(static_cast&lt;double&gt;(beginBit + bitCount) / 8.0) ); BitPosition beginPos = beginBit; int idxEnd = (beginBit + bitCount) % 8 - 1; if (idxEnd&lt;0) idxEnd=7; BitPosition endPos = static_cast&lt;BitPosition&gt;(idxEnd); switch(occupiedBytesCount) { case 1: // 1st byte result = GetNbitsWordBE(beginPos,endPos,data[0]); break; case 2: // 2nd byte arValue[1] = GetNbitsWordBE(BP0,endPos,data[1]); arRadio[1] = 1; // 1st byte arValue[0] = GetNbitsWordBE(beginPos,BP7,data[0]); arRadio[0] = POW2[endPos+1]; result = arValue[0]*arRadio[0] + arValue[1]*arRadio[1]; break; case 3: // 3rd byte arValue[2] = GetNbitsWordBE(BP0,endPos,data[2]); arRadio[2] = 1; // 2nd byte arValue[1] = data[1]; arRadio[1] = POW2[endPos+1]; // 1st byte arValue[0] = GetNbitsWordBE(beginPos,BP7,data[0]); arRadio[0] = POW2[endPos+1+8]; result = arValue[0]*arRadio[0] + arValue[1]*arRadio[1] + arValue[2]*arRadio[2]; break; case 4: // 4th byte arValue[3] = GetNbitsWordBE(BP0,endPos,data[3]); arRadio[3] = 1; // 3rd byte arValue[2] = data[2]; arRadio[2] = POW2[endPos+1]; // 2nd byte arValue[1] = data[1]; arRadio[1] = POW2[endPos+1+8]; // 1st byte arValue[0] = GetNbitsWordBE(beginPos,BP7,data[0]); arRadio[0] = POW2[endPos+1+8+8]; result = arValue[0]*arRadio[0] + arValue[1]*arRadio[1] + arValue[2]*arRadio[2] + arValue[3]*arRadio[3]; break; case 5: // 5th byte arValue[4] = GetNbitsWordBE(BP0,endPos,data[4]); arRadio[4] = 1; // 4th byte arValue[3] = data[3]; arRadio[3] = POW2[endPos+1]; // 3rd byte arValue[2] = data[2]; arRadio[2] = POW2[endPos+1+8]; // 2nd byte arValue[1] = data[1]; arRadio[1] = POW2[endPos+1+8+8]; // 1st byte arValue[0] = GetNbitsWordBE(beginPos,BP7,data[0]); arRadio[0] = POW2[endPos+1+8+8+8]; result = arValue[0]*arRadio[0] + arValue[1]*arRadio[1] + arValue[2]*arRadio[2] + arValue[3]*arRadio[3] + arValue[4]*arRadio[4]; break; default: break; } return result; } unsigned char GetNbitsWordBE(BitPosition beginPosition, BitPosition endPosition, const unsigned char &amp; data) { if (beginPosition==BP0 &amp;&amp; endPosition==BP7) return data; unsigned char result,ucTmp0,ucTmp1; ucTmp0 = data; ucTmp1 = static_cast&lt;unsigned char&gt;(ucTmp0&lt;&lt;beginPosition); result = static_cast&lt;unsigned char&gt;(ucTmp1&gt;&gt;(beginPosition+(7-endPosition))); return result; } </code></pre> <p>Dear Victor T<br/> Thank you for having taken time to do benchmarking job for my code. I use last-given functions in a function of my program. I post the consumer function as you requested for your reference as follows. <br/></p> <pre><code>#define IR_5KM_SCANLINE_PIXELS 2291 #define VIS_1KM_SCANLINE_PIXELS 9164 #define SVS_IR_SCANLINE_SIZE 4582 #define SVS_VIS_SCANLINE_SIZE 9164 #define SVS_SCANLINE_SIZE 57301 #define SVS_IR1_INDEX 2297 #define SVS_IR2_INDEX 4592 #define SVS_IR3_INDEX 6887 #define SVS_IR4_INDEX 9182 #define SVS_VIS1_INDEX 13766 #define SVS_VIS2_INDEX 22932 #define SVS_VIS3_INDEX 32098 #define SVS_VIS4_INDEX 41264 #define CSV_LINE_NO_SIZE 2 #define CSV_QC_ID_SIZE 1 #define CSV_DOC_ID_SIZE 2 #define CSV_DOC_SIZE 2291 #define CSV_IR_ID_SIZE 2 #define CSV_IR_SCANLINE_SIZE 2864 #define CSV_SIZE_VS_ID 2 #define CSV_VIS_SCANLINE_SIZE 6873 #define CSV_SCANLINE_SIZE 41260 #define CSV_DOC_INDEX 5 #define CSV_IR1_INDEX 2298 #define CSV_IR2_INDEX 5164 #define CSV_IR3_INDEX 8030 #define CSV_IR4_INDEX 10896 #define CSV_VIS1_INDEX 13762 #define CSV_VIS2_INDEX 20637 #define CSV_VIS3_INDEX 27512 #define CSV_VIS4_INDEX 34387 void ReadFileCSV(const char * strFile) { m_pHeaderInfo = new CFileHeader(); // Data buffers unsigned char* pSVSLine = new unsigned char [SVS_SCANLINE_SIZE]; unsigned char* pCSVLine = new unsigned char [CSV_SCANLINE_SIZE]; // Line counter unsigned short lineCount; FILE * fp = fopen(strFile, "rb"); if (fp == NULL) return; fseek(fp, 0, SEEK_END); long pos = ftell(fp); // Subtract the header info line (1 line) lineCount = static_cast&lt;unsigned short&gt;(pos / CSV_SCANLINE_SIZE) - 1; fseek(fp, 0, SEEK_SET); // Read the header info line fread(&amp;m_pHeaderInfo-&gt;header, sizeof(CFileHeader::HEADER_INFO), 1, fp); char cArTmp0[128]; strncpy(cArTmp0, m_pHeaderInfo-&gt;header.strRecordNum, 4); cArTmp0[4] = 0; int iTmp0; sscanf(cArTmp0, "%d", &amp;iTmp0); if (iTmp0 &lt; lineCount) lineCount = static_cast&lt;unsigned short&gt;(iTmp0); // Create 2D unsigned char array m_rawDoc.Create(lineCount, SVS_DOC_SIZE); // Create four 2D unsigned short arrays m_usIR1DataBuffer.Create(lineCount , IR_5KM_SCANLINE_PIXELS); m_usIR2DataBuffer.Create(lineCount , IR_5KM_SCANLINE_PIXELS); m_usIR3DataBuffer.Create(lineCount , IR_5KM_SCANLINE_PIXELS); m_usIR4DataBuffer.Create(lineCount , IR_5KM_SCANLINE_PIXELS); // Create a 2D unsigned char array m_ucVISDataBuffer.Create(lineCount * 4, VIS_1KM_SCANLINE_PIXELS); // Start to reading image data line for (unsigned int y = 0; y &lt; lineCount; y++) { fread(pCSVLine, 1, CSV_SCANLINE_SIZE, fp); memcpy(pSVSLine, pCSVLine + CSV_LINE_NO_SIZE + CSV_QC_ID_SIZE, CSV_DOC_ID_SIZE + CSV_DOC_SIZE); unsigned short *pUS1, *pUS2, *pUS3, *pUS4; pUS1 = reinterpret_cast&lt;unsigned short *&gt;(pSVSLine + SVS_IR1_INDEX); pUS2 = reinterpret_cast&lt;unsigned short *&gt;(pSVSLine + SVS_IR2_INDEX); pUS3 = reinterpret_cast&lt;unsigned short *&gt;(pSVSLine + SVS_IR3_INDEX); pUS4 = reinterpret_cast&lt;unsigned short *&gt;(pSVSLine + SVS_IR4_INDEX); for (int x = 0; x &lt; IR_5KM_SCANLINE_PIXELS; x++) { pUS1[x] = static_cast&lt;short&gt;(GetNbitsWordBE(x, pCSVLine + CSV_IR1_INDEX, BC10)); pUS2[x] = static_cast&lt;short&gt;(GetNbitsWordBE(x, pCSVLine + CSV_IR2_INDEX, BC10)); pUS3[x] = static_cast&lt;short&gt;(GetNbitsWordBE(x, pCSVLine + CSV_IR3_INDEX, BC10)); pUS4[x] = static_cast&lt;short&gt;(GetNbitsWordBE(x, pCSVLine + CSV_IR4_INDEX, BC10)); } unsigned char *pUC1, *pUC2, *pUC3, *pUC4; pUC1 = pSVSLine + SVS_VIS1_INDEX; pUC2 = pSVSLine + SVS_VIS2_INDEX; pUC3 = pSVSLine + SVS_VIS3_INDEX; pUC4 = pSVSLine + SVS_VIS4_INDEX; for (int x = 0; x &lt; VIS_1KM_SCANLINE_PIXELS; x++) { pUC1[x] = static_cast&lt;unsigned char&gt;(GetNbitsWordBE(x, pCSVLine + CSV_VIS1_INDEX, BC06)); pUC2[x] = static_cast&lt;unsigned char&gt;(GetNbitsWordBE(x, pCSVLine + CSV_VIS2_INDEX, BC06)); pUC3[x] = static_cast&lt;unsigned char&gt;(GetNbitsWordBE(x, pCSVLine + CSV_VIS3_INDEX, BC06)); pUC4[x] = static_cast&lt;unsigned char&gt;(GetNbitsWordBE(x, pCSVLine + CSV_VIS4_INDEX, BC06)); } memcpy(m_rawDoc.Ptr(y,0), pSVSLine + SVS_DOC_INDEX, SVS_DOC_SIZE); memcpy(m_usIR1DataBuffer.Ptr(y,0), pSVSLine + SVS_IR1_INDEX, SVS_IR_SCANLINE_SIZE); memcpy(m_usIR2DataBuffer.Ptr(y,0), pSVSLine + SVS_IR2_INDEX, SVS_IR_SCANLINE_SIZE); memcpy(m_usIR3DataBuffer.Ptr(y,0), pSVSLine + SVS_IR3_INDEX, SVS_IR_SCANLINE_SIZE); memcpy(m_usIR4DataBuffer.Ptr(y,0), pSVSLine + SVS_IR4_INDEX, SVS_IR_SCANLINE_SIZE); memcpy(m_ucVISDataBuffer.Ptr(4*y+0,0), pSVSLine + SVS_VIS1_INDEX, SVS_VIS_SCANLINE_SIZE); memcpy(m_ucVISDataBuffer.Ptr(4*y+1,0), pSVSLine + SVS_VIS2_INDEX, SVS_VIS_SCANLINE_SIZE); memcpy(m_ucVISDataBuffer.Ptr(4*y+2,0), pSVSLine + SVS_VIS3_INDEX, SVS_VIS_SCANLINE_SIZE); memcpy(m_ucVISDataBuffer.Ptr(4*y+3,0), pSVSLine + SVS_VIS4_INDEX, SVS_VIS_SCANLINE_SIZE); } fclose(fp); } </code></pre> <p>Dear Mr. Martin,<br/> Thank you for having taken time to read my code snippets. Please let me try to answer your questions to my code:<br/> (1) Background explanation behind coding<br/> The remotely sensed raw data image (for example satellite image) captured by the ground station are always packed in the form of 6-bit, 10-bit, or 12-bit streams. These data are stored scanline by scanline.<br/> <br/> As you see from my attached code, ReadFileCSV is used to read this kind of scanline one by one form an opend binary file, and stored to an unsigned char source buffer for a while. For 6-bit stream, I must scale up to 8-bit (one byte), and for 10-bit or 12-bit stream, I will make them to be scaled unsigned short integer. Finally, I should get an unsigned char (for 6-bit) or unsigned short destination buffer.<br/> <br/> (2) POW2 is the 2 raised to the power of n, where n can be set to any value from 0 to 32. </p> <pre><code> const unsigned int POW2[32] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288, 1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912, 1073741824,2147483648 };</code></pre> <p><br/> As you may see, const unsigned int POW2[32] is just like a look-up table.<br/> <br/> (3) I agree with your suggestion "avoid multiplying instead of shifting". <br/> <br/> (4) I worry about the performance of three overloading functions (GetNbitsWordBE(....)) too. I'm not good at bit operations (for example, shifting, |, ^, ~, and etc.). I think bit-big-player would not use such a complicated and clumsy method to convert PC unfavorable bits such as 6-bit, 10-bit, 12-bit, to its nearest favorable bits such as 8-bit (unsigned char), 16-bit (unsigned short).<br/> <br/> (5) Mr. Mark on SO suggest that I should use the following code snippets to scale my 6-bit and 10-bit values to their respective 8-bit (unsigned char) and 16-bit (unsigned short) values. As I cited here (BTW, I can't make it work): <br/> <br/> The usual way is to left shift by the difference in the number of bits between the input and the output, then add in the high order bits from the input to fill out the lower bits. <br/></p> <pre><code> unsigned char eightbit = (sixbit > 4); unsigned short sixteenbit = (tenbit > 4); unsigned short sixteenbit = (twelvebit > 8); </code></pre> <p>There's an alternate approach for the lower bits that I haven't seen very often - fill them with noise. This masks some of the quantization error in the original sample.</p> <pre><code> unsigned char eightbit = (sixbit > 14); unsigned short sixteenbit = (tenbit > 10); unsigned short sixteenbit = (twelvebit > 12); </code></pre> <p>(6) 10-bit stream illustartion<br/></p> <pre><code>10101010 01110101 00011001 | | ----------- 10-bit 10101010 01110101 00011001 | | ----------- 10-bit 10101010 01110101 01100110 | | ------------ 10-bit </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T05:43:14.753", "Id": "4548", "Score": "0", "body": "@Lee How does the rest of your program use these functions? Have you profiled your application and the measurements point to these functions to be the bottleneck? I ask because I benched your above code with 10million+ iterations and it seems fast enough. Everything completed < 1 second -- even faster if it was a power of two." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T11:26:43.840", "Id": "4551", "Score": "0", "body": "Your formatting is broken on the second code sample, the `#define` lines are being interpreted as headings. Probably you need more indentation." } ]
[ { "body": "<p>Sorry if I'm misunderstanding the code, but here are some ideas of how it can be improved, focusing on performance. Those are the things that immediately came to my mind. I've probably missed things, and there may be higher level optimizations that can be done that I didn't see because I just took a quick look at the code.</p>\n\n<p>What's the point of the POW2 array? It doesn't make the code any clearer than using the shift operator, and may make it harder for the compiler to find optimizations.</p>\n\n<p>So instead of doing</p>\n\n<pre><code>something * POW2[16]\n</code></pre>\n\n<p>just do</p>\n\n<pre><code>something &lt;&lt; 16\n</code></pre>\n\n<p>In general, avoid multiplying instead of shifting if you're working on the bit level anyway. Take for example case 4 which can be written simpler (and likely faster depending on how clever the compiler is) as:</p>\n\n<pre><code>case 4:\n // 4th byte\n arValue3 = GetNbitsWordBE(BP0, endPos, data[3]);\n arValue2 = data[2];\n arValue1 = data[1];\n arValue0 = GetNbitsWordBE(beginPos, BP7, data[0]);\n result = (arValue3) |\n (arValue2 &lt;&lt; (endPos + 1)) |\n (arValue1 &lt;&lt; (endPos + 1 + 8)) |\n (arValue0 &lt;&lt; (endPos + 1 + 8 + 8);\n</code></pre>\n\n<p>I've made arValue into local variables instead of an array because it's easier to type. There may be a performance difference in some direction that you may want to profile.</p>\n\n<p>I'd also worry about whether the GetNbitsWordBE function is inlined and optimized as well as you'd want it to. Oh, wait, there are three of it! Now I'm confused. I'd prefer not overloading it like that, but that's a style issue, not a performance problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T22:59:25.287", "Id": "2999", "ParentId": "2969", "Score": "5" } }, { "body": "<p>You're just trying to convert a lot of packed 10 bit integers into the typical C types?</p>\n\n<p>Have you considered an approach like \"round to the nearest 32-bit quantity, dereference that, and strip out the 'extra' bits\"? Something like this:</p>\n\n<pre><code>uint16_t\nget_packed_word(void *buf, int starting_bit, int nbits)\n{\n uint32_t r;\n\n /* Copy 32 bits... (Via memcpy since otherwise we'd do unaligned access.) */\n memcpy(&amp;r, ((char*)buf) + starting_bit/8, sizeof(r));\n\n /* Using htonl because I assume you want big endian... */\n r = htonl(r);\n\n /* Shift right to discard extra low bits... */\n r &gt;&gt;= ((32 - nbits) - (starting_bit % 8));\n\n /* Discard extra high bits... */\n r &amp;= ((1&lt;&lt;nbits) - 1);\n\n return r;\n}\n</code></pre>\n\n<p>This seems to work for your ASCII art test data with <code>nbits = 10</code>... No idea how it performs with large quantities of data [though bit shifting and AND is cheap, right?], but it's a lot simpler than what you have. I got this approach from the way some FAT drivers handle FAT12 (treat it like FAT16 with 16-bit dereferences, but truncate the extra fuzz).</p>\n\n<p><b>Update:</b> Looking at this again, my original code didn't handle some edge cases, such as <code>starting_bit = 7</code>... So I switched to 32-bit quantities rather than 16.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-19T05:11:29.967", "Id": "3006", "ParentId": "2969", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T16:57:54.140", "Id": "2969", "Score": "6", "Tags": [ "c++", "optimization" ], "Title": "Bit-twiddling for a custom image format" }
2969
<p>I'm trying to emulate the default behavior of an ItemsControl in a ContentControl--Bind Content to an <code>object</code> property and use the correct DataTemplate based on that object's type.</p> <p>I've tried to <strike>Reflector</strike> dotPeek at the implementation of the ItemsControl to see how it works, but I've reached a dead end. Consequently, I've come up with this custom DataTemplateSelector. Here's the code, after which I'll describe why it sucks.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows; using System.Windows.Markup; namespace TemplateSelectorAndInheritance { /// &lt;summary&gt; /// A &lt;see cref="DataTemplateSelector"/&gt; that finds &lt;see cref="DataTemplate"&gt; /// DataTemplates&lt;/see&gt; by the bound object's &lt;see cref="Type"/&gt;. /// &lt;/summary&gt; /// &lt;remarks&gt;This selector supports keys defined by both the /// &lt;see cref="TypeExtension"/&gt; and the type name specified by namespace /// (xmlns).&lt;/remarks&gt; public sealed class TypeBasedDataTemplateSelector : DataTemplateSelector { /// &lt;summary&gt; /// When overridden in a derived class, returns a /// &lt;see cref="T:System.Windows.DataTemplate"/&gt; based on custom logic. /// &lt;/summary&gt; /// &lt;param name="item"&gt;The data object for which to select the template.&lt;/param&gt; /// &lt;param name="container"&gt;The data-bound object.&lt;/param&gt; /// &lt;returns&gt; /// Returns a &lt;see cref="T:System.Windows.DataTemplate"/&gt; or null. The default /// value is null.&lt;/returns&gt; public override DataTemplate SelectTemplate( object item, DependencyObject container) { if (item == null) return null; if (container == null) throw new ArgumentNullException("container"); return FindFirstDataTemplate( item.GetType(), container as FrameworkElement); } /// &lt;summary&gt; /// Recursively searches up the visual tree searching for an applicable template. /// &lt;/summary&gt; /// &lt;param name="type"&gt;The &lt;see cref="Type"/&gt; of the template&lt;/param&gt; /// &lt;param name="frameworkElement"&gt;&lt;see cref="FrameworkElement"/&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;see cref="DataTemplate"/&gt; if found, &lt;c&gt;null&lt;/c&gt; otherwise.&lt;/returns&gt; private DataTemplate FindFirstDataTemplate( Type type, FrameworkElement frameworkElement) { if (frameworkElement == null) return null; var key = frameworkElement.Resources.Keys.OfType&lt;DataTemplateKey&gt;() .FirstOrDefault(x =&gt; { // there be hacks here var targetType = x.DataType as Type; var targetTypeName = x.DataType as string; // this one is very bad, since it doesn't take into account namespaces if (targetTypeName != null &amp;&amp; targetTypeName.EndsWith(type.Name)) return true; if (targetType != null &amp;&amp; targetType == type) return true; return false; }); if (key != null) return frameworkElement.Resources[key] as DataTemplate; // here's another hack--I'm picking the TP first, but I'm not sure // if this is best all the time? var parent = frameworkElement.TemplatedParent as FrameworkElement ?? frameworkElement.Parent as FrameworkElement; return FindFirstDataTemplate(type, parent); } } } </code></pre> <p>This works, but is very fragile and kludgy. I'm hoping to get help on the following points:</p> <p><strong>First:</strong> If you don't use the <code>{x:Type}</code> markup extension, this selector may fail. I can't figure out, within the limited context of the SelectTemplate method, how to find the defined namespaces. For example, if you were to do the following</p> <pre><code>&lt;DataTemplate xmlns:t="clr-namespace:Fubar" DataType="t:Derp" </code></pre> <p>then the DataTemplateKey's value is a string: "t:Derp". I can't figure out how to find out what namespace that <code>t:</code> represents within the context of the <code>SelectTemplate</code> method.</p> <p><strong>Second:</strong> My method of searching up the physical/logical tree looking for resources <em>sucks</em> and makes me unhappy. There has <strong>got</strong> to be a better way to search for resources! </p> <p><strong>Third:</strong> As I search up my parents, I've almost arbitrarily decided that I'll select a <code>TemplatedParent</code> before a <code>Parent</code>, but I'm not even sure that's the best thing to do.</p> <p>Whadyathink?</p>
[]
[ { "body": "<p>I think first of all you should get rid of looking for dataTemplates by type name. Then instead of your method you will be able to use <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findresource.aspx\" rel=\"nofollow\">FindResource method</a>:</p>\n\n<pre><code>var resourceKey = new DataTemplateKey { DataType = type };\nvar dataTemplate = (DataTemplate)frameworkElement.FindResource(resourceKey);\n</code></pre>\n\n<p>Regarding your second question: I think it doesn't matter which one you will take first, as far as I remember they are mutually exclusive. Also <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.parent.aspx\" rel=\"nofollow\">MSDN says</a>:</p>\n\n<blockquote>\n <p>For templates, the Parent of the template eventually will be null. To get past this point and extend into the logical tree where the template is actually applied, use TemplatedParent</p>\n</blockquote>\n\n<p>So taking this statement into account I would take <code>Parent ?? TemplatedParent</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T13:56:34.420", "Id": "4552", "Score": "0", "body": "Well, the first suggestion is pointless, seeing as that's what I'm trying to do, and what you suggest would only add levels of complexity to my application. But thanks for part 2, as that answers one of my concerns." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T16:55:46.953", "Id": "5154", "Score": "0", "body": "Crap, I feel like a jerk now. I read too much into your suggestion *get rid of looking for DataTemplates by type name*, and discounted your alternative suggestion. Now, that works pretty good... in fact, much better than my current code in some respects, so this is worth accepting as the best solution. I would still like to support text keys, but for now..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T12:00:42.527", "Id": "2980", "ParentId": "2970", "Score": "2" } } ]
{ "AcceptedAnswerId": "2980", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-15T17:20:35.540", "Id": "2970", "Score": "5", "Tags": [ "c#", ".net", "wpf" ], "Title": "Trying to un-hack this DataTemplateSelector" }
2970
<p>There is Three Validation Group A,B and No Group.</p> <p>How to get validation result of only the specific validation group.</p> <p>If Group A and No Group is not valid but all of group B is valid, i would like to get result as valid.</p> <p>I have read the article validation in depth but don't find the straightforward solution. <a href="http://msdn.microsoft.com/en-us/library/aa479045.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa479045.aspx</a> </p> <p>Is there any simpler solution than this</p> <pre><code> protected bool IsGroupB_Valid() { var validators = Page.GetValidators("B"); foreach (IValidator item in validators) { if(item.IsValid == false) return false; } return true; } </code></pre>
[]
[ { "body": "<p>Linq will make it look better:</p>\n\n<pre><code>protected bool IsGroupB_Valid()\n{\n return Page.GetValidators(\"B\").All(v =&gt; v.IsValid);\n}\n</code></pre>\n\n<p>But probably you should look for something really different</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T11:48:25.473", "Id": "2979", "ParentId": "2976", "Score": "4" } } ]
{ "AcceptedAnswerId": "2979", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T07:26:44.573", "Id": "2976", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "Get Validation result by group" }
2976
<pre><code>&lt;div class="minipassbox" style="margin-top: 5px;"&gt; &lt;?php for($i = 1; $i &lt;= 3; $i++) { $marginRight = ($i &lt; 3 ? "margin-right:4px" : ""); echo "&lt;div style='width:56px;float:left;{$marginRight}'&gt;"; echo "&lt;label for='param_kind{$i}' style='padding-left:4px;'&gt;{$i}. Kind&lt;/label&gt;"; echo "&lt;select id='param_kind{$i}' class='selFields' name='param_kind{$i}' style='margin-top:3px'&gt;"; echo "&lt;option selected='' value='-1'&gt;--- &lt;/option&gt;"; for($j = 1; $j &lt;= 16; $j++) { $selected = ($oRecherche-&gt;getParamValue("param_kind{$i}") == $j ? "selected='selected'" : ""); $option_text = ($j == 1 ? "&amp;lt; 2 Jah." : $j + "Jahre"); echo "&lt;option value='{$j}' {$selected}&gt;{$option_text}&lt;/option&gt;"; } echo "&lt;/select&gt;"; echo "&lt;/div&gt;"; } ?&gt; &lt;div style="clear:left"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T10:55:04.673", "Id": "4550", "Score": "0", "body": "Well, it's a loop. Any specific question? Beside, why don't you hard-code it if there isn't any dynamic in it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T17:36:50.527", "Id": "5358", "Score": "0", "body": "Seperate your html from your login as much as possible!" } ]
[ { "body": "<p>Two advices:</p>\n\n<ol>\n<li><p><strong>Use <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">PHP alternative syntax</a></strong></p>\n\n<p>When mixing HTML and PHP, it is a good practice to use <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">PHP alternative syntax</a>:</p>\n\n<pre><code>&lt;?php for ($i = 1; $i &lt;= 3; $i++): ?&gt;\n..\n&lt;?php endfor ?&gt;\n</code></pre></li>\n<li><p><strong>Improve the HTML code</strong></p>\n\n<ul>\n<li>Use double quotes in tag attributes (HTML standard)</li>\n<li>Try to respect indentation</li>\n<li>Move style to css declarations</li>\n</ul></li>\n</ol>\n\n<p>Final code proposition:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\n .minipassbox {\n margin-top: 5px;\n }\n .minipassbox &gt; div {\n width: 56px;\n float: left;\n }\n .minipassbox &gt; div.lt3 {\n margin-right: 4px;\n }\n .minipassbox label {\n padding-left: 4px;\n }\n .selFields {\n margin-top: 3px;\n }\n .boxclear {\n clear: left;\n }\n&lt;/style&gt;\n&lt;div class=\"minipassbox\"&gt;\n&lt;?php for ($i = 1; $i &lt;= 3; $i++): ?&gt;\n &lt;div &lt;?php echo $i &lt; 3 ? ' class=\"lt3\"' : '' ?&gt;\n &lt;label for=\"param_kind&lt;?php echo $i ?&gt;\"&gt;&lt;?php echo $i ?&gt;. Kind&lt;/label&gt;\n &lt;select id=\"param_kind&lt;?php echo $i ?&gt;\" class=\"selFields\" name=\"param_kind&lt;?php echo $i ?&gt;\"&gt;\n &lt;option value=\"-1\"&gt;--- &lt;/option&gt;\n &lt;?php for ($j = 1; $j &lt;= 16; $j++): ?&gt;\n &lt;option value=\"\"&lt;?php echo $j ?&gt;\"&lt;?php echo $oRecherche-&gt;getParamValue(\"param_kind$i\") == $j ? ' selected=\"selected\"' : '' ?&gt;&gt;&lt;?php echo $j == 1 ? \"&amp;lt; 2 Jah.\" : $j + \"Jahre\" ?&gt;&lt;/option&gt;\n &lt;?php endfor ?&gt;\n &lt;/select&gt;\n &lt;/div&gt;\n&lt;?php endfor ?&gt;\n &lt;div class=\"boxclear\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T13:51:57.863", "Id": "2981", "ParentId": "2977", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T10:08:26.067", "Id": "2977", "Score": "0", "Tags": [ "php" ], "Title": "PHP mini-password-box: Too many loops" }
2977
<p>Following is the code which finds the social network of a friend (i.e. friends of friends and so on). Friends definition is, ff W1 is friend of W2, then there should be Levenshtein distance equal to 1. It is working fine with a smaller dictionary, but is taking a lot of time with a bigger dictionary.</p> <p>Need some code review and advice.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;queue&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;set&gt; class BkTree { public: BkTree(); ~BkTree(); void insert(std::string m_item); void get_friends(std::string center, std::deque&lt;std::string&gt;&amp; friends); private: size_t EditDistance( const std::string &amp;s, const std::string &amp;t ); struct Node { std::string m_item; size_t m_distToParent; Node *m_firstChild; Node *m_nextSibling; Node(std::string x, size_t dist); bool visited; ~Node(); }; Node *m_root; int m_size; protected: }; BkTree::BkTree() { m_root = NULL; m_size = 0; } BkTree::~BkTree() { if( m_root ) delete m_root; } BkTree::Node::Node(std::string x, size_t dist) { m_item = x; m_distToParent = dist; m_firstChild = m_nextSibling = NULL; visited = false; } BkTree::Node::~Node() { if( m_firstChild ) delete m_firstChild; if( m_nextSibling ) delete m_nextSibling; } void BkTree::insert(std::string m_item) { if( !m_root ){ m_size = 1; m_root = new Node(m_item, -1); return; } Node *t = m_root; while( true ) { size_t d = EditDistance( t-&gt;m_item, m_item ); if( !d ) return; Node *ch = t-&gt;m_firstChild; while( ch ) { if( ch-&gt;m_distToParent == d ) { t = ch; break; } ch = ch-&gt;m_nextSibling; } if( !ch ) { Node *newChild = new Node(m_item, d); newChild-&gt;m_nextSibling = t-&gt;m_firstChild; t-&gt;m_firstChild = newChild; m_size++; break; } } } size_t BkTree::EditDistance( const std::string &amp;left, const std::string &amp;right ) { size_t asize = left.size(); size_t bsize = right.size(); std::vector&lt;size_t&gt; prevrow(bsize+1); std::vector&lt;size_t&gt; thisrow(bsize+1); for(size_t i = 0; i &lt;= bsize; i++) prevrow[i] = i; for(size_t i = 1; i &lt;= asize; i ++) { thisrow[0] = i; for(size_t j = 1; j &lt;= bsize; j++) { thisrow[j] = std::min(prevrow[j-1] + size_t(left[i-1] != right[j-1]), 1 + std::min(prevrow[j],thisrow[j-1]) ); } std::swap(thisrow,prevrow); } return prevrow[bsize]; } void BkTree::get_friends(std::string center, std::deque&lt;std::string&gt;&amp; flv) { if( !m_root ) return ; std::queue&lt; Node* &gt; q; q.push( m_root ); while( !q.empty() ) { Node *t = q.front(); q.pop(); if ( !t ) continue; size_t d = EditDistance( t-&gt;m_item, center ); if( d == 1 ) { if ( t-&gt;visited == false ) { flv.push_back(t-&gt;m_item); t-&gt;visited = true; } } Node *ch = t-&gt;m_firstChild; q.push(ch); while( ch ) { if( ch-&gt;m_distToParent &gt;= 1 ) q.push(ch); ch = ch-&gt;m_nextSibling; } } return; } int main( int argc, char **argv ) { BkTree *pDictionary = new BkTree(); std::ifstream dictFile("word.list"); std::string line; if (dictFile.is_open()) { while (! dictFile.eof() ) { std::getline (dictFile,line); if ( line.size()) { pDictionary-&gt;insert(line); } } dictFile.close(); } std::deque&lt;std::string&gt; flq; pDictionary-&gt;get_friends("aa", flq); int counter = 0; while ( !flq.empty()) { counter++; std::string nf = flq.front(); flq.pop_front(); pDictionary-&gt;get_friends(nf, flq); } std::cout &lt;&lt; counter &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>My first thought is that you may want to profile the code and see where most of the time is being spent.</p>\n\n<p>My second thought comes from examining the code. You are doing a lot of <code>xxx[i]</code> or similar inside loops where <code>i</code> is simply being incremented. To me, that suggests using an iterator (<code>std::vector&lt;size_t&gt;::iterator</code>). <code>xxx[i]</code> often can result in more calculations than the simple incrementing of an iterator.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T17:44:06.513", "Id": "2983", "ParentId": "2978", "Score": "1" } }, { "body": "<p>Here are a few tips:</p>\n\n<p>The loop to read from the file is better written as:</p>\n\n<pre><code>{\n std::ifstream dictFile(\"word.list\");\n std::string line; \n while (std::getline (dictFile,line)) \n { \n if (line.size())\n pDictionary-&gt;insert(line);\n }\n}\n</code></pre>\n\n<p>Next, most of your methods take <code>std::string</code> by value - which could be expensive depending on your compiler - you may be better off passing a const reference instead (you seem to mix and match).</p>\n\n<p>Next, in your <code>Node</code> constructor, consider using a member intialization list to set the members rather than in the body of the constructor. Why is this relevant, in your approach, the member is constructed and then later assigned to.</p>\n\n<p>The above may make a difference, now that that's done, profile like @jwernerny says, and it may reveal where your true hot spots are. For a profiler, if this is windows and visual studio, consider the intel profiler (I guess this is homework, so you can probably use the evaluation version) - it's pretty good at highlighting hotspots.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T10:05:32.283", "Id": "2990", "ParentId": "2978", "Score": "1" } }, { "body": "<p>It might be because you are using a queue to store your Nodes in q in get_friends. You are doing a breadth-first search, meaning a lot of insertions and removals. Note that for breadth-first you can also use a last-in-first-out queue, which you can simulate very efficiently using a pre-allocated vector.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-16T12:53:27.580", "Id": "4145", "ParentId": "2978", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T11:24:12.000", "Id": "2978", "Score": "2", "Tags": [ "c++", "algorithm", "edit-distance" ], "Title": "Finding social network of a friend" }
2978
<p>I'm making a pong game with SFML and in the process made a function that takes a <code>Time</code>, <code>Speed</code>, <code>Angle</code> of movement, buffer for the movement on the X axis, and buffer for the movement on the Y axis. </p> <p>I then implemented this function into my custom <code>mySprite</code> class, more specifically into its <code>update()</code> function which updates its Position using the above function to calculate its new position. </p> <p>However, I'm worried that giving the function the <code>FrameTime()</code> of the Window (the time since the frame was last updated) is not the best choice as the sprites might start jumping around if there's lag between frame updates or other problems.</p> <p>Finally I would like to know about my organization, planning, etc.</p> <pre><code>#include&lt;SFML/Graphics.hpp&gt; #include&lt;SFML/System.hpp&gt; #include&lt;cmath&gt; #include&lt;vector&gt; # define M_PI 3.14159265358979323846 sf::RenderWindow Window; template&lt;typename T&gt; void CalculateMove(T Time, T Speed, T Angle, T&amp; buffX, T&amp; buffY) { //determine what quadrant of circle we're in unsigned int Quadrant= 1; if(Angle&gt;90) Quadrant= 2; if(Angle&gt;180) Quadrant= 3; if(Angle&gt;270) Quadrant= 4; //anything above 90 would be impossible triangle Angle= (float)(Angle-(int)Angle)+(float)((int)Angle%90); // calculates x and y based on angle and Hypotenuse.02433 if((int)Angle!=0){ buffX= sin(Angle / 180 * M_PI)/ (1.f/(Speed*Time)); buffY= sin((180-Angle-90)/ 180 * M_PI)/ (1.f/(Speed*Time));} else{// Movement is a straight line on X or Y axis if(Quadrant==0 || Quadrant==2) buffX= Speed*Time; if(Quadrant==1 || Quadrant==4) buffY= Speed*Time;} //Quadrant Factor (positive or negative movement on the axis) switch(Quadrant){ case 1: break; case 2: buffX=-buffX; break; case 3: buffX=-buffX; buffY=-buffY; break; case 4: buffY=-buffY; break;} }; ///////////////////////////////////////// Mysprite //////////////////////////////// class mySprite : public sf::Sprite { private: float velocity; float angle; public: // all the values needed by the base class sprite(); mySprite( const sf::Image&amp; Img, const sf::Vector2f&amp; Position = sf::Vector2f(0, 0), const sf::Vector2f&amp; Scale = sf::Vector2f(1, 1), float Rotation = 0.f, const float Angle= 0.f, const float Velocity= 0.f, const sf::Color&amp; Col = sf::Color(255, 255, 255, 255)): Sprite(Img, Position, Scale, Rotation, Col){ angle= Angle; velocity= Velocity;}; float Velocity(){return velocity;}; void SetVelocity(float newVelocity){velocity=newVelocity;}; float Angle(){return angle;}; void SetAngle(float newAngle){angle=newAngle;}; void Update(){ float frameTime= Window.GetFrameTime(); float X=0,Y=0; CalculateMove(frameTime,velocity,angle,X,Y); Move(X,-Y); }; void Reflect(float CollAngle){ SetRotation(-GetRotation()); angle=-angle; //TODO: factor in the collision angle }; }; </code></pre>
[]
[ { "body": "<p>It's often simpler to have a fixed frame rate in a game. Then you don't have to multiply everything by a time factor. In this case, you do not have to lower the frame rate to the lowest value that all computers can handle. You can for example let the position updates run at 200Hz and update the graphics at the highest speed the computer can handle (which may be lower than 200Hz).</p>\n\n<p>If the updates can easily run at a fixed speed on all hardware you want it to run on, this can work well. It is a good way to get consistent behaviour in physics simulations, and for simple games, updating at a much higher speed than needed for the graphics is not a problem.</p>\n\n<p>On the other hand, if the position updates are complicated, you may not be able to run them at top speed, and you'll have to handle varying time deltas (as in your code). This is often more difficult. The \"jumping around in case of lag\" problem has a simple (but not perfect) solution: just put a cap on the time delta, so you'll never do calculations on a time delta bigger than say 50 ms.</p>\n\n<p>I guess this part of the question would fit better at gamedev.stackexchange.com, where there probably already are discussions about it.</p>\n\n<p><strong>EDIT:</strong> Sure is, have a look at <a href=\"https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step\">https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T19:52:20.533", "Id": "3048", "ParentId": "2985", "Score": "2" } } ]
{ "AcceptedAnswerId": "3048", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T01:56:06.677", "Id": "2985", "Score": "2", "Tags": [ "c++", "sfml" ], "Title": "How is my SFML sprite Move() function?" }
2985
<p>So I have started a PHP framework called ExCx and I haven't really had much experience in the professional development business.</p> <p>I was just wondering if my structure/layout/methods are up to scratch?</p> <p>EDIT: Forget the URL, added that. Normally I remember to omit the closing php tag...</p> <p>In tandem with this I am building a PHP Blocks type thing, It's still early days for both projects.</p> <pre><code>&lt;?php /**** * * ecCore Provides low-level debugging, error and exception functionality * Matthew Day (CFHC Web Development 2011) * @package: ExCx * @version: 1.0 * ****/ class ecCore { //The following constants allow for pretty call backs to static methods const backtrace = 'ecCore::backtrace'; const call = 'ecCore::call'; const callback = 'ecCore::callback'; const checkOS = 'ecCore::checkOS'; const checkVersion = 'ecCore::checkVersion'; const configureSMTP = 'ecCore::configureSMTP'; const debug = 'ecCore::debug'; const detectOpcodeCache = 'ecCore::detectOpcodeCache'; const disableContext = 'ecCore::disableContext'; const dump = 'ecCore::dump'; const enableDebugging = 'ecCore::enableDebugging'; const enableDynamicConstants = 'ecCore::enableDynamicConstants'; const enableErrorHandling = 'ecCore::enableErrorHandling'; const enableExceptionHandling = 'ecCore::enableExceptionHandling'; const expose = 'ecCore::expose'; const getDebug = 'ecCore::getDebug'; const handleError = 'ecCore::handleError'; const handleException = 'ecCore::handleException'; const registerDebugCallback = 'ecCore::registerDebugCallback'; const reset = 'ecCore::reset'; const sendMessagesOnShutdown = 'ecCore::sendMessagesOnShutdown'; const startErrorCapture = 'ecCore::startErrorCapture'; const stopErrorCapture = 'ecCore::stopErrorCapture'; static private $captured_error_level = 0; static private $captured_error_regex = array(); static private $captured_error_types = array(); static private $captured_errors = array(); static private $captured_errors_previous_handler = array(); static private $context_shown = FALSE; static private $debug = NULL; static private $debug_callback = NULL; static private $dynamic_constants = FALSE; static private $error_destination = 'html'; static private $error_message_queue = array(); static private $exception_destination = 'html'; static private $exception_handler_callback = NULL; static private $exception_handler_parameters = array(); static private $exception_message = NULL; static private $handles_errors = FALSE; static private $handles_exceptions = FALSE; static private $show_context = TRUE static private $smtp_connection = NULL; static private $smtp_from_email = NULL; //Creates a nicely formatted backtrace to where the method is initally called static public function backtrace($remove_lines=0, $backtrace=NULL) { if ($remove_lines !== NULL &amp;&amp; !is_numeric($remove_lines)) { $remove_lines = 0; } settype($remove_lines, 'integer'); $doc_root = realpath($_SERVER['DOCUMENT_ROOT']); $doc_root .= (substr($doc_root, -1) != DIRECTORY_SEPERATOR) ? DIRECTORY_SEPERATOR : ''; if ($backtrace === NULL) { $backtrace = debug_backtrace(); } while ($remove_lines &gt; 0) { array_shift($backtrace); $remove_lines--; } $backtrace = array_reverse($backtrace); $bt_string = ''; $i = 0; foreach ($backtrace as $call) { if ($i) { $bt_string .= "\n"; } if (isset($call['file'])) { $bt_string .= str_replace($doc_root, '{doc_root}' . DIRECTORY_SEPARATOR, $call['file']) . '(' . $call['line'] . '): '; } else { $bt_string .= '[internal function]: '; } if (isset($call['class'])) { $bt_string .= $call['class'] . $call['type']; } if (isset($call['class']) || isset($call['function'])) { $bt_string .= $call['function'] . '('; $j = 0; if (!isset($call['args'])) { $call['args'] = array(); } foreach ($call['args'] as $arg) { if ($j) { $bt_string .= ', '; } if (is_bool($arg)) { $bt_string .= ($arg) ? 'true' : 'false'; } elseif (is_null($arg)) { $bt_string .= 'NULL'; } elseif (is_array($arg)) { $bt_string .= 'Array'; } elseif (is_object($arg)) { $bt_string .= 'Object(' . get_class($arg) . ')'; } elseif (is_string($arg)) { // Shorten the UTF-8 string if it is too long if (strlen(utf8_decode($arg)) &gt; 18) { // If we can't match as unicode, try single byte if (!preg_match('#^(.{0,15})#us', $arg, $short_arg)) { preg_match('#^(.{0,15})#s', $arg, $short_arg); } $arg = $short_arg[0] . '...'; } $bt_string .= "'" . $arg . "'"; } else { $bt_string .= (string) $arg; } } $bt_string .= ')'; } $i++; } return $bt_string; } // end of the backtrace function /**** * * Performs a [http://php.net/call_user_func call_user_func()], while translating PHP 5.2 static callback syntax for PHP 5.1 and 5.0 * ****/ static public function call($callback, $parameters=array()) { //Fix PHP 5.0 and 5.1 static callback syntax if (is_string($callback) &amp;&amp; strpos($callback, '::') !== FALSE) { $callback = explode('::', $callback); } $parameters = array_slice(func_get_args(), 1); if (sizeof($parameters) == 1 &amp;&amp; is_array($parameters[0])) { $parameters = $parameters[0]; } return call_user_func_array($callback, $parameters); } /**** * * Translates a Class::method style static method callback to array style for compatibility with PHP 5.0 and 5.1 and built-in PHP functions * ****/ /**** * * Checks an error/exception destination to make sure it is valid * ****/ static private function checkDestination($destination) { if ($destination == 'html') { return 'html'; } if (preg_match('~^(?: # Allow leading whitespace (?:[^\x00-\x20\(\)&lt;&gt;@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") # An "atom" or a quoted string (?:\.[ \t]*(?:[^\x00-\x20\(\)&lt;&gt;@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* # A . plus another "atom" or a quoted string, any number of times )@(?: # The @ symbol (?:[a-z0-9\\-]+\.)+[a-z]{2,}| # Domain name (?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]) # (or) IP addresses ) (?:\s*,\s* # Any number of other emails separated by a comma with surrounding spaces (?: (?:[^\x00-\x20\(\)&lt;&gt;@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") (?:\.[ \t]*(?:[^\x00-\x20\(\)&lt;&gt;@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* )@(?: (?:[a-z0-9\\-]+\.)+[a-z]{2,}| (?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]) ) )*$~xiD', $destination)) { return 'email'; } $path_info = pathinfo($destination); $dir_exists = file_exists($path_info['dirname']); $dir_writable = ($dir_exists) ? is_writable($path_info['dirname']) : FALSE; $file_exists = file_exists($destination); $file_writable = ($file_exists) ? is_writable($destination) : FALSE; if (!$dir_exists || ($dir_exists &amp;&amp; ((!$file_exists &amp;&amp; !$dir_writable) || ($file_exists &amp;&amp; !$file_writable)))) { return FALSE; } return 'file'; } } // End of class ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T05:05:15.153", "Id": "4560", "Score": "0", "body": "Erm, 404 Not Found." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T08:38:59.980", "Id": "4607", "Score": "0", "body": "Please post code, not just links to code. See the FAQ for more information." } ]
[ { "body": "<p>I haven't read the source code entirely, but here a few things that came to mind immediately:</p>\n\n<ul>\n<li>Use PHP Docblocks, so my IDE can support me when using your code</li>\n<li>Please break down <code>backtrace()</code> into smaller functions which are understandable in an instant or insert some inline comments above those crazy if/else/string operations in this function.</li>\n<li>Omit the closing <code>?&gt;</code> when you have a PHP only file, because it might give you alot of headaches (weird spaces popping up in your HTML output which you won't find easily)</li>\n<li>Make <code>__construct</code> and <code>__clone</code> (even if they don't contain any code) private if you have a static class. This way somebody who uses your class and doesn't bother to look into the source or docs will realize how to use your class faster.</li>\n<li>Don't use String concatenation (<code>.=</code>) in a loop. Build some kind of data structure like an array within this loop and <code>implode()</code> afterwards. Much easier to understand and faster since concatenating strings is very expensive.</li>\n<li>If you want other people to use and maintain your code, please provide at least better description what this code does, some sample usage and output.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T20:38:58.037", "Id": "9007", "Score": "0", "body": "+1 agree with most statements, except string concatenation vs. implode perf, see http://www.sitepoint.com/high-performance-string-concatenation-in-php/. however this is micro-optimization. About readability, it depends on what you will do after the loop (+ may be quite subjective): check http://stackoverflow.com/questions/1847356/string-concatenation-vs-array-implode-in-php" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T07:55:50.410", "Id": "3038", "ParentId": "2986", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T04:08:49.290", "Id": "2986", "Score": "5", "Tags": [ "php" ], "Title": "Open source PHP framework" }
2986
<p>I've been playing around with Python off and on for about the past year and recently came up with the following 68 (was 62) lines. I think I'll try making a calculator out of it. I'd really like to know what readers here think of its attributes such as coding style, readability, and feasible purposefulness.</p> <pre><code># notes: separate addresses from data lest the loop of doom cometh class Interpreter: def __init__(self): self.memory = { } self.dictionary = {"mov" : self.mov, "put" : self.put, "add" : self.add, "sub" : self.sub, "clr" : self.clr, "cpy" : self.cpy, "ref" : self.ref } self.hooks = {self.val("0") : self.out } def interpret(self, line): x = line.split(" ") vals = tuple(self.val(y) for y in x[1:]) dereferenced = [] keys_only = tuple(key for key in self.memory) for val in vals: while val in self.memory: val = self.memory[val] dereferenced.append(val) vals = tuple(y for y in dereferenced) self.dictionary[x[0]](vals) def val(self, x): return tuple(int(y) for y in str(x).split(".")) def mov(self, value): self.ptr = value[0] def put(self, value): self.memory[self.ptr] = value[0] def clr(self, value): if self.ptr in self.hooks and self.ptr in self.memory: x = self.hooks[self.ptr] y = self.memory[self.ptr] for z in y: x(z) del self.memory[self.ptr] def add(self, values): self.put(self.mat(values, lambda x, y: x + y)) def sub(self, values): self.put(self.mat(values, lambda x, y: x - y)) def mat(self, values, op): a, b = self.memory[values[0]], self.memory[values[1]] if len(a) &gt; len(b): a, b = b, a c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]] return [tuple(x for x in c)] def cpy(self, value): self.put(value) def out(self, x): print chr(x), def ref(self, x): self.put(x) interp = Interpreter() for x in file(__file__.split('/')[-1].split(".")[-2] + ".why"): interp.interpret(x.strip()) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T14:37:04.900", "Id": "4557", "Score": "2", "body": "It would be nice to see some sample input too." } ]
[ { "body": "<p>To allow your module to be loadable by other files, it's customary to write the end of it with a <code>if __name__ == '__main__':</code> conditional like so:</p>\n\n<pre><code>if __name__ == '__main__':\n interp = Interpreter()\n for x in file(__file__.split('/')[-1].split(\".\")[-2] + \".why\"):\n interp.interpret(x.strip())\n</code></pre>\n\n<p>Maybe I'm being picky (but you did ask for style input), read <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> and try to follow it as best you can (stand). One thing that jumped out at me right away was your 2 space indentation vs. the PEP8 recommendation of 4. One letter variables are usually only recommended for looping vars. You could probably increase the readability of your code by renaming some of those x's, y's, a's, etc.</p>\n\n<p>Another maxim of Python programming is to use the tools provided, I was pondering what you were doing with:</p>\n\n<pre><code>__file__.split('/')[-1].split(\".\")[-2] + \".why\"\n</code></pre>\n\n<p>an alternative that uses existing Python modules (and is more portable across platforms) is:</p>\n\n<pre><code>os.path.splitext(os.path.basename(__file__))[0] + \".why\"\n</code></pre>\n\n<p>It's about the same length, and is a good deal more clear as to what you're doing as the function names spell it out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T14:35:30.923", "Id": "2994", "ParentId": "2988", "Score": "3" } }, { "body": "<p>Sorry for bluntness, intended or not, but here we go!</p>\n\n<p>Not very good readability IMO. It takes a while to understand what the code does. Unit tests or at least some sample input and output may make it obvious.</p>\n\n<p>In general, naming should be improved. It's difficult to understand what a function or variable does from its name.</p>\n\n<p>There's also much shuffling of data back and forth that seems unnecessary. It looks like this can be simplified quite a bit, see inline comments.</p>\n\n<p>Also, you use tuples in many situations where a list would be more natural.</p>\n\n<p>As I had problems understanding the code, I may have misunderstood things in it, so read the following inline comments with that in mind.</p>\n\n<pre><code># notes: separate addresses from data lest the loop of doom cometh\n</code></pre>\n\n<p>Not a very helpful comment, is it?</p>\n\n<pre><code>class Interpreter:\n</code></pre>\n\n<p>Can you find a class name that better tells what this class does? It not only interprets.</p>\n\n<pre><code> def __init__(self):\n self.memory = { }\n</code></pre>\n\n<p>I'd like a comment on what self.memory is.</p>\n\n<pre><code> self.dictionary = {\"mov\" : self.mov,\n \"put\" : self.put,\n \"add\" : self.add,\n \"sub\" : self.sub,\n \"clr\" : self.clr,\n \"cpy\" : self.cpy,\n \"ref\" : self.ref }\n</code></pre>\n\n<p>No shit, it's a dictionary. But can you find a name that tells what kind of dictionary it is?</p>\n\n<p>To reduce code size, you may consider <code>self.dictionary = dict(self.getattr(attr) for attr in 'mov put add sub clr cpy ref'.split())</code>, but some people may find it too \"clever.\"</p>\n\n<pre><code> self.hooks = {self.val(\"0\") : self.out }\n</code></pre>\n\n<p>Very unclear what hooks is for. This is the only value that is every put in it. <code>self.val(\"0\")</code> seems to be just a complicated way of saying (0,). What's up with that?</p>\n\n<pre><code> def interpret(self, line):\n x = line.split(\" \")\n</code></pre>\n\n<p>Bad variable name: <code>x</code>. Should it be <code>tokens</code> instead?</p>\n\n<pre><code> vals = tuple(self.val(y) for y in x[1:])\n</code></pre>\n\n<p>Here, vals could be a list instead, like <code>vals = [self.val(y) for y in x[1:]]</code>. Making it a tuple just makes the code a little bit more complicated for no reason.</p>\n\n<pre><code> dereferenced = []\n keys_only = tuple(key for key in self.memory)\n</code></pre>\n\n<p>Consider <code>keys_only = self.memory.keys()</code>? Oh, and by the way, <code>keys_only</code> is never used, so just remove it.</p>\n\n<pre><code> for val in vals:\n while val in self.memory: val = self.memory[val]\n</code></pre>\n\n<p>Looks like this while loop will be infinite if it runs at all. Is it supposed to be an if?</p>\n\n<pre><code> dereferenced.append(val)\n vals = tuple(y for y in dereferenced)\n</code></pre>\n\n<p>Pointless conversion of dereferenced to tuple.</p>\n\n<pre><code> self.dictionary[x[0]](vals)\n</code></pre>\n\n<p>I think the whole interpret method can be rewritten to something like the following. Note the changed names.</p>\n\n<pre><code> def interpret(self, line):\n command, *tokens = line.split() # Python 3 only\n values = [self.val(y) for token in tokens]\n dereferenced = [self.memory.get(value, value) for value in values]\n self.dictionary[command](dereferenced)\n</code></pre>\n\n<p>Some may say it's a bit too terse. I could have written the <code>dereferenced = ...</code> line as a couple of more explicit statements perhaps.</p>\n\n<p>I won't go into the rest, but the comments about naming and unnecessary complexity applies.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T22:19:06.880", "Id": "2998", "ParentId": "2988", "Score": "10" } } ]
{ "AcceptedAnswerId": "2994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T05:41:16.843", "Id": "2988", "Score": "6", "Tags": [ "python", "interpreter" ], "Title": "Simple Language Interpreter" }
2988
<p>i have this code that is suppose to work with at starting the minimum number of threads, say 5. when it starts the first five threads, it automatically replaces any thread that is finished making sure that there is always five threads working.</p> <p>the problem here is that, am finding it difficult to manage where am suppose perform locks</p> <pre><code>Private Sub StartProcess() intNextItemIndex = intMaxThreadCount ' start the first five threads For i = 0 To intMaxThreadCount If i &lt; ListWorkItems.Count Then StartNextItem(i) End If Next ' update running threads End Sub Private Sub StartNextItem(ByVal index As Integer) Dim tt As New ThreadTask If index &lt; ListWorkItems.Count Then ' start parsing thread Dim t As New Thread(AddressOf DoWork) With tt .Index = index .Task = "count" .Data = CStr(index * index) End With With t .IsBackground = True .Name = "Thread " &amp; index .Start(tt) End With Thread.Sleep(100) End If End Sub Private Sub DoWork(ByVal data As Object) Dim tt As ThreadTask = CType(data, ThreadTask) Dim sTemp As String = Nothing Dim objLock As Object = New Object() Dim t As Double = 0 myWatch = New Stopwatch Try Debug.Print("Incoming index: " &amp; CInt(tt.Index)) myWatch.Start() SyncLock (objLock) sTemp = PerformWork(ListWorkItems(CInt(tt.Index)).ToString) 'sTemp = CountTo() End SyncLock myWatch.Stop() t = myWatch.ElapsedMilliseconds / 1000 AddItem(tt.Index, t.ToString &amp; " = " &amp; sTemp) 'AddItem(index, t.ToString) Catch ex As Exception ' catch error Debug.Print( ex.Message) End Try end sub Public Sub AddItem(ByVal index As Integer, ByVal item As String) If Me.InvokeRequired Then Me.Invoke(New AddItemDelegate(AddressOf AddItem), index, item) Else Dim objLock As Object = New Object() Dim lvItem As New ListViewItem SyncLock (objLock) count += 1 intNextItemIndex += 1 End SyncLock With lvItem .Text = index.ToString .SubItems.Add(ListWorkItems(index).ToString) If item.Length &lt; 100 Then .SubItems.Add(item.ToString) Else .SubItems.Add(item.Length.ToString) End If End With listView1.Items.Add(lvItem) If count = ListWorkItems.Count Then Button1.Enabled = True tsslStatus.Text = "Finished!!" Debug.Print("Finished: " &amp; index.ToString) Else tsslStatus.Text = "Processing item (" &amp; count + 1 &amp; ")" End If StartNextItem(intNextItemIndex) End If End Sub </code></pre> <p>can someone help me review it and tell me whats wrong with it?</p> <p>Are the loks ok?</p> <p>Is this way of doing it ok?</p> <p>What possible improvements can i make</p> <p>thanks all</p>
[]
[ { "body": "<p>Unfortunately, the whole approach is broken. You should make your parallel <em>tasks</em> explicit in the code so that you don’t need cross-thread communication any more. Secondly, you are writing your own thread scheduler here. – Don’t. Schedulers already exist, take advantage of that.</p>\n\n<p>Have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/dd537609.aspx\" rel=\"nofollow\">Task Parallel Library</a>, in particular the <code>Task</code> and <code>TaskScheduler</code> classes.</p>\n\n<p>Better yet, try to model your algorithm to benefit from <a href=\"http://msdn.microsoft.com/en-us/library/dd537608.aspx\" rel=\"nofollow\">data parallelism</a> and eschew explicit threading completely in favour of the automatically parallelised computations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T11:44:14.563", "Id": "4555", "Score": "0", "body": "am using .net 2.0, of which the task Parallel is not available" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T11:45:23.983", "Id": "4556", "Score": "0", "body": "@Smith That’s a problem. Incidentally, why are you using a completely outdated (> 5 years old, > 2 versions outdated) version of .NET?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T11:40:26.550", "Id": "2992", "ParentId": "2991", "Score": "1" } } ]
{ "AcceptedAnswerId": "2992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T10:55:39.053", "Id": "2991", "Score": "2", "Tags": [ "multithreading", "vb.net" ], "Title": "multiple threaded program vb.net" }
2991
<p>I wrote program which simulates the work of the restaurant. It works but I would like to change it because I think there is better solution.Thanks for your suggestions.</p> <p>Client.java</p> <pre><code>public class Client implements Runnable { private Restaurant r; public void makeOrder() throws InterruptedException { synchronized (r) { r.notifyAll(); System.out.println("Start ordering "); Thread.sleep(1000); r.putOrderMadeByClient(r.orderId); System.out.println("End ordering "); while(r.orderReceived==false) r.wait(); r.getOrderReceived(); } } public Client(Restaurant r) { this.r=r; } public void run() { try { makeOrder(); } catch (InterruptedException e) { e.printStackTrace(); } } } </code></pre> <p>Waiter.java</p> <pre><code>public class Waiter implements Runnable { private Restaurant r; public void makeServe() throws InterruptedException { synchronized (r) { r.notifyAll(); while(r.orderMadeByClient==false) r.wait(); System.out.println("Start serving order "); Thread.sleep(1000); r.putOrder(r.getOrderMadeByClient()); while(r.orderReady==false) r.wait(); r.putOrderReceived(r.getFood()); System.out.println("End serving order "); } } public Waiter(Restaurant r) { this.r=r; } @Override public void run() { try { makeServe(); } catch (InterruptedException e) { e.printStackTrace(); } } } </code></pre> <p>Chef.java</p> <pre><code>public class Chef implements Runnable { private Restaurant r; public void makeFood() throws InterruptedException { synchronized (r) { r.notifyAll(); while(r.orderTaken==false) r.wait(); System.out.println("Start making food "); Thread.sleep(1000); r.putFood(r.getOrder()); System.out.println("End making food "); } } public Chef(Restaurant r) { this.r=r; } @Override public void run() { try { makeFood(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>Restaurant.java</p> <pre><code>public class Restaurant { boolean orderMadeByClient; boolean orderTaken; boolean orderReady; boolean orderReceived; long orderId; public Restaurant() { } public void makeRestaurant() { Client cl = new Client(this); Chef ch = new Chef(this); Waiter w = new Waiter(this); Thread t1 = new Thread(cl); Thread t2 = new Thread(w); Thread t3 = new Thread(ch); t1.start(); t2.start(); t3.start(); } synchronized long getOrderMadeByClient() { while (!orderMadeByClient) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderMadeByClient = false; notifyAll(); System.out.println("get order from client #" + orderId); return orderId; } synchronized void putOrderMadeByClient(long l) { while (orderMadeByClient) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderMadeByClient = true; this.orderId = l; notifyAll(); System.out.println("put order client #" + l); } synchronized long getOrder() { while (!orderTaken) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderTaken = false; notifyAll(); System.out.println("get order from waiter #" + orderId); return orderId; } synchronized void putOrder(long l) { while (orderTaken) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderTaken = true; this.orderId = l; notifyAll(); System.out.println("put order to cook #" + l); } synchronized long getFood() { while (!orderReady) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderReady = false; notifyAll(); System.out.println("get order by waiter #" + orderId); return orderId; } synchronized void putFood(long n) { while (orderReady) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderReady = true; this.orderId = n; notifyAll(); System.out.println("put order by cook #" + n); } synchronized long getOrderReceived() { while (!orderReceived) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderReceived = false; notifyAll(); System.out.println("get order by client #" + orderId); return orderId; } synchronized void putOrderReceived(long l) { while (orderReceived) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } orderReceived = true; this.orderId = l; notifyAll(); System.out.println("put order by waiter #" + l); } } </code></pre> <p>Main.java</p> <pre><code>public class Main { public static void main(String[] args) { Restaurant r=new Restaurant(); r.makeRestaurant(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T07:53:12.333", "Id": "4570", "Score": "0", "body": "There is very similar demo example [http://code.google.com/p/wing-ding/source/browse/trunk/books/Programming_Scala/src/ch09/sleepingbarber/]. It was written using scala and actor concurrency model, but suggests much readable way to do things you are trying to do. Detailed description of that code could be found there: http://programming-scala.labs.oreilly.com/ch09.html." } ]
[ { "body": "<p>The main issue here is that everything synchronizes on the restaurant object. This means that the chef cannot prepare food while the client is placing an order, waiters cannot serve while the chef is cooking, etc. The first step would be to add <code>BlockingQueue</code>s to <code>Restaurant</code> and let them manage all of the calls to <code>wait()</code> and <code>notify()</code> for you.</p>\n\n<p>You'd need one queue of orders that waiters place and chefs take and another for food that chefs place and waiters take. When a <code>Chef</code> calls <code>take()</code> on the order queue, it will block until there is an order available. A <code>Waiter</code> calling <code>offer()</code> on the same queue will block until there is room in the queue. You can make the queues bounded (maximum size) or unbounded.</p>\n\n<p>You might even create a queue to hold the <code>client</code>s waiting to place orders. <code>Waiter</code>s would <code>poll()</code> the food and client queues in their <code>run()</code> loop so they don't wait forever for food to be ready when they haven't even placed any orders yet.</p>\n\n<pre><code>public void run() {\n while (true) {\n Food f = foodQueue.poll(2, TimeUnit.SECONDS);\n if (f != null) {\n // deliver food to client...\n }\n Order o = clientQueue.poll(2, TimeUnit.SECONDS);\n if (o != null) {\n if (!orderQueue.offer(o, 120, TimeUnit.SECONDS)) {\n // kitchen is too busy!\n break; // waiter quits out of frustration\n }\n }\n }\n}\n</code></pre>\n\n<p>The <code>Chef</code> class currently waits for a second and then takes the order and makes the food available immediately. Instead, it should take the order, <em>then</em> wait, and finally make the food available. If you were to create a queue for the use of the chef while cooking, you could use a priority queue (orders the elements in the queue) and have different types of food take different lengths of time to prepare. The chef would then have multiple things cooking at once and deliver each after its own cook time has expired.</p>\n\n<p>With the above in place you could really kick this into high gear by creating multiple waiters and chefs and add a separate thread that randomly creates clients that place random orders.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T18:16:06.083", "Id": "3002", "ParentId": "3001", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T14:36:32.167", "Id": "3001", "Score": "5", "Tags": [ "java", "multithreading" ], "Title": "Simple multithreading task" }
3001
<p>I have the following class that processes a Bitmap to place a fisheye distortion on it. I've run my app through TraceView and found that virtually all the processing time is spent looping through the bitmap. One developer has suggested not using float as this will slow things down where graphics are concerned. Also, using <code>math.pow()</code> and <code>ceil()</code> are not necessary? </p> <p>At the moment to place the effect by looping through the entire bitmap takes around 42 seconds, yes seconds:) I've tried replacing the floats with integers and that has reduced the time to 37 secs, but the effect is no longer present on the bitmap. The argument <code>k</code> is originally a float and sets the level of distortion (eg <code>0.0002F</code>). If I pass an integer, then the effect doesn't work. </p> <p>Can anyone point me in the right direction on how to optimize this process? Once I've optimized it I'd like to look into perhaps not looping through the entire bitmap and maybe putting a bounding box around the effect or using the algorithm below that determines whether a pixel is within the circle with a radius of 150. </p> <pre><code>class Filters{ float xscale; float yscale; float xshift; float yshift; int [] s; private String TAG = "Filters"; long getRadXStart = 0; long getRadXEnd = 0; long startSample = 0; long endSample = 0; public Filters(){ Log.e(TAG, "***********inside filter constructor"); } public Bitmap barrel (Bitmap input, float k){ //Log.e(TAG, "***********INSIDE BARREL METHOD "); float centerX=input.getWidth()/2; //center of distortion float centerY=input.getHeight()/2; int width = input.getWidth(); //image bounds int height = input.getHeight(); Bitmap dst = Bitmap.createBitmap(width, height,input.getConfig() ); //output pic // Log.e(TAG, "***********dst bitmap created "); xshift = calc_shift(0,centerX-1,centerX,k); float newcenterX = width-centerX; float xshift_2 = calc_shift(0,newcenterX-1,newcenterX,k); yshift = calc_shift(0,centerY-1,centerY,k); float newcenterY = height-centerY; float yshift_2 = calc_shift(0,newcenterY-1,newcenterY,k); xscale = (width-xshift-xshift_2)/width; // Log.e(TAG, "***********xscale ="+xscale); yscale = (height-yshift-yshift_2)/height; // Log.e(TAG, "***********yscale ="+yscale); // Log.e(TAG, "***********filter.barrel() about to loop through bm"); int origPixel; long startLoop = System.currentTimeMillis(); for(int j=0;j&lt;dst.getHeight();j++){ for(int i=0;i&lt;dst.getWidth();i++){ origPixel= input.getPixel(i,j); getRadXStart = System.currentTimeMillis(); float x = getRadialX((float)j,(float)i,centerX,centerY,k); getRadXEnd= System.currentTimeMillis(); float y = getRadialY((float)j,(float)i,centerX,centerY,k); sampleImage(input,x,y); int color = ((s[1]&amp;0x0ff)&lt;&lt;16)|((s[2]&amp;0x0ff)&lt;&lt;8)|(s[3]&amp;0x0ff); // System.out.print(i+" "+j+" \\"); if( Math.sqrt( Math.pow(i - centerX, 2) + ( Math.pow(j - centerY, 2) ) ) &lt;= 150 ){ dst.setPixel(i, j, color); }else{ dst.setPixel(i,j,origPixel); } } } return dst; } void sampleImage(Bitmap arr, float idx0, float idx1) { startSample = System.currentTimeMillis(); s = new int [4]; if(idx0&lt;0 || idx1&lt;0 || idx0&gt;(arr.getHeight()-1) || idx1&gt;(arr.getWidth()-1)){ s[0]=0; s[1]=0; s[2]=0; s[3]=0; return; } float idx0_fl=(float) Math.floor(idx0); float idx0_cl=(float) Math.ceil(idx0); float idx1_fl=(float) Math.floor(idx1); float idx1_cl=(float) Math.ceil(idx1); int [] s1 = getARGB(arr,(int)idx0_fl,(int)idx1_fl); int [] s2 = getARGB(arr,(int)idx0_fl,(int)idx1_cl); int [] s3 = getARGB(arr,(int)idx0_cl,(int)idx1_cl); int [] s4 = getARGB(arr,(int)idx0_cl,(int)idx1_fl); float x = idx0 - idx0_fl; float y = idx1 - idx1_fl; s[0]= (int) (s1[0]*(1-x)*(1-y) + s2[0]*(1-x)*y + s3[0]*x*y + s4[0]*x*(1-y)); s[1]= (int) (s1[1]*(1-x)*(1-y) + s2[1]*(1-x)*y + s3[1]*x*y + s4[1]*x*(1-y)); s[2]= (int) (s1[2]*(1-x)*(1-y) + s2[2]*(1-x)*y + s3[2]*x*y + s4[2]*x*(1-y)); s[3]= (int) (s1[3]*(1-x)*(1-y) + s2[3]*(1-x)*y + s3[3]*x*y + s4[3]*x*(1-y)); endSample = System.currentTimeMillis(); } int [] getARGB(Bitmap buf,int x, int y){ int rgb = buf.getPixel(y, x); // Returns by default ARGB. int [] scalar = new int[4]; scalar[0] = (rgb &gt;&gt;&gt; 24) &amp; 0xFF; scalar[1] = (rgb &gt;&gt;&gt; 16) &amp; 0xFF; scalar[2] = (rgb &gt;&gt;&gt; 8) &amp; 0xFF; scalar[3] = (rgb &gt;&gt;&gt; 0) &amp; 0xFF; return scalar; } float getRadialX(float x,float y,float cx,float cy,float k){ x = (x*xscale+xshift); y = (y*yscale+yshift); float res = x+((x-cx)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy))); return res; } float getRadialY(float x,float y,float cx,float cy,float k){ x = (x*xscale+xshift); y = (y*yscale+yshift); float res = y+((y-cy)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy))); return res; } float thresh = 1; float calc_shift(float x1,float x2,float cx,float k){ float x3 = (float)(x1+(x2-x1)*0.5); float res1 = x1+((x1-cx)*k*((x1-cx)*(x1-cx))); float res3 = x3+((x3-cx)*k*((x3-cx)*(x3-cx))); if(res1&gt;-thresh &amp;&amp; res1 &lt; thresh) return x1; if(res3&lt;0){ return calc_shift(x3,x2,cx,k); } else{ return calc_shift(x1,x3,cx,k); } } }// end of filters class </code></pre>
[]
[ { "body": "<p>This line will eat a lot of performance:</p>\n\n<pre><code>if( Math.sqrt( Math.pow(i - centerX, 2) + ( Math.pow(j - centerY, 2) ) ) &lt;= 150 )\n</code></pre>\n\n<p>First for simple squaring, write your own function:</p>\n\n<pre><code>float sqr(float x) { return x*x; }\n</code></pre>\n\n<p>Second and even more important, if you square the expressions on both sides (which is OK because both are positive), you don't need the expensive sqrt-Function on the left side. Simply write:</p>\n\n<pre><code>if( sqr(i - centerX) + sqr(j - centerY) &lt;= 150*150 )\n</code></pre>\n\n<p>There are a lot of other little things, e.g.</p>\n\n<pre><code>float x3 = (float)(x1+(x2-x1)*0.5);\n</code></pre>\n\n<p>...could be...</p>\n\n<pre><code>float x3 = (x1+(x2-x1)*0.5f);\n</code></pre>\n\n<p>I don't know the details of the algorithm, e.g. if you could use <code>int</code>s in certain places, or if it would make sense to use a precalculated table for some values. </p>\n\n<p>I tried to improve your version. Of course I couldn't test it...</p>\n\n<pre><code>import java.util.Arrays;\n\nclass Filters {\n float xscale;\n float yscale;\n float xshift;\n float yshift;\n int[] s = new int[4];\n int[] s1 = new int[4];\n int[] s2 = new int[4];\n int[] s3 = new int[4];\n int[] s4 = new int[4];\n private String TAG = \"Filters\";\n long getRadXStart = 0;\n long getRadXEnd = 0;\n long startSample = 0;\n long endSample = 0;\n float xr;\n float yr;\n\n public Filters() {\n //Log.e(TAG, \"***********inside filter constructor\");\n }\n\n public Bitmap barrel(Bitmap input, float k) {\n //Log.e(TAG, \"***********INSIDE BARREL METHOD \");\n\n float centerX = input.getWidth() / 2; //center of distortion\n float centerY = input.getHeight() / 2;\n\n int width = input.getWidth(); //image bounds\n int height = input.getHeight();\n\n Bitmap dst = Bitmap.createBitmap(width, height, input.getConfig()); //output pic\n // Log.e(TAG, \"***********dst bitmap created \");\n xshift = calc_shift(0, centerX - 1, centerX, k);\n\n float newcenterX = width - centerX;\n float xshift_2 = calc_shift(0, newcenterX - 1, newcenterX, k);\n\n yshift = calc_shift(0, centerY - 1, centerY, k);\n\n float newcenterY = height - centerY;\n float yshift_2 = calc_shift(0, newcenterY - 1, newcenterY, k);\n\n xscale = (width - xshift - xshift_2) / width;\n // Log.e(TAG, \"***********xscale =\"+xscale);\n yscale = (height - yshift - yshift_2) / height;\n // Log.e(TAG, \"***********yscale =\"+yscale);\n // Log.e(TAG, \"***********filter.barrel() about to loop through bm\");\n\n\n int origPixel;\n long startLoop = System.currentTimeMillis();\n for (int j = 0; j &lt; dst.getHeight(); j++) {\n for (int i = 0; i &lt; dst.getWidth(); i++) {\n origPixel = input.getPixel(i, j);\n getRadXStart = System.currentTimeMillis();\n getRadialXY(j, i, centerX, centerY, k);\n getRadXEnd = System.currentTimeMillis();\n\n sampleImage(input, xr, yr);\n\n int color = ((s[1] &amp; 0x0ff) &lt;&lt; 16) | ((s[2] &amp; 0x0ff) &lt;&lt; 8) | (s[3] &amp; 0x0ff);\n // System.out.print(i+\" \"+j+\" \\\\\");\n\n dst.setPixel(i, j, \n (sqr(i - centerX) + sqr(j - centerY) &lt;= 150 * 150) \n ? color\n : origPixel);\n }\n }\n\n return dst;\n }\n\n float sqr(float x) {\n return x * x;\n }\n float cube(float x) {\n return x * x * x;\n }\n\n void sampleImage(Bitmap arr, float idx0, float idx1) {\n startSample = System.currentTimeMillis();\n Arrays.fill(s, 0);\n if (idx0 &lt; 0 || idx1 &lt; 0 || idx0 &gt; (arr.getHeight() - 1) || idx1 &gt; (arr.getWidth() - 1)) {\n return;\n }\n\n float idx0_fl = (float) Math.floor(idx0);\n float idx0_cl = (float) Math.ceil(idx0);\n float idx1_fl = (float) Math.floor(idx1);\n float idx1_cl = (float) Math.ceil(idx1);\n\n getARGB(s1, arr, (int) idx0_fl, (int) idx1_fl);\n getARGB(s2, arr, (int) idx0_fl, (int) idx1_cl);\n getARGB(s3, arr, (int) idx0_cl, (int) idx1_cl);\n getARGB(s4, arr, (int) idx0_cl, (int) idx1_fl);\n\n float x = idx0 - idx0_fl;\n float y = idx1 - idx1_fl;\n\n //reordered for less multiplications\n for(int i = 0; i &lt; 4; i++) {\n s[i] = (int) (s1[i] + x*(s4[i]-s1[i]) + y *(s2[i]-s1[i] + x*(s1[i]-s2[i]+s3[i]-s4[i])));\n }\n\n endSample = System.currentTimeMillis();\n }\n\n void getARGB(int[] scalar, Bitmap buf, int x, int y) {\n int rgb = buf.getPixel(y, x); // Returns by default ARGB.\n scalar[0] = (rgb &gt;&gt;&gt; 24) &amp; 0xFF;\n scalar[1] = (rgb &gt;&gt;&gt; 16) &amp; 0xFF;\n scalar[2] = (rgb &gt;&gt;&gt; 8) &amp; 0xFF;\n scalar[3] = rgb &amp; 0xFF;\n }\n\n void getRadialXY(float x, float y, float cx, float cy, float k) {\n x = (x * xscale + xshift);\n y = (y * yscale + yshift);\n float f = k * (sqr(x - cx) + sqr(y - cy));\n xr = x + ((x - cx) * f);\n yr = y + ((y - cy) * f);\n }\n float thresh = 1;\n\n float calc_shift(float x1, float x2, float cx, float k) {\n\n float x3 = x1 + (x2 - x1) * 0.5f;\n float res1 = x1 + cube(x1 - cx) * k ;\n\n if (-thresh &lt; res1 &amp;&amp; res1 &lt; thresh) {\n return x1;\n }\n\n float res3 = x3 + cube(x3 - cx) * k;\n return (res3 &lt; 0) \n ? calc_shift(x3, x2, cx, k)\n : calc_shift(x1, x3, cx, k);\n }\n}// end of filters class\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T12:52:08.407", "Id": "9457", "Score": "0", "body": "Are you shure about sqrt(x^2 + y^2) == sqrt(x) + sqrt(y) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T14:00:18.937", "Id": "9461", "Score": "0", "body": "Are you sure about sqr == sqrt?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T14:09:08.860", "Id": "9462", "Score": "0", "body": "Sorry, my fault!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-19T18:30:28.757", "Id": "3008", "ParentId": "3007", "Score": "3" } }, { "body": "<p>You might want to consider working line-at-a-time rather than pixel-at-a-time. Looking at <a href=\"http://developer.android.com/reference/android/graphics/Bitmap.html\" rel=\"nofollow\">the documentation</a> this would mean calling <code>getPixels</code> and <code>setPixels</code> rather than <code>getPixel</code>/<code>setPixel</code>. Each call to either of these functions must convert the <code>(x, y)</code> coordinates you specify to an offset into the buffer (eg. <code>y * line_length + x</code>), and if you do this for every pixel in a large image these multiplications can add up.</p>\n\n<p>So something like...</p>\n\n<pre><code>int pixels[] = new int[width];\n\nfor (int y = 0; y&lt;height; ++y)\n{\n input.getPixels(pixels, 0, width, 0, y, width, 1);\n\n for (int x = 0; x&lt;width; ++x)\n {\n // TODO: make modification on pixels[x]\n }\n\n dst.setPixels(pixels, 0, width, 0, y, width, 1);\n}\n</code></pre>\n\n<p>Again, I make no guarantees that this will actually be faster, but it's something to try. The last time I messed around with image manipulation (working in C and with by-now-very-old PC hardware) I did notice that the per-line approach was much faster than computing the offset for a coordinate for every pixel.</p>\n\n<p>I also agree with @Landei that <code>x * x</code> is better than <code>pow(x, 2)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-19T19:59:29.887", "Id": "3009", "ParentId": "3007", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-19T16:06:41.550", "Id": "3007", "Score": "8", "Tags": [ "java", "android", "image" ], "Title": "Adding a Fish Eye Distortion to a Bitmap" }
3007
<p>I am fairly new to PHP, and would love to have my code reviewed to see what I am doing wrong and ways to improve it. The code works fine, I just feel like there's an easier way to do this.</p> <p>This is the PHP code at the top of my page - and then the HTML is below it, but I will only paste the PHP code. What the page is, is a way for a shop to edit which credit cards they accept. </p> <p>Instead of a form, I have the credit card logos on the page and if it's selected in the database then it is highlighted at 100% opacity, and if it's not selected then it's at 25% opacity, so it's faded out. If they choose to start accepting Mastercard for example, they click on the faded Mastercard logo and it goes to ?card=mastercard&amp;value=1 and it updates the database and refreshes the page, so when it refreshes it is now full opacity and selected in the database.</p> <p>In the database it is called "credit_cards" and the values are "xxxx" for "visa, mastercard, discover, amex"</p> <p>So if they are all selected, it will show "1111" if all except discover then it is "1101"</p> <pre><code>&lt;?php require_once('MySqlDb.php'); $Db = new MySqliDb('localhost', 'root', 'root', 'shops'); if(!isset($_GET['user_id'])) { die("No user selected."); } $id = $_GET['user_id']; $Db-&gt;where('id', $id); $result = $Db-&gt;get('users'); if(isset($_GET['card']) &amp;&amp; isset($_GET['value'])) { if ($_GET['value'] == "1" || $_GET['value'] == "0") { $card = $_GET['card']; $value = $_GET['value']; // Get Current Credit Cards Value In Database $currentCreditCards = $result[0]['credit_cards']; // Individual Credit Card Values $visa = substr($currentCreditCards, 0, 1); $mastercard = substr($currentCreditCards, 1, 1); $discover = substr($currentCreditCards, 2, 1); $amex = substr($currentCreditCards, 3, 1); switch($card) { case "visa": // Get The New Value To Update The Database With $newCreditCards = $value ."". $mastercard ."". $discover ."". $amex; $updateData = array('credit_cards' =&gt; $newCreditCards); $Db-&gt;where('id', $id); $Db-&gt;update('users', $updateData); header("location: test.php?user_id=$id"); break; case "mastercard": $newCreditCards = $visa ."". $value ."". $discover ."". $amex; $updateData = array('credit_cards' =&gt; $newCreditCards); $Db-&gt;where('id', $id); $Db-&gt;update('users', $updateData); header("location: test.php?user_id=$id"); break; case "discover": $newCreditCards = $visa ."". $mastercard ."". $value ."". $amex; $updateData = array('credit_cards' =&gt; $newCreditCards); $Db-&gt;where('id', $id); $Db-&gt;update('users', $updateData); header("location: test.php?user_id=$id"); break; case "amex": $newCreditCards = $visa ."". $mastercard ."". $discover ."". $value; $updateData = array('credit_cards' =&gt; $newCreditCards); $Db-&gt;where('id', $id); $Db-&gt;update('users', $updateData); header("location: test.php?user_id=$id"); break; } } } foreach($result as $row) : if($row['credit_cards'][0] == "1"){ $visaNumber = "0"; $visaStyle = "style=\"opacity: 1; filter: alpha(opacity=100)\""; } else { $visaNumber = "1"; $visaStyle = "style=\"opacity: 0.25; filter: alpha(opacity=25)\""; } if($row['credit_cards'][1] == "1"){ $masterCardNumber = "0"; $masterCardStyle = "style=\"opacity: 1; filter: alpha(opacity=100)\""; } else { $masterCardNumber = "1"; $masterCardStyle = "style=\"opacity: 0.25; filter: alpha(opacity=25)\""; } if($row['credit_cards'][2] == "1"){ $discoverNumber = "0"; $discoverStyle = "style=\"opacity: 1; filter: alpha(opacity=100)\""; } else { $discoverNumber = "1"; $discoverStyle = "style=\"opacity: 0.25; filter: alpha(opacity=25)\""; } if($row['credit_cards'][3] == "1"){ $amexNumber = "0"; $amexStyle = "style=\"opacity: 1; filter: alpha(opacity=100)\""; } else { $amexNumber = "1"; $amexStyle = "style=\"opacity: 0.25; filter: alpha(opacity=25)\""; } ?&gt; </code></pre> <p>Is this a stupid way of doing it? Am I doing this wrong?</p> <p>The whole <code>visaNumber</code> and <code>visaStyle</code> stuff is just for the HTML, so if its selected in the database, then the URL needs to point to ?visa=0 to turn it off, instead of ?visa=1, and then it has to show the correct opacity.</p>
[]
[ { "body": "<p>The first part that updates the selected credit card has a lot of code duplication that could be made generic.</p>\n\n<pre><code>// Get Current Credit Cards Value In Database\n$userCards= $result[0]['credit_cards'];\n\n$CARDS = array('visa', 'mastercard', 'discover', 'amex');\n$cardIndex = array_search($card, $CARDS);\nif ($cardIndex !== false) {\n $userCards[$cardIndex] = $value;\n $updateData = array('credit_cards' =&gt; $userCards);\n $Db-&gt;where('id', $id);\n $Db-&gt;update('users', $updateData);\n header(\"location: test.php?user_id=$id\");\n}\n</code></pre>\n\n<p><strong>Update:</strong> Start by replacing named variables such as <code>$visaNumber</code> and <code>$visaStyle</code> with an array of number/styles so these become <code>$cardNumber[0]</code> and <code>$cardStyle[0]</code>. Add another loop to assign the numbers and styles.</p>\n\n<pre><code>$cardNumbers = array();\n$cardStyles = array();\nforeach ($result as $row) {\n foreach ($CARDS as $cardIndex =&gt; $cardName) {\n if ($row['credit_cards'][$cardIndex] == \"1\") {\n $cardNumbers[$cardIndex] = \"0\";\n $cardStyles[$cardIndex] = 'style=\"opacity: 1; filter: alpha(opacity=100)\"';\n } else {\n $cardNumbers[$cardIndex] = \"1\";\n $cardStyles[$cardIndex] = 'style=\"opacity: 0.25; filter: alpha(opacity=25)\"';\n }\n }\n}\n</code></pre>\n\n<p>Without seeing how the numbers and styles are used, I may have gotten the above wrong. What exactly does <code>$result</code> hold? What is in each <code>$row</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T02:57:40.447", "Id": "4568", "Score": "0", "body": "Wow! That really did shorten the code up tremendously while still doing the same thing. Exactly what I was looking for, I knew I was approaching it the wrong way. Thank you so much. Do you have a method of shortening the bottom part with the cardNumber and cardStyle?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T05:34:55.490", "Id": "4569", "Score": "0", "body": "@Drew - See my update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T12:29:50.133", "Id": "4575", "Score": "0", "body": "Thank you! Now I am starting to understand. Yeah, $result just holds what is in each row." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T02:07:07.173", "Id": "3011", "ParentId": "3010", "Score": "2" } }, { "body": "<p>Why do you store credit cards data in the database ? What is the purpose of this information?</p>\n\n<p>You should use CSS classes in your code:</p>\n\n<pre><code>.deselected {\n opacity: 0.25; filter: alpha(opacity=25)\n}\n</code></pre>\n\n<p>The selected cards need no additional style, HTML elements are already fully opaque.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:39:59.450", "Id": "4583", "Score": "0", "body": "Thank you! That is true, that will help shorten up that part of the code a lot. The page that I posted is a settings page that clients can log in and see - so they choose themselves which credit cards they want to appear on their website. Their website is dynamically created, so it searches the database to get which cards that specific user has selected and it shows the appropriate ones. Does that make sense? Is there a better way of doing it?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:48:11.410", "Id": "3026", "ParentId": "3010", "Score": "0" } } ]
{ "AcceptedAnswerId": "3011", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T00:42:05.773", "Id": "3010", "Score": "1", "Tags": [ "php", "mysqli", "finance" ], "Title": "Adding credit cards to a database" }
3010
<p>Over the last months I have been writing a jQuery plugin called <strong>Better Autocomplete</strong> (<a href="https://github.com/betamos/Better-Autocomplete">Code on Github</a>). It originated from another project, a Drupal module called Linkit, but I decided it should be a standalone plugin. I have spent a lot of time refactoring the code, mainly to make it more generic and flexible for multiple purposes. I have now reached a point where it makes sense to actually ask for advice on the code, hopefully by professional, more experienced JavaScript developers.</p> <p>EDIT: I read in the FAQ that I'm supposed to include some of the code. This is a shorter version of the code, describing the structure of the code. There is also <a href="http://betamos.se/better-autocomplete/index.html">documentation available</a>.</p> <pre><code>(function ($) { $.fn.betterAutocomplete = function(method) { var methods = { init: function(resource, options, callbacks) { var $input = $(this), bac = new BetterAutocomplete($input, resource, options, callbacks); $input.data('better-autocomplete', bac); bac.enable(); }, enable: function(bac) { bac.enable(); }, disable: function(bac) { bac.disable(); }, destroy: function(bac) { bac.destroy(); } }; var args = Array.prototype.slice.call(arguments, 1); // Method calling logic this.filter(':input[type=text]').each(function() { switch (method) { // ... Code here } }); // Maintain chainability return this; }; // This is the constructor function. Instantiated by using the new keyword var BetterAutocomplete = function($input, resource, options, callbacks) { options = $.extend({ charLimit: 3, // More options }, options); /** * These callbacks are supposed to be overridden by you when you need * customization of the default behavior. When you are overriding a callback * function, it is a good idea to copy the source code from the default * callback function, as a skeleton. */ callbacks = $.extend({ /** * Gets fired when the user selects a result by clicking or using the * keyboard to select an element. * * &lt;br /&gt;&lt;br /&gt;&lt;em&gt;Default behavior: Simply blurs the input field.&lt;/em&gt; * * @param {Object} result * The result object that was selected. */ select: function(result) { $input.blur(); }, // ... More callbacks for fetching data, parsing results etc. } var self = this, lastRenderedQuery = '', results = {}, // Caching database of search results. // ... More private instance variables // Create the DOM elements necessary and attach eventhandlers var $wrapper = $('&lt;div /&gt;') .addClass('better-autocomplete') .insertAfter($input); // Public methods this.enable = function() { ... }; // Then private methods var fetchResults = function() { ... }; var getHighlighted = function() { ... }; }; }(jQuery); </code></pre> <p>Some hands on questions:</p> <ol> <li>Does my design patterns look good? I am talking about modularity, namespacing, closures etc.</li> <li>How can I stand out more from jQuery UI autocomplete and other existing plugins? What can I provide that they can't? Also, where can I reach the people who need this plugin?</li> <li>Documentation. I have been using JSDoc toolkit but it is sometimes hard to understand. I have a few warnings when I generate the docs. Also I'm unsure about if I have correctly labeled functions, constructors etc. Can I improve it?</li> </ol> <p>I can take criticism, so don't be shy, rather be honest.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T03:03:24.410", "Id": "4738", "Score": "1", "body": "Firstly: I can't help with JSDoc and i'm not a very experienced jQuery plugin Developer but on #2 I think you should be asking the users of your plugin. Provide an email/discussion board/whatever as they are the ones who know what is needed. Maybe ask them specific questions like what have they done to extend your plugin etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-10T06:44:28.020", "Id": "17143", "Score": "1", "body": "I do not want to put a damper on the work you have done, but I think that your hard work is better put helping one of the established projects become better other than starting a new fork. Just my $0.02" } ]
[ { "body": "<p>You should strongly consider using a JS templating language such as Handlebars.js when rendering the interface.</p>\n\n<pre><code> // Add the group if it doesn't exist\n var group = callbacks.getGroup(result);\n if ($.type(group) == 'string' &amp;&amp; !groups[group]) {\n var $groupHeading = $('&lt;li /&gt;').addClass('group')\n .append($('&lt;h3 /&gt;').html(group))\n .appendTo($results);\n groups[group] = $groupHeading;\n }\n\n var $result = $('&lt;li /&gt;').addClass('result')\n .append(output)\n .data('result', result) // Store the result object on this DOM element\n .addClass(result.addClass);\n</code></pre>\n\n<p>You are doing enough dom manipulation to warrant its use (above is just one part of your code). Furthermore, templates will help separate presentation logic from your business logic which at the moment is quite tangled.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T06:55:10.470", "Id": "12570", "ParentId": "3012", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T03:24:04.807", "Id": "3012", "Score": "22", "Tags": [ "javascript", "jquery" ], "Title": "Writing a better alternative to jQuery Autocomplete" }
3012
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-23.html" rel="nofollow">SICP</a>:</p> <blockquote> <p>Exercise 3.47. A semaphore (of size n) is a generalization of a mutex. Like a mutex, a semaphore supports acquire and release operations, but it is more general in that up to n processes can acquire it concurrently. Additional processes that attempt to acquire the semaphore must wait for release operations. Give implementations of semaphores</p> <p>a. in terms of mutexes</p> </blockquote> <pre><code>(define (make-semaphore max) (let ((count 0) (the-mutex (make-mutex))) (define (increment) (set! count (+ count 1))) (define (decrement) (set! count (- count 1))) (define (has-room?) (&gt; max count)) (define (the-semaphore m) (cond ((eq? m 'acquire) (if (has-room?) (increment) (the-mutex 'acquire))) ((eq? m 'release) (decrement) (if (has-room?) (the-mutex 'release))))) the-semaphore)) </code></pre> <p>I wrote this answer and I'm hoping to find out if it is correct, and how it can be improved. Thank you for your time.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T05:57:36.740", "Id": "3013", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Write a definition of a semaphore in terms of mutexes" }
3013
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-23.html" rel="nofollow">SICP</a>:</p> <blockquote> <p>Exercise 3.47. A semaphore (of size n) is a generalization of a mutex. Like a mutex, a semaphore supports acquire and release operations, but it is more general in that up to n processes can acquire it concurrently. Additional processes that attempt to acquire the semaphore must wait for release operations. Give implementations of semaphores</p> <p>b. in terms of atomic test-and-set! operations.</p> </blockquote> <pre><code>(define (make-semaphore max) (let ((count 0) (cell (list false))) (define (increment) (set! count (+ count 1))) (define (decrement) (set! count (- count 1))) (define (has-room?) (&gt; max count)) (define (the-semaphore m) (cond ((eq? m 'acquire) (if (has-room?) (increment) (if (test-and-set! cell) (the-semaphore 'acquire)))) ((eq? m 'release) (decrement) (if (has-room?) (clear! cell))))) the-semaphore)) (define (clear! cell) (set-car! cell false)) (define (test-and-set! cell) (if (car cell) true (begin (set-car! cell true) false))) </code></pre> <p>Do you think that this solution is sufficient? Can it be improved?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T06:06:43.133", "Id": "3014", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Write a definition of a semaphore in terms of test-and-set! operations" }
3014
<p>I have a file containing one long line:</p> <pre><code>"name surname" &lt;name.surname@example.com&gt;, 'name surname' &lt;name.surname@example.com&gt;, name surname &lt;name.surname@example.com&gt;, "'name surname'" &lt;name.surname@example.com&gt;, surname, &lt;name.surname@example.com&gt;, name &lt;name.surname@example.com&gt; </code></pre> <p>Note that that's 6 different forms.</p> <p>I am splitting each email address into its own line, and saving the results into another file:</p> <pre><code>import sys ifile = sys.argv[1] ofile = sys.argv[2] with open(ifile) as ifile, open(ofile, "w") as ofile: addresses = ifile.readline().split("&gt;,") for n, address in enumerate(addresses): address = address.replace("'", "") address = address.replace('"', "") name, address = address.split("&lt;") address = "&lt;" + address if len(name) &gt; 1: name = name.strip() name = '"{}" '.format(name) address = "".join(name + address) if n &lt; len(addresses) - 1: ofile.write(address.strip() + "&gt;\n") else: ofile.write(address.strip() + "\n") </code></pre> <p>Feels to me like hackery so am looking for a better solution.</p>
[]
[ { "body": "<p>Why are you first removing the quotes and then putting them back?</p>\n\n<p>And why are you removing the brackets and them putting them back?</p>\n\n<p>This does the same thing, except change ' to \". It also doesn't handle commas in names,\nso if you have that it won't work. In that case I'd probably use a regexp.</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n for address in ifile.readline().split(\",\"):\n ofile.write(address.strip() + '\\n')\n</code></pre>\n\n<p>Update:</p>\n\n<p><code>\"surname, name &lt;name.surname@example.com&gt;\"</code> sucks, and that means your format is inconsistent and not parseable without horrid hacks. In that case your code seems OK, although I'd probably do it differently. I would most likely use a regexp to find all cases of commas that are NOT preceded by > and followed by a space to something else, say chr(128) or something like that. I'd then parse the code with my code above, extract the email from withing the brackets, strip all quotes and brackets from the remander, and replace back chr(128) with commas.</p>\n\n<p>And the lastly write that to the outfile.</p>\n\n<p>The difference there is that I don't try to handle a horrid format, I first try to fix the problems. It makes for cleaner code, IMO.</p>\n\n<p><strong>Update 2:</strong></p>\n\n<p>I instead replaced the commas that <em>should</em> be split on, making it simpler, like so:</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n data = ifile.read()\n data = data.replace('&gt;,', '&gt;\\xF0')\n for line in data.split('\\xF0'):\n name, email = line.split('&lt;')\n email = email.replace('&gt;', '').strip()\n name = name.replace('\"', '').replace(\"'\", \"\").strip()\n ofile.write('\"%s\" &lt;%s&gt;\\n' % (name, email))\n</code></pre>\n\n<p>and then I realized I could simplify it even more:</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n data = ifile.read()\n for line in data.split('&gt;,'):\n name, email = line.split('&lt;')\n email = email.strip()\n name = name.replace('\"', '').replace(\"'\", \"\").strip()\n ofile.write('\"%s\" &lt;%s&gt;\\n' % (name, email))\n</code></pre>\n\n<p>And as this point I'm basically doing what you are doing, but much simplified.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T10:58:56.097", "Id": "4571", "Score": "0", "body": "I'm sorry for forgetting to include the other things that the code must handle. See my updated question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T11:28:41.977", "Id": "4572", "Score": "0", "body": "I put back the single opening bracket because str.split() removes it from the list elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T11:34:22.127", "Id": "4573", "Score": "0", "body": "@Tshepang: Updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:23:41.093", "Id": "4577", "Score": "0", "body": "I'm not see where he indicates that he needs to parse that terrible version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:28:41.277", "Id": "4578", "Score": "0", "body": "There's 2 cases that your code doesn't handle. Run my code and yours and compare the results. Use the given input line to test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:29:46.707", "Id": "4579", "Score": "0", "body": "I prefer that you split the `replace()` functionality into separate lines, for the sake of clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:54:32.963", "Id": "4588", "Score": "0", "body": "@Tshepang: I'm not here to write code for you. I charge $100 and hour for that. You can split that into separate lines yourself. The only difference in output between yours and mine is that you skip the name if it's empty, which I leave as a trivial example for you to handle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:08:53.587", "Id": "4590", "Score": "0", "body": "@LennartRegebro: There is another difference: your code leaves an extra `>` in the output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:11:50.387", "Id": "4592", "Score": "0", "body": "@LennartRegebro: Regarding the $100 thing, it's only fair that you make your code to at least do what mine does, since you are trying to improve it. It makes it easier to compare my code and yours to clearly see the improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:12:47.563", "Id": "4593", "Score": "0", "body": "It's interesting that you didn't implement your solution in regexp. May I ask why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:14:19.903", "Id": "4594", "Score": "0", "body": "Can you comment on my `replace` suggestion. Does it make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:21:43.730", "Id": "4595", "Score": "0", "body": "This was simpler. I have no comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:39:08.860", "Id": "4596", "Score": "0", "body": "It seems I pissed you off. The assumption came due to your mention of money. I didn't mean to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T21:33:39.830", "Id": "4598", "Score": "0", "body": "@Tshepang: No, I just find your follow-up questions weird, including asking me to split the line. You can split the line. There is no requirement that you take my code character by character. And there is nothing to say about that suggestion. If you want to split the line, split the line. I don't understand why you are asking for comments on that. It's like asking for permission to go to the toilet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T22:12:41.293", "Id": "4602", "Score": "0", "body": "@LennartRegebro: Since this is Code Review (my code is already working), we are looking for best practices, and that includes code clarity. That's why I thought it's worth mentioning that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T05:11:44.897", "Id": "4604", "Score": "0", "body": "@Tshepang: That doesn't really explain your questions. Sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T17:45:24.960", "Id": "4677", "Score": "1", "body": "Instead of doing: `name.replace('\"', '').replace(\"'\", \"\").strip()` you should be able to do `name.strip(\"'\\\" \")` for the same effect, see: http://docs.python.org/library/string.html?highlight=strip#string.strip." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T18:09:05.303", "Id": "4679", "Score": "0", "body": "@Kit: Yeah, good point, didn't think of that." } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T10:53:10.070", "Id": "3017", "ParentId": "3016", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T09:35:49.410", "Id": "3016", "Score": "1", "Tags": [ "python" ], "Title": "Splitting one line into multiple ones given a separator" }
3016
<p>Here is my program which creates a linked list and reverses it:</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; struct node { int data; struct node *next; }; struct node *list=NULL; struct node *root=NULL; static int count=0; struct node *create_node(int);//function to create node void travel_list(void); void create_list(int); void reverse_list(void); int main() { int i, j, choice; printf("Enter a number this will be root of tree\n"); scanf("%d", &amp;i); create_list(i); printf("Enter 1 to enter more numbers \n 0 to quit\n"); scanf("%d", &amp;choice); while (choice!=0){ printf("Enter a no for link list\n"); scanf("%d",&amp;i); // printf("going to create list in while\n"); create_list(i); travel_list(); printf("Enter 1 to enter more numbers \n 0 to quit\n"); scanf("%d", &amp;choice); } printf("reversing list\n"); reverse_list(); travel_list(); } // end of function main void create_list (int data) { struct node *t1,*t2; //printf("in fucntion create_list\n"); t1=create_node(data); t2=list; if( count!=0) { while(t2-&gt;next!=NULL) { t2=t2-&gt;next; } t2-&gt;next=t1; count++; } else { root=t1; list=t1; count++; } } struct node *create_node(int data) { struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); temp-&gt;data=data; temp-&gt;next=NULL; // printf("create node temp-&gt;data=%d\n",temp-&gt;data); // printf("the adress of node created %p\n",temp); return temp; } void travel_list(void ) { struct node *t1; t1=list; printf("in travel list\n"); while(t1!=NULL) { printf("%d--&gt;",t1-&gt;data); t1=t1-&gt;next; } printf("\n"); } void reverse_list(void) { struct node *t1,*t2,*t3; t1=list; t2=list-&gt;next; t3=list-&gt;next-&gt;next; int reverse=0; if(reverse==0) { t1-&gt;next=NULL; t2-&gt;next=t1; t1=t2; t2=t3; t3=t3-&gt;next; reverse++; } while(t3!=NULL) { t2-&gt;next=t1; t1=t2; t2=t3; list=t1; travel_list(); t3=t3-&gt;next; } t2-&gt;next=t1; list=t2; } </code></pre> <p>I am posting it for further review if there can be any improvements to the algorithm, etc.</p>
[]
[ { "body": "<p>You should compile with all warnings enabled, e.g. <code>gcc -Wall</code>:</p>\n\n<pre><code>review.c: In function ‘main’:\nreview.c:16: warning: unused variable ‘j’\nreview.c:34: warning: control reaches end of non-void function\n</code></pre>\n\n<p>This tells you that you have an unused variable and that main() is missing a return statement. You should fix these and any other warnings.</p>\n\n<p>You should also pay attention to formatting your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T14:15:06.093", "Id": "3019", "ParentId": "3018", "Score": "2" } }, { "body": "<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\nstruct node {\n int data;\n struct node *next;\n};\nstruct node *list=NULL;\nstruct node *root=NULL;\nstatic int count=0;\n</code></pre>\n\n<p>Don't store data in global variables. It makes your code unreusable and harder to follow.</p>\n\n<pre><code>struct node *create_node(int);//function to create node\nvoid travel_list(void);\nvoid create_list(int);\nvoid reverse_list(void);\nint main()\n{\n int i, j, choice;\n</code></pre>\n\n<p>Using variables like i and j only make sense if used in the sense of indexes. Otherwise, the code just gets harder to read. Choice is also not very informative.</p>\n\n<pre><code> printf(\"Enter a number this will be root of tree\\n\");\n scanf(\"%d\", &amp;i);\n create_list(i);\n printf(\"Enter 1 to enter more numbers \\n 0 to quit\\n\");\n scanf(\"%d\", &amp;choice);\n while (choice!=0){\n printf(\"Enter a no for link list\\n\");\n scanf(\"%d\",&amp;i);\n</code></pre>\n\n<p>Use consistent indentation. Otherwise things will go downhill fast.</p>\n\n<pre><code>// printf(\"going to create list in while\\n\");\n</code></pre>\n\n<p>Don't leave dead code in your code, that's what source control is for.</p>\n\n<pre><code> create_list(i);\n travel_list(); \n printf(\"Enter 1 to enter more numbers \\n 0 to quit\\n\");\n scanf(\"%d\", &amp;choice);\n</code></pre>\n\n<p>Deja vu. Why isn't the previous instance doing the same thing done in the loop?</p>\n\n<pre><code> }\n printf(\"reversing list\\n\");\n reverse_list();\n travel_list();\n }\n\n\n// end of function main\nvoid create_list (int data)\n</code></pre>\n\n<p>This function appends to the end of a list, it doesn't create it. Use function names that indicate what is really happening.</p>\n\n<pre><code>{\n struct node *t1,*t2;\n</code></pre>\n\n<p>t1 and t2 are very uninformative variable names.</p>\n\n<pre><code> //printf(\"in fucntion create_list\\n\");\n t1=create_node(data);\n t2=list;\n if( count!=0)\n</code></pre>\n\n<p>This is the only place that count is used. Check whether list is null instead.</p>\n\n<pre><code> {\n while(t2-&gt;next!=NULL)\n {\n t2=t2-&gt;next;\n }\n t2-&gt;next=t1;\n count++;\n }\n else \n {\n root=t1;\n</code></pre>\n\n<p>You don't ever seem to do anything with root.</p>\n\n<pre><code> list=t1;\n count++;\n }\n}\nstruct node *create_node(int data)\n{\n struct node *temp;\n</code></pre>\n\n<p>The new node isn't really temporary</p>\n\n<pre><code> temp = (struct node *)malloc(sizeof(struct node));\n temp-&gt;data=data;\n temp-&gt;next=NULL;\n // printf(\"create node temp-&gt;data=%d\\n\",temp-&gt;data);\n// printf(\"the adress of node created %p\\n\",temp);\n return temp;\n}\nvoid travel_list(void )\n{\n struct node *t1;\n t1=list;\n printf(\"in travel list\\n\");\n while(t1!=NULL)\n {\n printf(\"%d--&gt;\",t1-&gt;data);\n t1=t1-&gt;next;\n }\n printf(\"\\n\");\n}\nvoid reverse_list(void)\n{\n struct node *t1,*t2,*t3;\n</code></pre>\n\n<p>This piece of code would be way easier to follow if you used real names</p>\n\n<pre><code> t1=list;\n t2=list-&gt;next;\n t3=list-&gt;next-&gt;next; \n</code></pre>\n\n<p>This is going to fail for lists shorter then three elements</p>\n\n<pre><code> int reverse=0;\n if(reverse==0)\n</code></pre>\n\n<p>This will always be true since you just assigned reverse = 0.</p>\n\n<pre><code> {\n t1-&gt;next=NULL;\n t2-&gt;next=t1;\n t1=t2;\n t2=t3;\n t3=t3-&gt;next;\n reverse++;\n</code></pre>\n\n<p>You never use reverse again</p>\n\n<pre><code> }\n\n\n while(t3!=NULL)\n {\n\n t2-&gt;next=t1;\n t1=t2;\n t2=t3;\n list=t1;\n travel_list();\n t3=t3-&gt;next;\n }\n t2-&gt;next=t1;\n list=t2;\n}\n</code></pre>\n\n<p>My version of reverse_list (untested)</p>\n\n<pre><code>struct node * reverse_list(struct node * list)\n{\n struct node *previous, *current;\n previous = NULL;\n current = list;\n while(current)\n {\n struct node * next = current-&gt;next;\n current-&gt;next = previous;\n previous = current;\n current = next;\n }\n return previous;\n}\n</code></pre>\n\n<p>}</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:11:24.030", "Id": "4591", "Score": "0", "body": "What, no recursion? ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T15:40:17.220", "Id": "3022", "ParentId": "3018", "Score": "7" } }, { "body": "<p>here is LinkedList class I implemented using c++ templates.\nalso I implemented reverse and sorting linked list by merge sort</p>\n\n<pre><code>template &lt;class T&gt;\nvoid LinkedList&lt;T&gt;::reverseList()\n{\n Node&lt;T&gt; *curr = head, *prev = head, *save = NULL;\n\n while (curr)\n {\n save = curr-&gt;next;\n curr-&gt;next = prev;\n prev = curr;\n curr = save;\n }\n\n head-&gt;next = NULL;\n head = prev;\n}\n</code></pre>\n\n<p><a href=\"https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/ds/LinkedList.cpp\" rel=\"nofollow\">https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/ds/LinkedList.cpp</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T13:09:26.560", "Id": "4577", "ParentId": "3018", "Score": "0" } }, { "body": "<p>This is my version in C-language. I am reusing the root node instead of an extra node since it is manipulated with in the function and will not change globally. Also, look at the way I am returning the head, once the entire reversal of the list is complete. This is perfectly valid, the passing and returning of a struct by functions in C, and you can use it to get rid of global variables.</p>\n\n<pre><code>node *reverselinklist(node *root)\n{\nnode *pre,*cur;\npre='\\0';\nwhile(root!='\\0')\n{\ncur=root-&gt;next;\nroot-&gt;next=pre;\npre=root;\nroot=cur;\n\n}\nreturn pre;\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T18:03:48.967", "Id": "7848", "ParentId": "3018", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T13:17:11.713", "Id": "3018", "Score": "4", "Tags": [ "c", "linked-list" ], "Title": "Creating and reversing a linked list" }
3018
<p>I'm using this pattern for the first time and wanted to check if this is the correct implementation.</p> <p><strong>class.validator.strategy.php</strong></p> <pre><code>abstract class ValidatorStrategy { abstract public function check( $name, $val ); } </code></pre> <p><strong>class.text.validator.php</strong></p> <pre><code>class TextValidator extends ValidatorStrategy { public function check( $name, $val ) { //logic here } } </code></pre> <p><strong>class.number.validator.php</strong></p> <pre><code>class NumberValidator extends ValidatorStrategy { public function check( $name, $val ) { //logic here } } </code></pre> <p><strong>class.validator.php</strong> </p> <pre><code>include('validator.strategy.php'); include('class.text.validator.php'); include('class.number.validator.php'); include('class.email.validator.php'); class Validator { //holds strategy object protected $validatorStrategy = array(); //holds form field protected $fields = array(); public function __construct() { $this-&gt;validatorStrategy[ 'text' ] = new TextValidator(); $this-&gt;validatorStrategy[ 'number' ] = new NumberValidator(); $this-&gt;validatorStrategy[ 'email' ] = new EmailValidator(); } public function ruleForTextField( $name, $value ) { $this-&gt;fields[ $name ][ 'value' ] = $value; $this-&gt;fields[ $name ][ 'type' ] = 'text'; } public function ruleForNumbertField( $name, $value ) { $this-&gt;fields[ $name ][ 'value' ] = $value; $this-&gt;fields[ $name ][ 'type' ] = 'number'; } public function ruleForEmailField( $name, $value ) { $this-&gt;fields[ $name ][ 'value' ] = $value; $this-&gt;fields[ $name ][ 'type' ] = 'email'; } public function isValidate() { $status = 0; foreach ( $this-&gt;fields as $key =&gt; $val ) { if ( !$this-&gt;validatorStrategy[ $val[ 'type' ] ]-&gt;check( $key, $val ) ) { $status++; } if ( $status == 0 ) { return true; } else { return false; } } } </code></pre> <p><br/> <strong>Uses:</strong></p> <pre><code>$validator = new Validator(); $validator-&gt;ruleForTextField('username', $_POST['username'] ); $validator-&gt;ruleForNumberField('age', $_POST['age'] ); $validator-&gt;ruleForEmailField('email', $_POST['email'] ); if($validator-&gt;isValidate()) { echo 'validated'; } else { echo 'fail validation'; } </code></pre> <p>Inside the <code>isValidate()</code> method, it iterate against all validator strategy and perform appropriate logic.</p> <p>Is this is the correct way to use this pattern? </p>
[]
[ { "body": "<p>I don't write php, so please bear with me; but I don't care for the isValidate method. In pseudo-code... I usually write something like</p>\n\n<pre><code>foreach(var validator in validatorCollection)\n if validator-&gt;Check = false\n return false\n\nreturn true\n</code></pre>\n\n<p>Also, some of the method names are a bit unclear. A list of names I'd prefer to see...</p>\n\n<ul>\n<li>IsValid rather than Check</li>\n<li>IsValid rather than IsValidate</li>\n</ul>\n\n<p>Additionally, I think your example is a poor one for the usage of the strategy pattern, but I'm assuming that's because it is a simple sample problem. </p>\n\n<p>As and example, we use the strategy pattern to determine shipping methods for packages. We have a validator for UPS, and a validator for USPS, and a validator for FedEx. We pass a package object to each of the validators to determine eligibility. Each of those validators has a list of rules (weight, height, hazardous materials, etc) to determine if that package can be shipped that method.</p>\n\n<pre><code>ListOfCarriers result\nListOfCarriers carriers\nforeach(carrier in carriers)\n if(carrier.canShip(package)\n result.add(carrier)\nreturn result\n</code></pre>\n\n<p>A carrier's canShip method might look like...</p>\n\n<pre><code>function canShip(package)\n return weightRule.Applies(package)\n and heightRule.Applies(package)\n and hazmatRule.Applies(package)\n</code></pre>\n\n<p>and the weightRule might look like...</p>\n\n<pre><code>function Applies(package)\n return package.weight &lt; 70.0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:10:46.040", "Id": "4581", "Score": "0", "body": "thx for ur explaination" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T16:59:20.850", "Id": "3024", "ParentId": "3021", "Score": "1" } }, { "body": "<p>I am not sure this is really a strategy pattern: you never rely on the <code>ValidatorStrategy</code> interface, there is no real choice of a strategy (there are direct calls to <code>Validator</code> methods) and you cannot add another strategy without braking your context object (<code>Validator</code> class).</p>\n\n<p>What you can do is refactor <code>Validator</code> to inject a <code>ValidatorStrategy</code> instance for each field to validate. Let call this modified class <code>FormValidator</code> (a <code>Validator</code> instance validates one field only) and see how it can be implemented:</p>\n\n<pre><code>class FormValidator\n{\n /**\n * @var array of StrategyValidator\n */\n protected $validators;\n\n /**\n *\n * @param string $name\n * @param ValidatorStrategy $strategy \n */\n public function addValidator($name, ValidatorStrategy $strategy)\n {\n $this-&gt;validators[$name] = $strategy;\n }\n\n /**\n *\n * @param array $form \n */\n public function isValid($form)\n {\n foreach ($this-&gt;validators as $name =&gt; $validator)\n {\n if (!$validator-&gt;isValid($form[$name]))\n {\n return false;\n }\n }\n\n return true;\n }\n}\n\n$formValidator = new FormValidator();\n$formValidator-&gt;addValidator('username', new TextValidator());\n$formValidator-&gt;addValidator('age', new NumberValidator());\n$formValidator-&gt;addValidator('email', new EmailValidator());\n\n// Now you can reuse $formValidator where you want\n$values = array(\n 'username' =&gt; $_POST['username'],\n 'age' =&gt; $_POST['age'],\n 'email' =&gt; $_POST['email'],\n);\n\nif($formValidator-&gt;isValid($values))\n{\n echo 'validated';\n}\nelse\n{\n echo 'fail validation';\n}\n</code></pre>\n\n<p>Some advices:</p>\n\n<ul>\n<li>John Kraft's naming advices are excellent, you should follow them: a method starting with is*, has* returns a boolean, methods starting with get* and set* are accessors, etc.</li>\n<li>Always take a moment to think about you classes role, and deduce their name from it</li>\n<li>When manipulating booleans, use boolean vars ($status)</li>\n<li>When using <code>new Myclass()</code> in a class method, ask yourself if you are not closing the classes to future evolution, especially if MyClass implements an interface: this is a sign that the class can vary and we should rely on the interface instead (see <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">Dependency Injection</a>)</li>\n</ul>\n\n<p>This last advice is illustrated by the method <code>addValidator()</code> in my example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:07:30.020", "Id": "4580", "Score": "0", "body": "thx for ur explaination, it really help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:35:40.353", "Id": "3025", "ParentId": "3021", "Score": "2" } }, { "body": "<p>No, strategy pattern relies on an interface to allow composition to determine functionality at run time. Notice that it is easier to extend with new speaking functionality; and can be used to execute at run time. Here you are just using the array of the interface instantiations to do multiple validations.</p>\n\n<p>I.E.</p>\n\n<p>Interface for the pattern</p>\n\n<pre><code>public interface Speak {\n public void execute();\n}\n</code></pre>\n\n<p>Implementations of the pattern</p>\n\n<pre><code>public class Quack extends Speak {\n public void execute() { /* Quack */ }\n}\n\npublic class Bark extends Speak {\n public void execute() { /* bark */ }\n}\n</code></pre>\n\n<p>Class that uses the strategy</p>\n\n<pre><code>public Animal {\n private Speak _speak;\n public Animal(Speak s) { _speak = s; }\n}\n</code></pre>\n\n<p>Example usage</p>\n\n<pre><code>main() {\n new Animal(new Bark()); /* creates animal that barks */\n new Animal(new Quack()); /* creates animal that quacks */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T02:42:13.470", "Id": "4584", "Score": "1", "body": "@Suroot - Your way is the normative way of using a strategy pattern, but the OPs solution is very interesting, in that he can easily extend what he can validate by just implementing his interface and adding it to his array, so, he isn't having multiple classes changing what they are doing, but the basic concept of what he is doing is still present." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T02:47:15.867", "Id": "4585", "Score": "0", "body": "His use is more of a lookup style pattern; I'm not sure if there is a design pattern already created for this; but it does not appear to be strategy. Strategy has one interface and multiple instantiations of that interface followed by one or more classes that contain ONE of those instantiations to give the illusion that the class is changing implementation at run time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T14:37:05.087", "Id": "4586", "Score": "0", "body": "@Suroot yes i can implement classic strategy pattern but that will force my application code to instantiate all related class.Let say i need to validate 4 type of validation, my application code need to instantiate 4 time validator class...i dont want to force this in my application code..thats why my code en up like that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T15:17:34.943", "Id": "4587", "Score": "0", "body": "@suroot see update, is that more like strategy pattern?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T01:56:01.760", "Id": "3029", "ParentId": "3021", "Score": "4" } } ]
{ "AcceptedAnswerId": "3025", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T15:30:05.320", "Id": "3021", "Score": "3", "Tags": [ "php", "design-patterns", "validation", "email" ], "Title": "Email text validator" }
3021
<p>I would like your thoughts on my database structure. I am kind of a rookie but I am trying. All of your suggestions, alternatives, ideas, additions are welcome. Thank you.</p> <pre><code>CREATE TABLE `buy` ( `PurchaseID` int(10) unsigned NOT NULL AUTO_INCREMENT, `PurchaseTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `CashMachineCode` int(10) unsigned NOT NULL, PRIMARY KEY (`PurchaseID`), KEY `CashMachineCode` (`CashMachineCode`), CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`CashMachineCode`) REFERENCES `cashmachine` (`CashMachineCode`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `buying` ( `CustomerID` int(10) unsigned NOT NULL, `PurchaseID` int(10) unsigned NOT NULL, PRIMARY KEY (`CustomerID`,`PurchaseID`), KEY `PurchaseID` (`PurchaseID`), CONSTRAINT `buying_ibfk_1` FOREIGN KEY (`CustomerID`) REFERENCES `customer` (`CreditCardCode`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `buying_ibfk_2` FOREIGN KEY (`PurchaseID`) REFERENCES `buy` (`PurchaseID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `shift` ( `CashierCode` int(10) unsigned NOT NULL, `CashMachineCode` int(10) unsigned NOT NULL, `ShiftStart` time NOT NULL, `ShiftEnd` time DEFAULT NULL, PRIMARY KEY (`CashierCode`,`CashMachineCode`,`ShiftStart`), KEY `CashMachineCode` (`CashMachineCode`), CONSTRAINT `shift_ibfk_1` FOREIGN KEY (`CashierCode`) REFERENCES `employee` (`EmployeeID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `shift_ibfk_2` FOREIGN KEY (`CashMachineCode`) REFERENCES `cashmachine` (`CashMachineCode`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `availability` ( `ShopID` int(10) unsigned NOT NULL, `ProductID` int(10) unsigned NOT NULL, PRIMARY KEY (`ProductID`,`ShopID`), KEY `ShopID` (`ShopID`), CONSTRAINT `availability_ibfk_1` FOREIGN KEY (`ShopID`) REFERENCES `shop` (`ShopID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `availability_ibfk_2` FOREIGN KEY (`ProductID`) REFERENCES `product` (`ProductID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `director` ( `EmployeeID` int(10) unsigned NOT NULL, PRIMARY KEY (`EmployeeID`), CONSTRAINT `director_ibfk_1` FOREIGN KEY (`EmployeeID`) REFERENCES `employee` (`EmployeeID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `WorksOn` ( `EmployeeID` int(10) unsigned NOT NULL, `ShopID` int(10) unsigned NOT NULL, PRIMARY KEY (`EmployeeID`), KEY `ShopID` (`ShopID`), CONSTRAINT `WorksOn_ibfk_1` FOREIGN KEY (`EmployeeID`) REFERENCES `employee` (`EmployeeID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `WorksOn_ibfk_2` FOREIGN KEY (`ShopID`) REFERENCES `shop` (`ShopID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `shop` ( `ShopID` int(10) unsigned NOT NULL AUTO_INCREMENT, `Name` varchar(45) DEFAULT NULL, `Address` varchar(100) DEFAULT NULL, PRIMARY KEY (`ShopID`) ) CREATE TABLE `customer` ( `CreditCardCode` int(10) unsigned NOT NULL AUTO_INCREMENT, `CustomerName` varchar(45) DEFAULT NULL, `CustomerSurname` varchar(45) DEFAULT NULL, `Address` varchar(100) DEFAULT NULL, PRIMARY KEY (`CreditCardCode`) ) CREATE TABLE `contains` ( `PurchaseID` int(10) unsigned NOT NULL, `ProductID` int(10) unsigned NOT NULL, `Quantity` int(10) unsigned NOT NULL, `ProductPrice` decimal(10,2) unsigned NOT NULL, PRIMARY KEY (`PurchaseID`,`ProductID`), KEY `ProductID` (`ProductID`), CONSTRAINT `contains_ibfk_1` FOREIGN KEY (`PurchaseID`) REFERENCES `buy` (`PurchaseID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `contains_ibfk_2` FOREIGN KEY (`ProductID`) REFERENCES `product` (`ProductID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `product` ( `ProductID` int(10) unsigned NOT NULL, `Description` varchar(100) DEFAULT NULL, PRIMARY KEY (`ProductID`) ) CREATE TABLE `cashmachine` ( `CashMachineCode` int(10) unsigned NOT NULL AUTO_INCREMENT, `Number` int(11) NOT NULL, `ShopID` int(10) unsigned NOT NULL, PRIMARY KEY (`CashMachineCode`), KEY `ShopID` (`ShopID`), CONSTRAINT `cashmachine_ibfk_1` FOREIGN KEY (`ShopID`) REFERENCES `shop` (`ShopID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `cashier` ( `EmployeeID` int(10) unsigned NOT NULL, PRIMARY KEY (`EmployeeID`), CONSTRAINT `cashier_ibfk_1` FOREIGN KEY (`EmployeeID`) REFERENCES `employee` (`EmployeeID`) ON DELETE CASCADE ON UPDATE CASCADE ) CREATE TABLE `employee` ( `EmployeeID` int(10) unsigned NOT NULL AUTO_INCREMENT, `EmployeeName` varchar(45) DEFAULT NULL, `EmployeeSurname` varchar(45) DEFAULT NULL, PRIMARY KEY (`EmployeeID`) ) </code></pre>
[]
[ { "body": "<p>Looking at what you have so far, it seems your tables logically fall into two groups: </p>\n\n<ol>\n<li>entity tables </li>\n<li>relationship tables. </li>\n</ol>\n\n<p>It may be easier to read if you define all the entity tables first, then all the relationship tables.</p>\n\n<p>In general, your entity tables are clear as written (employee, cashmachine, product, shop, customer, and buy&lt;--you should rename <code>buy</code> as <code>purchase</code> so it's clearly a noun). The <code>employee</code> table is a particularly clear example. The name of the table tells me that it is a table of employees. Its primary key is sensibly called <code>EmployeeID</code>, and is auto-incrementing.</p>\n\n<p>The change I would recommend is to simplify your relationship tables. In particular, some of the relationships you're defining actually don't need any separate table. For example, <code>cashier</code> and <code>director</code> could just be boolean columns added to the employee table. Similarly, if <code>Purchases-to-Customers</code> is a <code>many-to-one</code> relationship, then <code>CustomerID</code> should be an added column to purchase table, eliminating the need for the 'buying' cross table.</p>\n\n<p>Where a cross table is necessary (I see <code>Products-to-Shops</code> availability is a <code>many-to-many</code> relationship), try to rename it to include the name of at least one of the related entities, such as <code>product_availability</code> instead of <code>availability</code> and <code>purchase_items</code> instead of <code>contains</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T20:23:38.733", "Id": "4597", "Score": "0", "body": "Can you please edit my table end simplify it? At least one or two tables. Thank you very much for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T16:54:26.973", "Id": "4638", "Score": "0", "body": "I understand, the tables `cashier` and `director` are defined to guarantee that only one person can hold the respective attribute (cashier or director). Probably there was no better way to enforce that on the database level." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T02:52:21.417", "Id": "4828", "Score": "0", "body": "@Andriy -- As written there could be any number of people listed in the `cashier` and `director` tables. In real life it might make sense to have many cashiers and one director. With boolean director column this could sort of be enforced with `add column director bool unique`, using True for the only director and NULL for everyone else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T04:40:03.720", "Id": "4830", "Score": "0", "body": "Don't know about MySQL, but such a trick would definitely not work in SQL Server. If there's the unique constraint defined on the column, all its contents must be unique, which means there could only be possible just one NULL. Are you positive it would work in MySQL? As for the many cashiers, well, judging from the schema, this particular company seemed to require there to be just one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T11:45:55.383", "Id": "4838", "Score": "0", "body": "@Andriy -- Interesting. I successfully tested `bool unique` in MySQL, but you're right that [it breaks in MSSQL](http://connect.microsoft.com/SQLServer/feedback/details/299229/change-unique-constraint-to-allow-multiple-null-values). In MSSQL it would be better to use a table-level [check constraint](http://msdn.microsoft.com/en-us/library/ms188258.aspx), which lets you place any constraint criteria you want, but is [not supported my MySQL](http://stackoverflow.com/questions/2115497/check-constraint-in-mysql-not-working)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:13:21.267", "Id": "3027", "ParentId": "3023", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T16:17:34.320", "Id": "3023", "Score": "1", "Tags": [ "sql", "mysql" ], "Title": "Cash Register database structure" }
3023
<p>I'm currently reviewing some standard pieces of code I use a lot in projects.</p> <p>Currently I'm using the following functions for password hashing.</p> <pre><code>function generate_salt($length = 20){ $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'. '0123456789``-=~!@#$%^&amp;*()_+,./&lt;&gt;?;:[]{}\|'; $str = ''; $max = strlen($chars) - 1; for ($i=0; $i &lt; $length; $i++) $str .= $chars[rand(0, $max)]; return $str; } function hash_password($password, $salt, $iter=5) { $hash = sha1(sha1($password.$salt).sha1(strrev($password).strrev($salt))); for($i=0;$i&lt;=$iter;++$i) { $hash = sha1(sha1($hash).sha1(strrev($hash))); } return $hash; } </code></pre> <p>I will replace <code>sha1()</code> with <code>hash('sha512', )</code>.</p> <p>Any other suggestions to make this more secure / to improve it?</p>
[]
[ { "body": "<p>What is the motivation behind hashing and reversing the string multiple times? If you have a secure hash function, then hashing a single time (combined with a sufficient amount of salt data) is perfectly sufficient. If you have an insecure hash function, then hashing multiple times is extraordinarily unlikely to be enough to make it secure.</p>\n\n<p>The only slight security issue I can see in the code you've posted is the possibility that the random number generator will not be properly seeded, or is not a sufficiently secure random number generator. This is extremely unlikely to be a problem, however, since the purpose of salting is not typically undermined by having an insecure random number generator. Provided hashes get salt values that are reasonably well-distributed it won't help an attacker. If your attacker can interfere with the timing of password creation somehow, to ensure that the majority of users ended up with exactly the same salt, then this would render a dictionary attack easier at a later date, provided they could obtain the hashed passwords. In reality, any user who has this level of control over your system has probably got lots of other ways to obtain the passwords.</p>\n\n<p>Which is of course the real point. Don't spend a lot of time trying to make your hash function cleverer or more secure, just make sure that it does its job. Spend the rest of your time looking over the rest of the system for any chinks in the armour. The system is only as strong as the weakest link in the chain, and that's unlikely to be the hash function. For example, maybe you store the unhashed function in the PHP session, and your server is misconfigured so that the session data is readable by other users on the same box. Maybe you forgot to configure HTTPS so the site is vulnerable to packet sniffers. Maybe your box got rooted and the attacker changed your PHP, so even though the code in your repository is flawless, all your users are compromised.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T21:24:52.723", "Id": "3033", "ParentId": "3030", "Score": "2" } }, { "body": "<p>I would just like to point something out. I realize that this question was written three years ago, however it's important to know the current standard.</p>\n\n<p>If you stumbled upon this question looking for a user password hashing function, <strong>do not use the original post's code!</strong></p>\n\n<p>Instead, update your PHP version to the most recent version if you can, and begin to implement the <a href=\"http://php.net/manual/en/function.password-hash.php\" rel=\"nofollow\"><code>password_hash()</code></a> function.</p>\n\n<blockquote>\n <p><code>password_hash()</code> creates a new password hash using a strong one-way hashing algorithm. <code>password_hash()</code> is compatible with <code>crypt()</code>.</p>\n</blockquote>\n\n<p>It automatically handles salting, and it's incredibly easy to implement <a href=\"http://php.net/manual/en/function.password-verify.php\" rel=\"nofollow\"><code>password_verify()</code></a> for authentication.</p>\n\n<hr>\n\n<p>Using this function completely eliminates each line of code in the original post!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-30T20:36:47.560", "Id": "58563", "ParentId": "3030", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:39:01.777", "Id": "3030", "Score": "2", "Tags": [ "php", "security" ], "Title": "Reviewing password hashing functions" }
3030
<p>I tried a <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataYahtzee" rel="nofollow">Yahtzee kata</a> in Python the other day. I'm not particularly experienced in Python (C# is my main language) so I'd be interested in any feedback as to how I could have done things better. In particular, I wonder whether my <code>Count</code> and <code>HighestRepeated</code> methods could be a little more elegant.</p> <pre><code>import unittest #helpers def Count(dice, number): return len([y for y in dice if y == number]) def HighestRepeated(dice, minRepeats): unique = set(dice) repeats = [x for x in unique if Count(dice, x) &gt;= minRepeats] return max(repeats) if repeats else 0 def OfAKind(dice, n): return HighestRepeated(dice,n) * n def SumOfSingle(dice, selected): return sum([x for x in dice if x == selected]) #strategies def Chance(dice): return sum(dice) def Pair(dice): return OfAKind(dice, 2) def ThreeOfAKind(dice): return OfAKind(dice, 3) def FourOfAKind(dice): return OfAKind(dice, 4) def SmallStraight(dice): return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0 def LargeStraight(dice): return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0 def Ones(dice): return SumOfSingle(dice,1) def Twos(dice): return SumOfSingle(dice,2) def Threes(dice): return SumOfSingle(dice,3) def Fours(dice): return SumOfSingle(dice,4) def Fives(dice): return SumOfSingle(dice,5) def Sixes(dice): return SumOfSingle(dice,6) def Yahtzee(dice): return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0 class YahtzeeTest(unittest.TestCase): testCases = ( ((1,2,3,4,5), 1, Ones), ((1,2,3,4,5), 2, Twos), ((3,2,3,4,3), 9, Threes), ((3,2,3,4,3), 0, Sixes), ((1,2,3,4,5), 0, Pair), # no pairs found ((1,5,3,4,5), 10, Pair), # one pair found ((2,2,6,6,4), 12, Pair), # picks highest ((2,3,1,3,3), 6, Pair), # only counts two ((2,2,6,6,6), 18, ThreeOfAKind), ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three ((6,2,6,6,6), 24, FourOfAKind), ((2,6,4,6,6), 0, FourOfAKind), # no fours found ((5,5,5,5,5), 20, FourOfAKind), # only counts four ((1,2,5,4,3), 15, SmallStraight), ((1,2,5,1,3), 0, SmallStraight), ((6,2,5,4,3), 20, LargeStraight), ((1,2,5,1,3), 0, LargeStraight), ((5,5,5,5,5), 50, Yahtzee), ((1,5,5,5,5), 0, Yahtzee), ((1,2,3,4,5), 15, Chance), ) def testRunAll(self): for (dice, expected, strategy) in self.testCases: score = strategy(dice) self.assertEquals(expected, score, "got {0} expected {1}, testing with {2} on {3}".format(score, expected, strategy.__name__, dice)) print 'ran {0} test cases'.format(len(self.testCases)) if __name__ == '__main__': unittest.main() </code></pre>
[]
[ { "body": "<pre><code>import unittest\n\n#helpers\ndef Count(dice, number):\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for global functions.</p>\n\n<pre><code> return len([y for y in dice if y == number])\n</code></pre>\n\n<p>This can be written as</p>\n\n<pre><code> return dice.count(number)\n\ndef HighestRepeated(dice, minRepeats):\n unique = set(dice)\n repeats = [x for x in unique if Count(dice, x) &gt;= minRepeats]\n return max(repeats) if repeats else 0\n</code></pre>\n\n<p>This will be somewhat clearer if you find the highest repeated count and then check it against minRepeats. You can also use the counter class:</p>\n\n<pre><code>counts = collections.Counter(dice)\nelement, count = counts.most_common()[0]\nreturn count if minRepeats &lt;= count else 0\n\n\ndef OfAKind(dice, n):\n return HighestRepeated(dice,n) * n\n\ndef SumOfSingle(dice, selected):\n return sum([x for x in dice if x == selected])\n</code></pre>\n\n<p>Could be written as</p>\n\n<pre><code> return collections.Counter(dice)[selected]\n\n#strategies\ndef Chance(dice):\n return sum(dice)\n\ndef Pair(dice):\n return OfAKind(dice, 2)\n\ndef ThreeOfAKind(dice):\n return OfAKind(dice, 3)\n\ndef FourOfAKind(dice):\n return OfAKind(dice, 4)\n\ndef SmallStraight(dice):\n return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0\n</code></pre>\n\n<p>Shouldn't a small straight consist of 4 elements in a row?</p>\n\n<pre><code>def LargeStraight(dice):\n return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0\n</code></pre>\n\n<p>Can't a large straight start with 1?</p>\n\n<pre><code>def Ones(dice):\n return SumOfSingle(dice,1)\n\ndef Twos(dice):\n return SumOfSingle(dice,2)\n\ndef Threes(dice):\n return SumOfSingle(dice,3)\n\ndef Fours(dice):\n return SumOfSingle(dice,4)\n\ndef Fives(dice):\n return SumOfSingle(dice,5)\n\ndef Sixes(dice):\n return SumOfSingle(dice,6)\n</code></pre>\n\n<p>Writing so many functions that differ only in a parameter they pass to another function is odd. </p>\n\n<pre><code>def Yahtzee(dice):\n return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0\n</code></pre>\n\n<p>Can't you assume that there are always 5 dice? Also, why don't you use OfAKind?</p>\n\n<pre><code>class YahtzeeTest(unittest.TestCase):\n testCases = (\n ((1,2,3,4,5), 1, Ones),\n ((1,2,3,4,5), 2, Twos),\n ((3,2,3,4,3), 9, Threes),\n ((3,2,3,4,3), 0, Sixes),\n ((1,2,3,4,5), 0, Pair), # no pairs found\n ((1,5,3,4,5), 10, Pair), # one pair found\n ((2,2,6,6,4), 12, Pair), # picks highest\n ((2,3,1,3,3), 6, Pair), # only counts two\n ((2,2,6,6,6), 18, ThreeOfAKind), \n ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found\n ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three\n ((6,2,6,6,6), 24, FourOfAKind), \n ((2,6,4,6,6), 0, FourOfAKind), # no fours found\n ((5,5,5,5,5), 20, FourOfAKind), # only counts four\n ((1,2,5,4,3), 15, SmallStraight),\n ((1,2,5,1,3), 0, SmallStraight),\n ((6,2,5,4,3), 20, LargeStraight),\n ((1,2,5,1,3), 0, LargeStraight),\n ((5,5,5,5,5), 50, Yahtzee),\n ((1,5,5,5,5), 0, Yahtzee), \n ((1,2,3,4,5), 15, Chance),\n )\n\n def testRunAll(self):\n for (dice, expected, strategy) in self.testCases:\n score = strategy(dice)\n self.assertEquals(expected, score, \"got {0} expected {1}, testing with {2} on {3}\".format(score, expected, strategy.__name__, dice))\n print 'ran {0} test cases'.format(len(self.testCases))\n</code></pre>\n\n<p>You are duplicating some of the logic of the unit test system here. I recommend using nose tests which would allow this one function to generate a number of tests each of which is considered an independent test by the unit testing system. Then you wouldn't need to spend so much effort.</p>\n\n<p>I'd also consider writing functions for each of your tests rather then putting them in a huge list. The list technique is really nice but its best used for calling the same function. Using it to test so many different functions is odd. </p>\n\n<pre><code>if __name__ == '__main__':\n unittest.main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T05:46:45.207", "Id": "4605", "Score": "0", "body": "Thanks, some really good suggestions there - I knew there had to be a better way to do my count function. As far as I can tell, the large and small straights are what the kata wiki specifies - although it may have got the yahtzee rules wrong. I'll give nose a try - I was looking for an equivalent to the NUnit TestCase attribute which I find very useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T07:52:51.330", "Id": "4606", "Score": "0", "body": "You only score a Yahtzee if you roll five of a kind. Assuming these functions are used to score the remaining dice after saving some to be scored, they need to correctly score fewer than five dice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T22:04:52.517", "Id": "4625", "Score": "0", "body": "@Mark, yeah your source does seem to indicate those rules for straights. It looks like it results from a misunderstanding of the original rules. However, the rules for a real straight might be a more interesting implementation challenge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T22:05:39.740", "Id": "4626", "Score": "0", "body": "@David, that's not how I remember Yahtzee working. (i.e. you can only score one category at a time.) But in that case yes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T23:24:50.497", "Id": "3037", "ParentId": "3036", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T22:02:40.530", "Id": "3036", "Score": "7", "Tags": [ "python", "game", "programming-challenge", "playing-cards", "dice" ], "Title": "Yahtzee Code Kata in Python" }
3036
<p>I've knocked together a few lines of python to read in stats for a service (haproxy), and store them in an array (to do some analysis on later). It basically takes a multiline output, and splits it into multiple subarrays. This is how I've done it - can anyone offer improvements for me?</p> <pre><code>def build_array(): services=[] for line in data.split('\n'): # split out each line of raw input holding=[] # start a temp array for var in line.split(','): # for each value append it to the temp array holding.append(var) services.append(holding) # append the temp array to the services array return services </code></pre> <p>The raw data is in the format:</p> <pre><code>data="""web,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,0,,,,0,0,0,0,0,0,,0,0,0,,, mysql,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,3,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web-https,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,4,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web,web2-NEW,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,0,1,0,0,19,0,,1,5,1,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,web1-OLD,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,19,0,,1,5,2,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,BACKEND,0,0,0,0,0,0,0,0,0,0,,0,0,0,0,UP,1,1,1,,0,19,0,,1,5,0,,0,,1,0,,0,,,,0,0,0,0,0,0,,,,,0,0,""" </code></pre>
[]
[ { "body": "<p><code>build_array</code> uses a global variable, which I don't see any good reason for. Why not just pass the data in as a parameter?</p>\n\n<pre><code>def build_array(data):\n # ...whatever\n</code></pre>\n\n<p>Also, you don't remove the leading whitespace from the first element on each line - remember that python <code>\"\"\"</code> quotes will leave indentation spaces in the string (even though they get removed from docstrings).</p>\n\n<p>It might be better just to remove leading and trailing whitespace from every string immediately after you split it, unless whitespace is ever significant in your application:</p>\n\n<pre><code>holding.append(var.strip())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T15:33:47.453", "Id": "3045", "ParentId": "3040", "Score": "2" } }, { "body": "<p>This looks like CSV. You are probably better off using the python csv module.</p>\n\n<pre><code> holding=[] # start a temp array\n for var in line.split(','): # for each value append it to the temp array\n holding.append(var)\n services.append(holding) # append the temp array to the services arra\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>services.append( line.split(',') )\n</code></pre>\n\n<p>line.split() returns a list already, there is no need to copy the elements into another list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T11:00:59.250", "Id": "4633", "Score": "0", "body": "I was trying something like that originally, but it kept failing on me. Works now! Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T16:52:16.220", "Id": "3046", "ParentId": "3040", "Score": "4" } }, { "body": "<p>I think NumPy library exists exactly for use cases like this. It is a pretty well known, established Python library which provides numerical capabilities in Python. It has a very active community with frequent releases. In numpy I would just do this:</p>\n\n<pre><code>from numpy import genfromtxt\nfrom StringIO import StringIO\n\ngenfromtxt(StringIO(data), delimter=',', dtype=None)\n</code></pre>\n\n<p>Very concise and more readable. Much easier to maintain since fewer lines of code and hence fewer bugs :)</p>\n\n<p>Also, I tried executing your code and genfromtxt code and it looks like for the given data genfromtxt is slower than your code by almost an order of magnitude, but I think specifying the datatype of the columns in the data will improve the performance of genfromtxt a bit. \nAlso, if you can give the nature of the analysis you are trying to perform, what columns you want specifically for this analysis, the code can be made much faster.</p>\n\n<p>Over and above all these, Python emphasises on readability because developer time is more expensive than CPU time today!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T22:00:08.997", "Id": "4624", "Score": "0", "body": "numpy is awesome, although I don't know if its useful here. It all depends on what you want to do with the data afterwards." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T11:00:19.000", "Id": "4632", "Score": "0", "body": "I've briefly used numpy before. The only reason for me probably not using it is that this script will be deployed on a number of boxes, and I'd prefer to avoid having to install the numpy library on each machine. Thanks anyhow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T12:44:54.023", "Id": "4635", "Score": "0", "body": "I am not trying to convince you to use numpy, but installing any Python package has never been a problem to me. It has always been just a matter of easy_install numpy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T20:00:02.473", "Id": "4640", "Score": "0", "body": "Yes, but the script will probably be used across 100s of servers. Each one needing numpy installed, and each one being installed at a different time. It's not a problem with numpy, or it's install process, it's that I can't guarantee a server installed X years ago will have the same version of python/numpy as a server installed last week. The less I depend on external requirements, the more the script becomes portable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T16:08:38.933", "Id": "4669", "Score": "0", "body": "Ok. Makes sense. Have to trade-off at some point :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:23:34.917", "Id": "3050", "ParentId": "3040", "Score": "1" } } ]
{ "AcceptedAnswerId": "3046", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T11:29:23.630", "Id": "3040", "Score": "1", "Tags": [ "python", "array" ], "Title": "Multiline Input into Python Arrays" }
3040
<p>I'm creating a function that converts a title, to a URL slug. I'm not all to familiar with regular expressions, but I've done my best. Can you see any problems or improvements with the following function below?</p> <p>The only thing allowed in the slug is letters, numbers and <code>-</code> charchaters.</p> <pre><code>function slugify($input) { // Convert multiple spaces to single spaces $slug = preg_replace("/[[:blank:]]+/",' ', $input); // Convert to lower case $slug = strtolower($slug); // Remove anything that's not a number, letter or space $slug = preg_replace('/[^a-z0-9\s]+/', '', $slug); // Trim, and replace spaces with hyphens $slug = preg_replace('/\s/', '-', trim($slug)); return $slug; } </code></pre>
[]
[ { "body": "<p>You should prepare a set of sentences to slugify and verify by yourself if your function is ok.</p>\n\n<p>Below are the step I use to slugify text:</p>\n\n<ol>\n<li><p>Use <code>iconv()</code> if available:</p>\n\n<p><code>$slug = iconv('utf-8', 'us-ascii//TRANSLIT', $text);</code></p></li>\n<li><p>Lowercase the text, taking Unicode into account:</p>\n\n<p><code>$slug = mb_strtolower($slug);</code></p></li>\n<li><p>Remove unwanted characters like you do:</p>\n\n<p><code>$slug = preg_replace('/\\W+/', '-', $slug);</code></p></li>\n</ol>\n\n<p>These are the steps used in Propel ORM or symfony framework for example.\nThe complete code can be:</p>\n\n<pre><code>function slugify($text, $separator = '-')\n{\n // transliterate\n if (function_exists('iconv'))\n {\n $slug = iconv('utf-8', 'us-ascii//TRANSLIT', $text);\n }\n\n // lowercase\n if (function_exists('mb_strtolower'))\n {\n $slug = mb_strtolower($slug);\n }\n else\n {\n $slug = strtolower($slug);\n }\n\n // remove accents resulting from OSX's iconv\n $slug = str_replace(array('\\'', '`', '^'), '', $slug);\n\n // replace non letter or digits with separator\n $slug = preg_replace('/\\W+/', $separator, $slug);\n\n // trim\n $slug = trim($slug, $separator);\n\n return $slug;\n}\n</code></pre>\n\n<p>I think <code>$text</code> is a better name than <code>$input</code> for the string to slugify.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T14:25:27.380", "Id": "3044", "ParentId": "3041", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-06-21T12:46:50.757", "Id": "3041", "Score": "2", "Tags": [ "php", "regex", "url" ], "Title": "Function to convert a title to a slug" }
3041
<p>So I'm developing a webpage using MVC which will be mainly JavaScript driven.</p> <p>Instead of using global variables, and global functions, I would like to do it right this time. I don't want to use something to complex, because the team and I are new to large JavaScript applications. I tried implementing the Module pattern to organize my functions and page state. </p> <p>This is what I came up with so far.</p> <p>Am I misusing the Module pattern? What am I doing wrong? Where will I get into trouble?</p> <pre><code>&lt;script type="text/javascript"&gt; var ui = (function ($) { var _ui = {}; _ui.submitMainForm = function () { document.main.submit(); }; return _ui; } (jQuery)); ui.tabs = (function ($) { var _tabs = {}; var resourceTabs = $("#resourceTabs"); var selectedTabPersistence = $("#SelectedTab"); _tabs.getSelectedTab = function () { return selectedTabPersistence.val(); }; _tabs.setSelectedTab = function (value) { selectedTabPersistence.val(value); }; _tabs.initialize = function () { resourceTabs.tabs({ select: function (event, ui) { _tabs.setSelectedTab(ui.tab.hash); } }); resourceTabs.tabs("select", _tabs.getSelectedTab()); }; return _tabs; } (jQuery)); ui.filter = (function ($) { var _filter = {}; var personLevels = $("#personLevels"); var vehicleLevels = $("#vehicleLevels"); var personLevelsRadio = $("#personLevels :radio"); var vehicleLevelsRadio = $("#vehicleLevels :radio"); _filter.initialize = function () { personLevels.buttonset(); vehicleLevels.buttonset(); personLevelsRadio.bind("change", function () { ui.submitMainForm() }); vehicleLevelsRadio.bind("change", function () { ui.submitMainForm() }); }; return _filter; } (jQuery)); $(document).ready(function () { ui.tabs.initialize(); ui.filter.initialize(); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>You have multiple anonymous functions when you could do one and on the last line return your ui.* object.</p>\n\n<pre><code>var ui = (function($) {\n // local ui ref\n var ui = {};\n\n // other namespaces .. etc\n ui.tabs = {};\n\n return ui;\n})(jQuery));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:04:19.997", "Id": "3052", "ParentId": "3047", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T18:16:38.780", "Id": "3047", "Score": "4", "Tags": [ "javascript", "jquery", "jquery-ui" ], "Title": "Organizing page functions and page state using the Module pattern" }
3047
<pre><code>new MethodExecuter() .ForAllInvocationsCheckCondition(!Context.WannaShutDown) .When(shouldRun).ThenInvoke(x =&gt; x.Methods(new Action[] { B.Process, A.Process })) .When(shouldRun).ThenInvoke(x =&gt; x.Method(B.Process).Repeat(100)) .Invoke(x =&gt; x.Method(C.Process)); </code></pre> <p>I deliberately do not say anything about what this API does. I did show this API my team mates and they did not like it. For them it is unreadable.</p> <p>What do you think about the API? What tips do you have? What do you think about complexitiy, usability and readability of fluent APIs and how to achieve good APIs?</p> <p>EDIT Why did I build this API?</p> <p>Well, I have a bunch of methods that are invoked synchronously when a condition is false. The condition applies foreach method invocation.</p> <pre><code>if (!Context.WannaShutDown) A.Process(); if (!Context.WannaShutDown) B.Process(); if (!Context.WannaShutDown) C.Process(); if (!Context.WannaShutDown) D.Process(); if (!Context.WannaShutDown) E.Process(); if (!Context.WannaShutDown) F.Process(); if (!Context.WannaShutDown) { if (condition) { for (int i = 0; i &lt;= 100 i++) { Z.Process(); } } ... </code></pre> <p>I do not like such crap code. What I wanted to do is to solve "the problem" <strong>once</strong> with a class that is responsible for invocating methods. I tried to build an API that is as simple as possible, but it seems I failed.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:52:42.703", "Id": "4615", "Score": "1", "body": "How enjoyable is it to debug this? Does the fluent syntax make it more difficult? What is this abstraction buying you? Fluent APIs are not better ipso facto. Similar to how a `.ForEach` operator is not necessarily better than a simple `foreach` loop. With that being said, this could be a good design, but I think you need to explain a bit the pain it abstracts away. To put it another way, C# already has a language facility for executing methods: the language itself is already designed for this purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:12:30.113", "Id": "4622", "Score": "0", "body": ".ForEach let you express things very very compact. Debuging is not that big problem, because you only have to set breakpoints at the method that shall be invoked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T15:57:51.727", "Id": "4636", "Score": "0", "body": "you would probably be well-served if you read this Eric Lippert article: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx" } ]
[ { "body": "<p>Fluent APIs in general always make me think back to <a href=\"http://codeutopia.net/blog/2008/01/21/pooquery-the-fluent-php-revolution/\" rel=\"nofollow\">pooQuery</a>. Fluent APIs (in my opinion) are aimed at the same goal that resulted in the creation of <a href=\"http://en.wikipedia.org/wiki/COBOL#Verbose_syntax\" rel=\"nofollow\">COBOL</a>: to be readable and \"comprehensible\" to non-programmers. Programmers, of course, know that this is a fallacy. The difficulty in programming is not understanding the particular syntax of a given programming language, but in formulating the logical steps needed to implement a particular algorithm. Knowing this, verbose, english-like languages (\"fluent APIs\") do not help, and indeed, only serve to obfuscate the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:55:24.260", "Id": "4616", "Score": "1", "body": "I think dismissing all fluent APIs with this broad stroke of yours ignores the many APIs that are best expressed fluently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:57:14.243", "Id": "4617", "Score": "0", "body": "@Kirk: Such as?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:59:07.440", "Id": "4618", "Score": "0", "body": "Let's see: Ninject, NHibernate, MS Entity Framework, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:01:56.627", "Id": "4619", "Score": "0", "body": "@Kirk: All these APIs worked just fine (and still do) without fluent APIs. Whether or not they are \"best expressed fluently\" is merely your opinion. In my opinion, they are not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:05:33.570", "Id": "4620", "Score": "0", "body": "@Mark, the code-first approach *requires* using fluent syntax. The manual for Ninject *entirely* relies on fluent syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:07:50.273", "Id": "4621", "Score": "0", "body": "I edit my question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T21:25:14.267", "Id": "4623", "Score": "1", "body": "@Kirk: the fact that a particular project only exposes a fluent API is not proof that a fluent API is better, it's only proof that whoever designed and implemented the API believes it's better. It's still an opinion. The question is subjective, and I provided my opinion. You're free to provide yours as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T16:48:38.253", "Id": "4637", "Score": "0", "body": "I give you one great example of a good fluent API: [RunSharp](http://www.codeproject.com/KB/dotnet/runsharp.aspx)! Try emitting the same code yourself ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T15:16:47.387", "Id": "4666", "Score": "0", "body": "@Steven: RunSharp is a perfect example of a terrible fluent API: you have, for example, a `WriteLine()` method that does NOT write anything anywhere, it only puts some generated code into a list somewhere that will call the `Console.WriteLine()` method. What if you want to call `WriteLine()` on some other `TextWriter` instance? What would that method be in this \"good\" fluent API? The fact that emitting code is difficult is NOT proof that a fluent API is the best way to accomplish it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T20:13:58.987", "Id": "4688", "Score": "0", "body": "@Mark: I see your point, and agree to some extent (it's no proof indeed), but for me personally the fluent syntax made a difficult concept accessible to me." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:53:57.740", "Id": "3051", "ParentId": "3049", "Score": "0" } }, { "body": "<p>Kirk Woll makes some excellent points in his comment which could have been an answer IMHO.</p>\n\n<blockquote>\n <p>Fluent APIs are not better ipso facto.</p>\n</blockquote>\n\n<p>You are entirely right in wanting to refactor your given code sample in the edit, but it might be worthwhile to first explore some other possibilities before deciding on using a fluent API.</p>\n\n<p>A first concern is the <code>Context</code> class, as it looks like this is a global which is accessed from any location (A, B, C, ...). If there is any way to remove this global state, that might already be a more important improvement.</p>\n\n<p>Using only your given code sample (assuming a <code>IProcess</code> interface), you could already improve it by writing something like this:</p>\n\n<pre><code>Dictionary&lt;IProcess, int&gt; executeOperations = new Dictionary&lt;IProcess, int&gt;\n{\n { A, 1 }, { B, 1 }, { C, 1 }, { D, 1 }, { E, 1 }, { F, 1 },\n { Z, 100 }\n}\n\nforeach ( var executeItem in executeOperations )\n{\n if ( !Context.WannaShutDown )\n {\n for ( int i = 0; i &lt;= executeItem.Value; ++i )\n {\n executeItem.Key.Process();\n }\n }\n}\n</code></pre>\n\n<p>It's not clear what the <code>condition</code> in your code sample is meant to be, or why only Z needs to check for it, but for demonstration purposes I believe the above example shows there are other ways of refactoring your given code without having to rely on fluent syntax. You could replace the <code>int</code> value in the dictionary to a struct containing more execution parameters.</p>\n\n<p>That said, I believe your supplied sample is still too small to conclusively say whether or not using fluent syntax could be justified.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T17:18:55.993", "Id": "3061", "ParentId": "3049", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T20:09:40.027", "Id": "3049", "Score": "3", "Tags": [ "c#", "api" ], "Title": "Complexity, Usability and Readability of FluentAPIs - Sample: FluentMethodInvoker" }
3049
<p>I'm testing some methods for checking if an area of the screen changes, can you see any problems with how I'm doing this, and is there a better way for me to do this?</p> <p>the <code>_memoryImage2</code> will not change in the final app, it will be a read only array that I will check the <code>memoryImage</code> against.</p> <pre><code>namespace ScreenShot_BoundsTest { public partial class Form1 : Form { Bitmap _memoryImage1; Bitmap _memoryImage2; Color[,] _first; Color[,] _second; private string _valueX; public Form1() { InitializeComponent(); } private void Button1Click(object sender, EventArgs e) { backgroundWorker1.RunWorkerAsync(); } private void GetImage() { _memoryImage2 = _memoryImage1; CaptureScreen(); pictureBox2.Image = pictureBox1.Image; if (_memoryImage1 != null) _first = Bitmap2Imagearray(_memoryImage1); pictureBox1.Image = _memoryImage1; if (_memoryImage2 != null) _second = Bitmap2Imagearray(_memoryImage2); var x = CompareArrays(); _valueX = x != true ? "false" : "true"; } private bool CompareArrays() { for (var i = 0; i &lt; _memoryImage1.Width; i++) { for (var j = 0; j &lt; _memoryImage1.Height; j++) { if (_first == null) continue; if (_second != null) if (_first[i,j] != _second[i,j]) { return false; } } } return _first != null &amp;&amp; _second != null; } private void CaptureScreen() { Size s; using (var myGraphics = CreateGraphics()) { s = new Size(100, 50); _memoryImage1 = new Bitmap(s.Width, s.Height, myGraphics); } var memoryGraphics = Graphics.FromImage(_memoryImage1); memoryGraphics.CopyFromScreen(100, 100, 10, 10, s); } private static Color[,] Bitmap2Imagearray(Bitmap b) { var imgArray = new Color[b.Width, b.Height]; for (var y = 0; y &lt; b.Height; y++) { for (var x = 0; x &lt; b.Width; x++) { imgArray[x, y] = b.GetPixel(x, y); } } return imgArray; } private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e) { GetImage(); Thread.Sleep(100); } private void BackgroundWorker1RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { label1.Text = _valueX; backgroundWorker1.RunWorkerAsync(); } } } </code></pre>
[]
[ { "body": "<p>Let's start with your algorithm. You're using <code>Bitmap.GetPixel</code> to convert the entire bitmap image pixel by pixel into matrix of colors. I tried this approach several years ago - it was pretty slow on .Net 2.0 and I suppose it is still slow. You should convert image into <code>byte[]</code> and extract color bytes out of this array, it should be hundred times faster. Look into <a href=\"http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx\" rel=\"nofollow\">Bitmap.Lockbits method</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx\" rel=\"nofollow\">BitmapData class</a>.</p>\n\n<p>Remaining points are about your code readability. There are several general rules which may improve readability a lot:</p>\n\n<ol>\n<li>If method has some result of execution then <strong>return this result</strong> instead of assigning it to some field. Also use method parameters to accept arguments instead of class fields. </li>\n<li>If variable is not needed outside of one method's scope then <strong>do not declare a field</strong> for it, <strong>use local variable</strong> instead. </li>\n<li>Be <strong>strongly typed</strong>. Do not cast anything to string until you really need string. </li>\n</ol>\n\n<p>These simple rules being applied to your code mean: </p>\n\n<ol>\n<li><p>Rules <strong>#1</strong> and <strong>#3</strong> mean that your methods should have following signature: </p>\n\n<ul>\n<li><strong>void GetImage()</strong> -> <strong>bool CompareCurrentImageWithPrevious()</strong></li>\n<li><strong>bool CompareArrays()</strong> -> <strong>static bool CompareImageArrays(Color[,] imageArray1, Color[,] imageArray2)</strong> </li>\n<li><strong>void CaptureScreen()</strong> -> <strong>Bitmap CaptureScreen()</strong> </li>\n</ul></li>\n<li><p>This</p>\n\n<pre><code>var x = CompareArrays();\n_valueX = x != true ? \"false\" : \"true\";\n</code></pre>\n\n<p>Should be replaced with: </p>\n\n<pre><code>return CompareArrays(); \n</code></pre></li>\n<li><p>This</p>\n\n<pre><code>for (var i = 0; i &lt; _memoryImage1.Width; i++)\n{\n for (var j = 0; j &lt; _memoryImage1.Height; j++)\n {\n if (_first == null) continue;\n if (_second != null)\n if (_first[i,j] != _second[i,j])\n {\n return false;\n }\n }\n}\nreturn _first != null &amp;&amp; _second != null;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code> if (_first == null || _second == null) return false;\n if (_memoryImage1.Width != _memoryImage2.Width ||\n _memoryImage1.Height != _memoryImage2.Height)\n return false;\n return _first.SequenceEquals(_second);\n</code></pre></li>\n<li><p>Do not assign result of <code>GetImage()</code> to class field, <code>DoWorkEventArgs</code> have <code>Result</code> property which can be used to return value computed by background worker.</p>\n\n<pre><code>private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)\n{\n e.Result = GetImage();\n Thread.Sleep(100);\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T12:00:15.170", "Id": "4634", "Score": "0", "body": "thank you very mutch, it was realy helpful :) I will implement the changes and start using the ways you describe in future projects. +1 for helping in making me a better developer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T09:28:11.670", "Id": "3058", "ParentId": "3053", "Score": "8" } } ]
{ "AcceptedAnswerId": "3058", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T22:51:21.867", "Id": "3053", "Score": "4", "Tags": [ "c#" ], "Title": "Checking to see if an area of the screen changes" }
3053
<p>I caught a whiff of a code-smell emanating from one of my tests, in a scenario akin to the following:</p> <pre><code>[TestFixture] public void CarPresenterTests{ [Test] public void Throws_If_Cars_Wheels_Collection_Is_Null(){ IEnumerable&lt;Wheels&gt; wheels = null; var car = new Car(wheels); Assert.That( ()=&gt;new CarPresenter(car), Throws.InstanceOf&lt;ArgumentException&gt;() .With.Message.EqualTo("Can't create if cars wheels is null")); } } public class CarPresenter{ public CarPresenter(Car car) { if(car.Wheels == null) throw new ArgumentException("Can't create if cars wheels is null"); _car = car; foreach(var wheel in _car.Wheels) { wheel.Rolling += WheelRollingHandler; } } } </code></pre> <p>I was struggling to describe what the problem is except that it seems wrong that a <code>CarPresenter</code> should attempt to dictate to a <code>Car</code> whether or not its <code>Wheels</code> are initialised correctly.</p> <p>I wondered what pointers people here might give me?</p>
[]
[ { "body": "<p>Is a car really a car without wheels? </p>\n\n<p>If not, the check should be done at <code>Car</code> <strong>construction time</strong> and <code>CarPresenter</code> should not have to check for null, it should assume that a good working car is passed to it. (Correction, <code>CarPresenter</code> should check at construction time that <code>Car</code> is not <code>null</code>.) </p>\n\n<p>Assuming of course that <code>Car</code> is a class that you control as well therefore you can change it.</p>\n\n<p>And while we are talking about smells... You do not have much encapsulation. <code>Wheels</code> on <code>Car</code> should probably be private with public accessor methods if needed. </p>\n\n<p><strong>Answer to comment:</strong> </p>\n\n<blockquote>\n <p>So would you just handle the event\n Wheels.Rolling event and accept that\n if Wheels is null an exception will be\n thrown</p>\n</blockquote>\n\n<p>No, if you check at construction time and make sure you have working wheels, then you do not need to worry about it later. It is a lot better to bluntly (runtime exception) point out as early as possible if someone made a mistake (passing <code>null</code> for wheels) than waiting for these wheels to blow up who knows where in the code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T01:41:44.973", "Id": "4627", "Score": "0", "body": "thanks for your answer. So would you just handle the event Wheels.Rolling event and accept that if Wheels is null an exception will be thrown, or should car have a Moving event to encapsulate Wheels.Rolling, also, re encapsulation I'm working in C# so Wheels is a readonly property i.e. get_Wheels() with no set_Wheels(...) method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:59:46.900", "Id": "4660", "Score": "0", "body": "@panamac: see answer body. Also, I never worked with C# or events before so I cannot comment on the second half of your question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T00:33:30.593", "Id": "3055", "ParentId": "3054", "Score": "10" } }, { "body": "<p>Basically, by passing wheels in the constructor, you are saying its public interface has something to do with giving it wheels. Meaning anything that makes cars might give the wrong input.</p>\n\n<p>Encapsulate building of cars:</p>\n\n<pre><code>builder = new CarBuilder();\n\nvar car = builder.Car().Wheel().Wheel().Wheel().Wheel().SteeringWheel().AsCar();\n</code></pre>\n\n<p>You could even make wheel factories and such for different types of wheels.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T02:23:18.763", "Id": "3056", "ParentId": "3054", "Score": "0" } }, { "body": "<p>First off - I do not like the idea of asserting on an exception message. I'd rather have the class throw a <code>WheelNotFoundException</code> rather than an <code>ArgumentException</code>. This could be easily asserted on.</p>\n\n<p>Secondly, the smell I see are from the class itself:</p>\n\n<ol>\n<li><p>As @c_maker pointed out, the check for existence of wheels should be done while creating a <code>Car</code>. It is not the <code>CarPresenter</code>'s responsibility to check if the car is valid. Besides, the <code>CarPresenter</code> takes a <code>Car</code> as a parameter - this contract itself should tell the <code>CarPresenter</code> that the <code>Car</code> is properly created.</p></li>\n<li><p>Again a bit of violation of encapsulation - <code>CarPresenter</code> should deal with just the <code>Car</code> object, and not access its member's properties directly. In this case I'd rather have a <code>Car.OnMove</code> event handled at <code>CarPresenter</code> and in <code>Car</code> class should chain the event to the Wheel's rolling.</p></li>\n<li><p>Car has <code>Wheel</code>s which is a collection of <code>Wheel</code>. Are you looking at a generic event handler for the <code>Wheel</code>s collection? I would prefer each <code>Wheel</code> having its own event. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T04:49:49.963", "Id": "4629", "Score": "1", "body": "It's true the class smells too, but actually since the test came first, the smell is more of a brain smell than a code smell. Thanks to all answerers for the brain surgery." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T03:28:05.137", "Id": "3057", "ParentId": "3054", "Score": "2" } } ]
{ "AcceptedAnswerId": "3055", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T00:13:20.080", "Id": "3054", "Score": "5", "Tags": [ "c#", "unit-testing" ], "Title": "Car presenter tests" }
3054
<p>I have created a "Wizard" using JavaScript and based on people's answers you get taken to certain results divs. It works the way I want, but this code is VERY repetitive. Is there a way to clean up this JavaScript code?</p> <p>Demo can be seen <a href="http://jsfiddle.net/dswinson/PXp7c/56/" rel="nofollow">here</a>.</p> <pre><code>$(".hidden").hide(); $(function() { $("#start_button").click(function(){ $("#wizard_start").hide(); $("#Q1").show(); }); $("#reset").click(function(){ $("#wizard_start").show(); $(".hidden").hide(); $(":input").not(":button, :submit, :reset, :hidden").each( function() { this.value = this.defaultValue; }); }); $("#q1_button").click(function(){ if ($("input[value='q1_1']:checked").val()){ $("#Q2").show(); $("#Q1").hide(); } else if ($("input[value='q1_2']:checked").val()) { $("#results1").show(); $("#Q1").hide(); } else if ($("input[value='q1_3']:checked").val()) { $("#Q3").show(); $("#Q1").hide(); } }); $("#q2_button").click(function(){ if ($("input[value='q2_1']:checked").val()){ $("#results2").show(); $("#Q2").hide(); } else { $("#results3").show(); $("#Q2").hide(); } }); $("#q3_button").click(function(){ if ($("input[value='q3_1']:checked").val()){ $("#Q4").show(); $("#Q3").hide(); } else { $("#results1").show(); $("#Q3").hide(); } }); $("#q4_button").click(function(){ if ($("input[value='q4_1']:checked").val()){ $("#Q5").show(); $("#Q4").hide(); } else { $("#Q6").show(); $("#Q4").hide(); } }); $("#q5_button").click(function(){ if ($("input[value='q5_1']:checked").val()){ $("#results4").show(); $("#Q5").hide(); } else { $("#Q7").show(); $("#Q5").hide(); } }); $("#q6_button").click(function(){ if ($("input[value='q6_1']:checked").val()){ $("#Q8").show(); $("#Q6").hide(); } else { $("#Q9").show(); $("#Q6").hide(); } }); $("#q7_button").click(function(){ if ($("input[value='q7_1']:checked").val()){ $("#results4").show(); $("#Q7").hide(); } else { $("#results5").show(); $("#Q7").hide(); } }); $("#q8_button").click(function(){ if ($("input[value='q8_1']:checked").val()){ $("#results6").show(); $("#Q8").hide(); } else { $("#results7").show(); $("#Q8").hide(); } }); $("#q9_button").click(function(){ if ($("input[value='q9_1']:checked").val()){ $("#results8").show(); $("#Q9").hide(); } else if ($("input[value='q9_2']:checked").val()) { $("#Q10").show(); $("#Q9").hide(); } else if ($("input[value='q9_3']:checked").val()) { $("#results3").show(); $("#Q9").hide(); } }); $("#q10_button").click(function(){ if ($("input[value='q10_1']:checked").val()){ $("#results9").show(); $("#Q10").hide(); } else { $("#results3").show(); $("#Q10").hide(); } }); $("#q2_backbutton").click(function(){ $("#Q1").show(); $("#Q2").hide(); }); $("#q3_backbutton").click(function(){ $("#Q1").show(); $("#Q3").hide(); }); $("#q4_backbutton").click(function(){ $("#Q3").show(); $("#Q4").hide(); }); $("#q5_backbutton").click(function(){ $("#Q4").show(); $("#Q5").hide(); }); $("#q6_backbutton").click(function(){ $("#Q4").show(); $("#Q6").hide(); }); $("#q7_backbutton").click(function(){ $("#Q5").show(); $("#Q7").hide(); }); $("#q8_backbutton").click(function(){ $("#Q6").show(); $("#Q8").hide(); }); $("#q9_backbutton").click(function(){ $("#Q6").show(); $("#Q9").hide(); }); $("#q10_backbutton").click(function(){ $("#Q9").show(); $("#Q10").hide(); }); }); </code></pre>
[]
[ { "body": "<p>Something like this is probably a good way to start consolidating. Do the buttons share a class by chance?</p>\n\n<pre><code>$('.myButtonClass').click(function () {\n // Extract an id:\n var myid = this.id.substr(1, 3);\n\n switch (myid) {\n case 'reset':\n $('wizard_start').show();\n $('questionClass').hide();\n\n default:\n if ($(\"input[value='q' + myid + '_1']:checked\").val()){\n $(\"#Q\" + (myid + 1)).show();\n } else {\n $(\"#Q\" + (myid + 2)).show();\n }\n\n $(\"#Q\" + myid).hide();\n }\n\n});\n</code></pre>\n\n<p>The amount of code duplication this will eliminate will depend on how similar your function bodies actually are. You'd add case statements to the switch to accommodate special cases.</p>\n\n<p>Alternatively, you could add an object that contained values referring to what you check against, what you show, and what you hide. That would look something like this:</p>\n\n<pre><code>var wizardOrder = {\n 'q1': {\n 'check': \"input[value='q1_1']:checked\",\n 'show': 'Q2',\n 'hide': 'Q3'\n }\n};\n</code></pre>\n\n<p>Then our click function becomes something like this:</p>\n\n<pre><code>$('myButtonClass').click(function () {\n var myid = this.id.substr(1, 3);\n\n if ($(wizardOrder[myid]['check']).val()) {\n $(wizardOrder[myid]['show'].show();\n $(wizardOrder[myid]['hide'].show(); \n }\n});\n</code></pre>\n\n<p>Hopefully one of those two fit with your idea of reducing duplication and/or simplifying.</p>\n\n<p>-- Edit --</p>\n\n<p>I realized I didn't address your \"Jump to start\" functionality. I added that to the first example. It could be added to the second as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T17:57:53.863", "Id": "4678", "Score": "0", "body": "Thank you! I will play around with it and let you know how it goes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T19:21:02.783", "Id": "3066", "ParentId": "3060", "Score": "5" } }, { "body": "<p>I'll come back and edit this with more suggestions but for now I have two minor performance ones for your to pick up:</p>\n\n<ul>\n<li>Cache your jQuery DOM elements! Don't keep using <code>$('#Q2')</code> etc. Store it like so at the beginning of your closure: <code>var $q2 = $('#Q2');</code>.</li>\n<li>Also dont use <code>:checked\").val()</code>. This just seems backwards. Use <code>$(\"input[value=whatever]\").is(\":checked\");</code></li>\n<li>Additionally, to help reduce the quantity of code you're duplicated, consider writing just one function to handle showing and hiding of questions.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>var questions = [$('#Q1'), $('#Q2') ... etc];\nfunction showQuestion(questionNumber) {\n questionNumber -= 1; // so you can pass in '1' and have it zero indexed.\n for (var i = 0; i &lt; questions.length; i++) {\n if (i === questionNumber) questions[i].show();\n else questions[i].hide();\n }\n}\n</code></pre>\n\n<ul>\n<li>You are on the right track here asking for ways to reduce code duplication. You are taking a very procedural and 'manual' approach to writing your code though, from the outset try and imagine common repetitive tasks you'll be attempting in your program and abstract them out to functions / methods. It's worth also trying to take a more OO approach to your coding. </li>\n<li>This is a bit of a self plug, but I recently wrote a framework that might help with this....\n<a href=\"http://github.com/skippychalmers/xa.js/\" rel=\"nofollow\">http://github.com/skippychalmers/xa.js/</a> . You could re-write this entire quiz application using this and maintain it quite easily. Any problems at all with it just let me know and I'll fix / support. Alternatively, it might be a good idea to use something a bit more mature like sproutCore, knockout, spine or backbone. Check 'em all out and research your options. It's a learning curve to make the jump from this procedural style of coding to a more sustainable OO approach, but worth it in the long run!</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-13T08:34:23.443", "Id": "4069", "ParentId": "3060", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T17:08:23.843", "Id": "3060", "Score": "4", "Tags": [ "javascript" ], "Title": "Wizard for displaying results divs based on answers" }
3060
<p>I am trying to take advantage of the reflection built into RouteValueDictionary to add values to the query string of a URL. This is what I came up with. It seems to work, but I thought I would post it to see if anyone has any suggestions. It also uses the super-secret HttpValueCollection returned by ParseQueryString(), which automatically generates a URL-encoded query string.</p> <p>So far the only negative is that it only works on URLs that can be parsed by UriBuilder (i.e. absolute URLs). So, relative URLs (i.e. "/Home/Index") will throw an exception. Maybe I should try the UriBuilder, and if that fails then try to extract/append the query string manually.</p> <pre><code>public static string AppendQueryValues(this string absoluteUrl, object queryValues) { if (absoluteUrl == null) throw new ArgumentNullException("absoluteUrl"); if (queryValues == null) throw new ArgumentNullException("queryValues"); // Parse URL so we can modify the query string var uriBuilder = new UriBuilder(absoluteUrl); // Parse query string into an HttpValueCollection var queryItems = HttpUtility.ParseQueryString(uriBuilder.Query); // Parse &amp; filter queryValues (using reflection) into key/value pairs var newQueryItems = new RouteValueDictionary(queryValues) .Where(x =&gt; !queryItems.AllKeys.Contains(x.Key)); // Add new items to original collection foreach (var newQueryItem in newQueryItems) { queryItems.Add(newQueryItem.Key, newQueryItem.Value.ToString()); } // Save new query string (HttpValueCollection automatically URL encodes) uriBuilder.Query = queryItems.ToString(); return uriBuilder.Uri.AbsoluteUri; } </code></pre>
[]
[ { "body": "<p>Instead of catching an exception if the url is relative, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"nofollow\">System.Uri</a> class to see if it is an absolute Uri.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:39:02.090", "Id": "16486", "ParentId": "3063", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T18:30:42.740", "Id": "3063", "Score": "6", "Tags": [ "c#", "asp.net" ], "Title": "Using RouteValueDictionary to convert anonymous type to query string" }
3063
<p>I have the following code block which I'd like to refactor into a method, I just don't see a good way to get the following code into a method which doesn't have multiple responsibilities. Here is the code block:</p> <pre><code>int maxResults = pageable.getMaxResults(userPrefs); int firstResult; if (pageData.isLastPage()) { int count = getCountFromDb(); //'Heavy' cost associated with this, so we only //determine the count if they are on the last page... firstResult = getFirstResult(count, maxResults); if (count &gt; 0) { boolean isFinalPageFull = (count % maxResults) == 0; int pageNum = count / maxResults; pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum; } } else { firstResult = maxResults * pageNumber; } </code></pre> <p>I'd like to move this out into a method or two, but I need to only do this count one time. This limitation is clouding my vision, as I can't think of any function which follows the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow">Single Responsibility Principle</a>. Anything I can do to achieve my goal?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T22:37:35.153", "Id": "4641", "Score": "0", "body": "How do you know you're on the last page without knowing how many total results you have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:11:13.277", "Id": "4658", "Score": "0", "body": "It's not the ideal solution, but we send in Integer.MAX_VALUE, then we determine which results & how many should have been displayed on the page. When that occurs we reset the page number on the pageData object as you see, so that we can properly move to the next to last page. I don't like it, but it's what our customer agreed to due to the large tables we work with." } ]
[ { "body": "<p>You could make <code>count</code> a field, then have a function to <code>determineFirstResult()</code>. Then the <code>setPageNumber</code> block can be separated out.</p>\n\n<pre><code>if (pageData.isLastPage()) {\n count = getCountFromDb();\n if (count &gt; 0) {\n boolean isFinalPageFull = (count % maxResults) == 0;\n int pageNum = count / maxResults;\n pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum;\n }\n}\nfirstResult = determineFirstResult();\n</code></pre>\n\n<p>...</p>\n\n<pre><code>int determineFirstResult(int maxResults) {\n if (pageData.isLastPage()) return getFirstResult(count, maxResults);\n return maxResults * pageNumber;\n}\n</code></pre>\n\n<p>But now you've got a dependency; <code>count</code> has to be determined before calling <code>determineFirstResult()</code> as written. So maybe make <code>count</code> a lazy-loaded field; if it's requested and <code>null</code>, then (and only then) do you <code>getCountFromDb</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T18:57:33.823", "Id": "3065", "ParentId": "3064", "Score": "4" } } ]
{ "AcceptedAnswerId": "3065", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T18:43:29.830", "Id": "3064", "Score": "2", "Tags": [ "java" ], "Title": "Externalize to a function" }
3064
<p>I started working on a jQuery port for this <a href="http://www.dynamicdrive.com/dynamicindex16/formdependency.htm" rel="nofollow">Form Dependency Manager</a> script. It works fine, and I added a few extra options too.</p> <p>The problem is speed. If you create dependencies between 20+ form elements on a page you get the PC to run really slow. Firefox is throwing that "script is too slow" message. This is probably because of the heavy FOR loops.</p> <p>Do you guys have any suggestions on how could this be improved, or maybe new ideas on how to implement this kind of functionality?</p> <pre><code>(function($){ $.fn.setupDependencies = function(options){ var defaults = { attribute : 'rules', // the field attribute which contains the rules (use 'rel' for w3c valid code) disable_only : true, // if true it will disable fields + label, otherwise it will also hide them clear_inactive : false, // clears input values from hidden/disabled fields identify_by : 'name', // attribute used to identify dependencies (ie. DEPENDS ON [identify_by] BEING ...) condition_separator : ' AND ', // rules... possibility_separator : ' OR ', name_value_separator : ' BEING ', depends : 'DEPENDS ON ', conflicts : 'CONFLICTS WITH ', empty : 'EMPTY' }, settings = $.extend({}, defaults, options), matches = this, valueMatches = function(e, v){ return (e.val() == v || (e.is(':radio') &amp;&amp; e.filter(':checked').val() == v)); }, // show or enable show = function(e){ $('label[for="' + e.attr('id') + '"]').removeClass('disabled'); e.removeAttr('disabled'); if(!settings.disable_only){ e.show(); $('label[for="' + e.attr('id') + '"]').show(); } return true; }, // hide or disable hide = function(e){ $('label[for="' + e.attr('id') + '"]').addClass('disabled'); e.attr('disabled', 'disabled'); if(!settings.disable_only){ e.hide(); $('label[for="' + e.attr('id') + '"]').hide(); } if(settings.clear_inactive == true &amp;&amp; !e.is(':submit')) // ignore submit buttons if(e.is(':checkbox,:radio')) e.removeAttr('checked'); else e.val(''); return true; }; return this.bind('change input', function(){ // note: input event not working in IE &lt;= 8, obviously var j, k, f, n, isHidden, dep; matches.each(function(){ isHidden = false; dep = $(this).attr(settings.attribute); if(typeof dep !== 'undefined' &amp;&amp; dep !== false) for(j = 0, f = dep.split(settings.condition_separator); j &lt; f.length; ++j) if(f[j].indexOf(settings.depends) === 0){ for(k = 0, g = f[j].substr(settings.depends.length).split(settings.possibility_separator); k &lt; g.length; ++k) if(g[k].indexOf(settings.name_value_separator) === -1){ if(matches.filter('[' + settings.identify_by + '="' + g[k] + '"]').is(':checked')) break; else if(k + 1 == g.length) isHidden = hide($(this)); }else{ n = g[k].split(settings.name_value_separator); if(valueMatches(matches.filter('[' + settings.identify_by+'="' + n[0] + '"]'), n[1])) break; else if(k + 1 == g.length) isHidden = hide($(this)); } }else if(f[j].indexOf(settings.conflicts) === 0){ if(f[j].indexOf(settings.name_value_separator) === -1){ if(matches.filter('[' + settings.identify_by + '="' + f[j].substr(settings.conflicts.length) + '"]').is(':checked')){ isHidden = hide($(this)); break; } }else{ n = f[j].substr(settings.conflicts.length).split(settings.name_value_separator); if(valueMatches(matches.filter('[' + settings.identify_by + '="' + n[0] + '"]'), n[1])){ isHidden = hide($(this)); break; } } }; if(!isHidden) show($(this)); }); return true; }).change(); }; })(jQuery); </code></pre> <p>Note that my version uses a non-standard attribute for the rules by default (<code>rules</code>) instead of <code>class</code> like in the original script...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:35:19.923", "Id": "4656", "Score": "0", "body": "Personally I don't like non-standard attributes. I'd prefer using `class`. At least you should use a HTML5 `data-` attribute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T22:35:15.753", "Id": "4711", "Score": "0", "body": "well if anyone else wants to use this, they can change it. I'm using it in a site's administration interface, where the w3c validator is not welcome :)" } ]
[ { "body": "<p>All the points below I started writing while looking over the code for the performance issue, but aren't related to it. To be honest after the first read over I can't see how one would do it differently to be faster. One would probably have to do some proper profiling. </p>\n\n<p>My best guess however would be, that the performance is lost while re-parsing the rules every time and the only idea I have concerning that, is somehow to parse them once and maybe generate functions out of them, which you only need to call later on.</p>\n\n<p>Thinking of that, another solution would be to use a completely different approach and avoid parsing altogether. Instead of assigning a the rules via string in a property, you could create jQuery methods. Something like: <code>$(\"#some_form_element\").dependsOn(\"[name='mycheckbox']\");</code></p>\n\n<p>Now the performance unrelated points: </p>\n\n<ul>\n<li>The main code block is very difficult to read due to the deeply nested <code>if</code>s and <code>for</code>s. It would help to split it down into more sub routines, especially as a believe to see some code duplication.</li>\n<li>Additionally the one letter variables makes reading the code a bit more difficult, too.</li>\n<li>Setting custom properties on DOM objects (<code>isHidden</code>) is usually not recommended - that's why you had problems as it was called <code>hidden</code>. Why are you using a property here at all? It doesn't seem that you are using the value outside the loop anyway, so a simple variable would suffice.</li>\n<li><code>if(typeof dep !== \"undefined\" &amp;&amp; dep !== false)</code> could be simplified to <code>if (dep)</code>.</li>\n<li>I would move the <code>default</code> object and all the \"private\" methods out of the main function</li>\n<li>Real nitpick: You have unnecessary semicolons after block statements</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T22:10:53.083", "Id": "4708", "Score": "0", "body": "I've taken a function, jQuery approach like you've suggested. I posted it at http://codereview.stackexchange.com/questions/3104/how-can-i-improve-my-jquery-react-plugin . Is this similiar to what you are suggesting?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T22:29:02.873", "Id": "4709", "Score": "0", "body": "About your solution - I think natedavisolds here did exactly that. Anyway in my my case I'm trying to cut down the javascript as much as possible on a CMS page with lots of such form elements that depend on each other. This is why I'd like to avoid explicitly calling jQuery methods for each input. Regarding the speed I mentioned, I think I have to looks some place else because I tried testing this in a HTML page with 100+ elements and it seems to run pretty fast. Thanks for the input!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:28:32.233", "Id": "3083", "ParentId": "3070", "Score": "1" } }, { "body": "<p>I just posted a similar code review request: <a href=\"https://codereview.stackexchange.com/questions/3104/how-can-i-improve-my-jquery-react-plugin\">Plugin that conditionally displays elements based on form values</a> .</p>\n\n<p>I think that we are tackling the same issue here. I wish that we could merge the discussion to find the best solution, but at least we can use this great forum to bounce ideas off each other. :)</p>\n\n<p>It looks like you've taken a <code>String</code> approach to the problem. While I've taken a function based approach.</p>\n\n<p>I don't have any speed benchmarks yet, but I will be performing those on Monday and can share them then.</p>\n\n<p>Do you have an example of how to extend this to more rules? Is it easy?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T22:32:07.753", "Id": "4710", "Score": "0", "body": "I'm not sure what other rules could be added, because these ones cover pretty much all situations. I'm also not so sure about the performance hit anymore, because outside my CMS it doesn't seem to be noticeable; will have to do some more tests about this" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T22:13:25.390", "Id": "3109", "ParentId": "3070", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T01:46:34.793", "Id": "3070", "Score": "2", "Tags": [ "javascript", "jquery", "performance", "form" ], "Title": "Form dependencies, slow javascript" }
3070
<p>What would your preferred loop type be for a case like this:</p> <pre><code>StringBuilder sb = new StringBuilder(); for(Integer id : idList) { sb.append("?,"); } </code></pre> <p>In short: In dependency to the size of a List i want to add stuff to a String. The above example produces a "unused variable" warning.</p> <p>I'm thinking of these alternatives:</p> <pre><code>for(int i=0; i&lt;idList.size(); i++) { // ... } </code></pre> <p>I don't really like all the extra typing there...</p> <pre><code>Iterator it = idList.iterator(); while(it.hasNext()) { // ... it.next(); } </code></pre> <p>The loop head itself looks nice, but i end up typing a lot of extra code (getting the iterator, moving to the next element...)</p> <p>What I'd like to do would be something like that:</p> <pre><code>for(idList) { // ... } </code></pre> <p>Is there a better style/What is the best kind of style for that kind of loop?</p>
[]
[ { "body": "<p>I would go with the first alternative and use <code>@SuppressWarnings</code>.</p>\n\n<p>If you need this pattern more often, how about an object oriented solution:</p>\n\n<pre><code>public static class Repeat&lt;T&gt; implements Iterable&lt;T&gt; {\n private final T[] ts;\n private final int n;\n\n public Repeat(int n, T ... ts) {\n this.ts = ts;\n this.n = n;\n }\n\n public Iterator&lt;T&gt; iterator() {\n return new Iterator&lt;T&gt;() {\n int count = 0; \n\n public boolean hasNext() {\n return count &lt; n;\n }\n\n public T next() {\n if (! hasNext()) {\n throw new NoSuchElementException();\n }\n return ts[(count++) % ts.length];\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n };\n }\n public static &lt;U&gt; Repeat&lt;U&gt; repeat(int n, U ... us) {\n return new Repeat&lt;U&gt;(n, us);\n }\n}\n\n//usage\nimport static blabla.Repeat.*;\n...\nfor(String s : repeat(idList.size(), \"?,\")) {\n sb.append(s);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:18:34.130", "Id": "4645", "Score": "0", "body": "So where exactly does this improve on the given example? I don't see any advantage (or extra reuseability) in using this class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:25:30.820", "Id": "4647", "Score": "0", "body": "It's a nice OO approach (+1), but far too verbose for the presented problem (-1). Thus no vote in either direction from me :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:34:56.050", "Id": "4659", "Score": "1", "body": "As I said, I would consider this **only** when I had such a case multiple times, and the first alternative shown by the TO is completely okay. I added \"cyclic\" behavior in order to make it a little bit more reuseable. I don't understand @Steven Jeuris complaints, whose solution doesn't look very convinicing, by the way. And an Iterable is more flexible than @RoTaRa's solution, which solves the problem very concisely but is not reuseable at all. I don't say that everybody needs to actually **like** my solution, but I think nothing is wrong with it and the downvote is bullshit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T19:55:46.397", "Id": "4682", "Score": "0", "body": "@Landei: My downvote is not because this is a bad solution in its own right, but because its a bad solution for the posed problem. Now I know you shouldn't worry about performance until required, but neglecting it altogether for no added conciseness/clarity is worth a downvote in my personal opinion. Why pass the string around through iterators if its a const? If other people feel different they can still upvote. Don't take it so personal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T07:48:13.230", "Id": "4693", "Score": "1", "body": "@Steven Jeuris: There is always a trade-off between reuseability and performance. I think it makes sense to look for the most flexible and general solution for a given problem, and having an iterator that gives back a fixed list of things is certainly useful. I think the performance hit isn't as bad as you think, and you don't seem to bother much about performance yourself when suggesting **closures**, which would be exactly as \"bad\" as an Iterable performance-wise. And again, your solution with a loop var and range checks and inc doesn't look nice to me. But I would never downvote it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T06:46:48.100", "Id": "4792", "Score": "1", "body": "This \"simplifies\" `for(int i=0; i<foo.size(); ++i)` how? I'm all for the \"don't repeat yourself\" maxim but this is pushing it. The best part is `\"Not implemented yet\"` - are you planning to implement removal in the future?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T15:06:43.153", "Id": "4806", "Score": "0", "body": "@asveikau: Shouldn't we try to push our limits? The point is that your code repeats three(!) times the loop variable, which isn't used at all. Isn't saying \"repeat this x times\" easier to comprehend? The `Not implemented yet` came from the IDE, please ignore the \"yet\"." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:04:42.040", "Id": "3074", "ParentId": "3073", "Score": "1" } }, { "body": "<p>The second example is by far the clearest in expressing your intention. You want to do something an amount of times, in this case, <code>idList.size()</code>.</p>\n\n<pre><code>for( int i = 0; i &lt; idList.size(); ++i ) {\n // ...\n}\n</code></pre>\n\n<p>In the third one you are basically just writing what the first example already generates, so that's definitely not an improvement.</p>\n\n<p>You do have a point that a for loop is rather a big code construct to express just executing a piece of code an amount of times. <a href=\"http://www.techotopia.com/index.php/Looping_with_for_and_the_Ruby_Looping_Methods\" rel=\"nofollow noreferrer\">Ruby's <code>times</code> operator</a> is made exactly for this purpose. In other languages there are some code constructs available which could help you. Extension methods in C# allow you to create a similar operator as the <code>times</code> operator of Ruby.</p>\n\n<p>For Java I don't believe a more concise syntax is possible since <a href=\"http://en.wikipedia.org/wiki/Closure_%28computer_science%29\" rel=\"nofollow noreferrer\">closures</a> aren't supported in Java by default.</p>\n\n<hr>\n\n<p>As in <a href=\"https://codereview.stackexchange.com/questions/3073/java-simplify-a-loop/3076#3076\">RoToRa's answer</a>, a simple <code>String</code> helper class containing a <code>Repeat</code> function is most likely the cleanest solution for you. It doesn't provide the functionality to repeat any type or operation, but it does provide the concise syntax you are looking for.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T13:21:26.317", "Id": "4664", "Score": "0", "body": "I've heard noises that Java 7 will support closures :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T19:31:37.197", "Id": "4681", "Score": "0", "body": "@Michael K: Java will have to if they don't want to lose programmers to other languages. ;p" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:16:45.410", "Id": "3075", "ParentId": "3073", "Score": "6" } }, { "body": "<p>I would use a \"normal\" string repeating method:</p>\n\n<pre><code>String s = repeat(\"?,\", idList.size());\n</code></pre>\n\n<p>Unfortunately Java doesn't have such a method in the standard API. So you could write one yourself:</p>\n\n<pre><code>String repeat(String s, count i) {\n StringBuilder sb = new StringBuilder();\n while (i-- &gt; 0) {\n ab.append(s);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>or use one provided by several \"standard add-on APIs\" such as Apache Commons' <a href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#repeat%28java.lang.String,%20int%29\"><code>StringUtils.repeat()</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:25:20.193", "Id": "4646", "Score": "1", "body": "+1 That is a good alternative (or perhaps better) solution than using closures indeed! :) I was thinking way too technical hehe. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T00:22:33.287", "Id": "5405", "Score": "0", "body": "I don't dislike the answer, but I think the construct \"while(i-- >0) is not as clear as a more often seen for(int i=0; i<count; i++).. This is more intuitive IMO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T10:19:45.457", "Id": "3076", "ParentId": "3073", "Score": "15" } }, { "body": "<p>I suggest to use <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Strings.html#repeat%28java.lang.String,%20int%29\" rel=\"nofollow\">Strings.repeat()</a> from Google Guava library:</p>\n\n<pre><code>String result = Strings.repeat(\"?,\", idList.size());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:53:22.553", "Id": "3084", "ParentId": "3073", "Score": "4" } }, { "body": "<p>I'd personally use the second version, i.e. the <code>for</code> loop because it is clearer. The first example looks like you've introduced an error by not using the id, the third adds two extra lines of code, but isn't too bad on the eyes.</p>\n\n<p>I think I would also create a local cache of the <code>size()</code> so that you can avoid the function call on every iteration of the loop. But this is a compromise between speed, the size of the list, readability and whether the list size will change during the loop.</p>\n\n<pre><code>int size = idList.size();\nfor (int i = 0; i &lt; size; ++i) {...}\n</code></pre>\n\n<p>If this is a heavily called inner loop the saving yourself a few tens of thousands of function calls to return back a \"constant\" can save some time. But if you do something like this it might be worth a comment to say why you did it \"differently\" to an normal expected way.</p>\n\n<p>I like for loops because they are very self contained; you get start value, end condition and increment operation all on one line whereas a while loop requires hunting for the \"<code>++</code>\" somewhere within the while block itself. </p>\n\n<p>I think keeping your intention simple and clearly seen is more important going forward when your code has to be maintained. Remember to code as if the person maintaining your code is serial axe murderer who know where you live!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T11:15:18.133", "Id": "4699", "Score": "0", "body": "While I totally agree with your answer, it doesn't add much more to the given ones. Consider expanding it a bit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T11:02:34.743", "Id": "3097", "ParentId": "3073", "Score": "1" } } ]
{ "AcceptedAnswerId": "3076", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T09:19:49.533", "Id": "3073", "Score": "8", "Tags": [ "java" ], "Title": "Simplify a loop" }
3073
<p>I have a custom <code>PropertiesByValueComparer</code> and am fairly happy how it behaves for simple classes. I haven't included comparing by fields yet. Is there anything that is blatantly fail about this, or do you have other recommendations?</p> <pre><code>public class PropertiesByValueComparer&lt;T&gt; : IEqualityComparer&lt;T&gt; where T : class { private List&lt;PropertyInfo&gt; properties; private List&lt;FieldInfo&gt; fieldInfos; public PropertiesByValueComparer() { Type t = typeof(T); this.properties = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).ToList(); this.fieldInfos = t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).ToList(); } public bool Equals(T x, T y) { var pool = new List&lt;object&gt;(); return this.Equals(x, y, pool); } public bool Equals(T x, T y, List&lt;object&gt; pool) { if(pool.Contains(x) &amp;&amp; pool.Contains(y)) { return true; } if ((x == null &amp;&amp; y == null) || ReferenceEquals(x, y)) { pool.Add(x); pool.Add(y); return true; } if (x == null || y == null) { return false; } var xList = (x as IList); var yList = (y as IList); if(xList != null &amp;&amp; yList != null) { var result = CompareCollectionIgnoreOrder(xList, yList, pool); if(result) { pool.Add(xList); pool.Add(yList); return true; } } var valueProperties = GetValueProperties(); foreach (var property in valueProperties) { if (!Equals(property.GetValue(x, null), property.GetValue(y, null))) { return false; } } var classProperties = properties.Where(p =&gt; p.PropertyType.IsClass &amp;&amp; p.PropertyType != typeof(String)); foreach (var classProperty in classProperties) { Type valueComparerType = typeof(PropertiesByValueComparer&lt;&gt;); Type typeArg = classProperty.PropertyType; Type constructed = valueComparerType.MakeGenericType(typeArg); if (classProperty.PropertyType.Namespace != null &amp;&amp; classProperty.PropertyType.Namespace.Equals("System.Collections.Generic")) { var collectionX = classProperty.GetValue(x, null); var collectionY = classProperty.GetValue(y, null); if (collectionX == null &amp;&amp; collectionY == null) { continue; } var arrayX = (collectionX as IList); var arrayY = (collectionY as IList); if(!CompareCollectionIgnoreOrder(arrayX, arrayY, pool)) { return false; } continue; } else { object[] args = {classProperty.GetValue(x, null), classProperty.GetValue(y, null), pool}; object o = Activator.CreateInstance(constructed); if (!(bool)constructed.InvokeMember("Equals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null,o, args)) { return false; } } } pool.Add(x); pool.Add(y); return true; } private bool CompareCollectionIgnoreOrder(IList arrayX, IList arrayY, List&lt;object&gt; pool ) { if ((arrayX == null &amp;&amp; arrayY != null) || (arrayY == null &amp;&amp; arrayX != null)) { return false; } if (arrayX == null &amp;&amp; arrayY == null) { return true; } if (arrayX.Count == 0 &amp;&amp; arrayY.Count == 0) { return true; } if (arrayX.Count != arrayY.Count) { return false; } foreach (var itemX in arrayX) { foreach (var itemY in arrayY) { Type valueComparerType = typeof (PropertiesByValueComparer&lt;&gt;); Type typeX = itemX.GetType(); if(typeX.IsValueType || typeX == typeof(String)) { if(Equals(itemX, itemY)) { arrayY.Remove(itemY); break; } continue; } Type innerConstructed = valueComparerType.MakeGenericType(typeX); object iO = Activator.CreateInstance(innerConstructed); var iArgs = new object[] { itemX, itemY, pool }; if ((bool)innerConstructed.InvokeMember("Equals", BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, iO, iArgs)) { arrayY.Remove(itemY); break; } return false; } } if (arrayY.Count &gt; 0) { return false; } return true; } public int GetHashCode(T obj) { var valueProperties = GetValueProperties(); unchecked { int result = 0; foreach (var property in valueProperties) { var value = property.GetValue(obj, null); result = (result * 397) ^ (value != null ? value.GetHashCode() : 0); } return result; } } private IEnumerable&lt;PropertyInfo&gt; GetValueProperties() { var valueProperties = properties.Where(p =&gt; p.PropertyType.IsValueType || p.PropertyType == typeof(String)); return valueProperties; } } </code></pre> <p>I particularly feel that the <code>GetHashCode()</code> could do with some improvement, because it doesn't give unique values for objects with different reference objects nested further.</p>
[]
[ { "body": "<p>Some comments / suggestions:</p>\n\n<ul>\n<li>Make the <code>properties</code> / <code>fieldInfos</code> fields static; they don't change for each closed instance of the type PropertiesByValueComparer (i.e., for each T passed to it), so you don't need to initialize them for every new instance of the comparer</li>\n<li>On <code>Equals(T, T, List&lt;object&gt;)</code>, there's no need to add both x and y if ReferenceEquals returns <code>true</code> - they're the same object, and you're only using the pool to check for pre-searched objects</li>\n<li><code>GetValueProperties</code> is implemented as a (single-line) method; to fetch the \"class properties\" you use the lambda expression inline; the code should be consistent (either do both Where expressions inline, or both as helper methods)</li>\n<li>The calls to <code>ReferenceEquals</code> and <code>Equals</code> should be prefixed by <code>Object.</code> and <code>base.</code> respectively, so that we know without looking at the rest of the class that those are the methods from <code>Object</code>, not a helper method in the class</li>\n<li>[minor] Instead of using <code>classProperty.PropertyType.Namespace.Equals(\"System.Collections.Generic\")</code>, I'd remove the string and use something like <code>classProperty.PropertyType.Namespace.Equals(typeof&lt;IList&lt;object&gt;&gt;.Namespace)</code></li>\n<li>The comparer doesn't handle <code>Dictionary&lt;K,V&gt;</code>, since you're only looking for IList; if you started looking for <code>IEnumerable&lt;T&gt;</code> (and added a special case for <code>KeyValuePair&lt;K,V&gt;</code>) it would handle dictionaries as well</li>\n<li>I think the pool logic might be broken; you're adding objects which you see to the pool, and if the objects are on the pool then they're considered the same. It will fail if you have two objects of type A with three properties as shown below:</li>\n</ul>\n\n<p>Objects:</p>\n\n<pre><code>object 1 { prop1 = B, prop2 = C, prop3 = B }\nobject 2 { prop1 = B, prop2 = C, prop3 = C }\n</code></pre>\n\n<p>The comparer will validate that prop1 is the same (and add B to the pool), then validate that prop2 is the same (and add C to the pool), and when it validates prop3, even though they're different, since both B and C are in the pool, the comparer will consider them to be the same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T10:59:41.110", "Id": "4697", "Score": "0", "body": "one question I have for you @carlosfigueira is in regards to your suggestion to handle dictionaries: How would you know the <T> part of the IEnumerable you are checking against? The problem is (and this is why I chose the IList in the first place) that at compile time I don't know the value of T." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T13:31:07.533", "Id": "4700", "Score": "0", "body": "I have made some modifications, and am curious as to what the best strategy for showing them would be? replace the original codeblock, or add underneath?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T15:40:38.450", "Id": "4702", "Score": "0", "body": "@Martin, I believe adding modified code below the original one is ok. Otherwise it won't be clear what our current answers were about. Just make sure that it will be displayed separately from the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T16:48:39.960", "Id": "4704", "Score": "0", "body": "@Martin, IDictionary<K,V> is-a IEnumerable<KeyValuePair<K,V>>, so if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(KeyValuePair<,>)), then you can apply a comparison logic for lists of KVP. Another option is to first check for IDictionary, then IEnumerable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:40:05.927", "Id": "4766", "Score": "0", "body": "@carlosfigueira made some changes as suggested. looks pretty good to me now." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T03:34:06.927", "Id": "3094", "ParentId": "3088", "Score": "7" } }, { "body": "<p>One small addition to <em>carlosfigueira</em>'s answer. I would also propose extracting <em>ValueProperties</em> nad <em>ClassProperties</em> in the constructor, there is no point to store <code>properties</code> in this case at all and you can avoid executing reflection and linq again and again for each <code>GetValueProperties</code> call.</p>\n\n<p>Also it is unclear why <code>GetHashCode</code> takes only value properties into account. Even though it will definitely work but looks a little bit strange. Maybe you should add a comment why <em>class properties</em> are ignored?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T12:32:32.260", "Id": "4756", "Score": "0", "body": "If I'm not mistaken, the `GetHashCode()` function normally takes the object's memory address into it's calculation. I'll have to do some more reading up on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:31:58.057", "Id": "4764", "Score": "0", "body": "@Martin, well, it depends, because `GetHashCode` in your classes used as properties may be overridden as well" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T08:41:02.170", "Id": "3096", "ParentId": "3088", "Score": "3" } } ]
{ "AcceptedAnswerId": "3094", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T14:29:42.877", "Id": "3088", "Score": "9", "Tags": [ "c#" ], "Title": "Custom EqualityComparer using IEqualityComparer<> interface" }
3088
<pre><code>using System; using System.Web.UI.WebControls; namespace RideShare.Web { public partial class UserOrganization : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { // Fill drop down in search area. FillOrganizationDropDown(); // Populate riders grid with all records in Riders table. PopulateRidersGrid((int)SearchArguments.Zeor, null, (int)SearchArguments.Zeor, (int)SearchArguments.GenderDefaultValue); } } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Populate drop down list with organizations in each row bound. // Select Organization in drop down if rider has one. protected void grdRiders_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddlRiderOrganization = e.Row.FindControl("ddlRiderOrganization") as DropDownList; if (ddlRiderOrganization != null) { PopulateGridOrgDropDown(ddlRiderOrganization); // This is needed to select the organization of rider in ddl in grid Label lblOrganizationId = e.Row.FindControl("lblOrganizationId") as Label; if (lblOrganizationId != null) { if (!(string.IsNullOrEmpty(lblOrganizationId.Text.Trim()))) { ddlRiderOrganization.SelectedValue = lblOrganizationId.Text; } } } } } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Update organization when user click on update button. protected void grdRiders_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName == "UpdateOrganization") { int rowIndex = -1; rowIndex = int.Parse(e.CommandArgument.ToString()); if (rowIndex &gt;= 0) { GridViewRow row = grdRiders.Rows[rowIndex]; // Get organization id from ddl int seletedOrganizationId = GetSelecetdOrgId(row); // Organization is selected in drop down. if (seletedOrganizationId &gt; 0) { int riderId = GetRiderId(row); if (riderId &gt; 0) { bool isUpdate = RidersService.UpdateRiderOrganization(riderId, seletedOrganizationId); ShowMessage(isUpdate); } } } } } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Filter grid on given criteria. protected void btnSearch_Click(object sender, EventArgs e) { try { FilterGrid(); } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Put all controls on default position and populate grid. protected void btnClear_Click(object sender, EventArgs e) { try { txtName.Text = ""; txtAge.Text = ""; ddlGender.SelectedValue = "-1"; ddlOrganization.SelectedIndex = 0; FilterGrid(); } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Filter Riders grid on changing organizaton. protected void ddlOrganization_SelectedIndexChanged(object sender, EventArgs e) { try { FilterGrid(); } catch (Exception ex) { Exceptions.CatchException(false, ex); } } // Fitler grid on search criteria specified. private void FilterGrid() { int organizationId = 0; int.TryParse(ddlOrganization.SelectedValue.ToString(), out organizationId); string name = ""; if (!(string.IsNullOrEmpty(txtName.Text.Trim()))) { name = txtName.Text.Trim(); } int age = 0; if (!(string.IsNullOrEmpty(txtAge.Text.Trim()))) { int.TryParse(txtAge.Text.Trim(), out age); } int gender = int.Parse(ddlGender.SelectedValue.ToString()); PopulateRidersGrid(organizationId, name, age, gender); } // Fill grid with riders. private void PopulateRidersGrid(int organizationId, string firstName, int age, int gender) { grdRiders.DataSource = RidersService.GetRidersOnOrganizationId(organizationId, firstName, age, gender); grdRiders.DataBind(); } // Fill Organizations drop down. This drop down is in search area. private void FillOrganizationDropDown() { // Append is to retain an item i.e. 'All' having '0' value. ddlOrganization.AppendDataBoundItems = true; ddlOrganization.DataTextField = "OrganizationName"; ddlOrganization.DataValueField = "OrganizationId"; ddlOrganization.DataSource = RidersService.GetAllOrganization(); ddlOrganization.DataBind(); } // Populate organization drop down in gridview. private void PopulateGridOrgDropDown(DropDownList ddlRiderOrganization) { ddlRiderOrganization.DataTextField = "OrganizationName"; ddlRiderOrganization.DataValueField = "OrganizationId"; ddlRiderOrganization.DataSource = RidersService.GetAllOrganization(); ddlRiderOrganization.DataBind(); } // Get organization id from drown down in grid. private int GetSelecetdOrgId(GridViewRow row) { int selectedOrganizationId = -1; // Capture organization drop down list of current row. DropDownList ddlRiderOrganization = row.FindControl("ddlRiderOrganization") as DropDownList; if (ddlRiderOrganization != null) { selectedOrganizationId = int.Parse(ddlRiderOrganization.SelectedValue.ToString()); } return selectedOrganizationId; } // Get rider id from specified grid row. private int GetRiderId(GridViewRow row) { int riderId = 0; Label lblRiderId = row.FindControl("lblRiderId") as Label; if (lblRiderId != null) { if (!(string.IsNullOrEmpty(lblRiderId.Text))) { riderId = int.Parse(lblRiderId.Text); } } return riderId; } private void ShowMessage(bool isUpdated) { if (isUpdated) { ltrlMessage.Text = "Organization Updated Successfully!"; } else { ltrlMessage.Text = "Organization Not Updated. Please contact support team!"; } } private enum SearchArguments : int { GenderDefaultValue = -1, Zeor = 0 } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T18:23:15.163", "Id": "5099", "Score": "0", "body": "what does this code do Exceptions.CatchException(false, ex);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T06:44:17.313", "Id": "5142", "Score": "0", "body": "@Jethro, this is where I Log exceptions in text file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T08:07:11.733", "Id": "5143", "Score": "0", "body": "can I ask why you are always setting the CatchException(false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T13:07:35.493", "Id": "5146", "Score": "0", "body": "@Jethro, there is nothing special I am using this flag to show or not show the Error Page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T13:54:26.950", "Id": "5147", "Score": "0", "body": "small suggestion then would be to add this to the Application session if it's a global variable, or to a user session if it's per user setting, this way if you want to show the error you don't have to go to every page and change that hard coded false to a true." } ]
[ { "body": "<p>I'd recommend that you register your methods as event handlers. You have several handlers that merely call more descriptive methods, which clutters up the code a bit. In <code>Page_Load()</code>:</p>\n\n<pre><code>// Register event handlers\nbtn_Search.Click += new EventHandler(this.FilterGrid);\nbtn_Clear.Click += new EventHandler(this.ClearGrid);\n</code></pre>\n\n<p>And so on for each event. (ClearGrid is hypothetical - not one you already have implemented.) This ought to condense the source quite a bit. You might lose some of the Visual Studio navigation options; IMO it's worth it for a cleaner code-behind.</p>\n\n<p>Oh, and you've misspelled <code>GetSelecetdOrgId</code> :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T18:40:31.147", "Id": "4706", "Score": "0", "body": "Thanks for your time and reviewing it. By admitting my little knowledge I just want to ask that can you please provide me more information on \"register your methods as event handlers\". Tutorial, blog post etc. So I have clear understanding that what benefits this technique has so I use this with more understanding. I don't want to know that HOW to do this I want to know WHY to do this. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T13:37:36.723", "Id": "3101", "ParentId": "3089", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T16:40:29.857", "Id": "3089", "Score": "2", "Tags": [ "c#", ".net", "asp.net" ], "Title": "Simple search page." }
3089
<p>This method runs in just under two minutes. I would like to optimize it to run in less than 15 seconds. Using a LAMDA filter on my list before iterating it's elements and removing one conditional statement in the method shaved off 30 seconds. Any ideas to improve performance?</p> <p>c# .net 4.0</p> <pre><code>[SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand)] private static void GetGroupMembership(List&lt;ActiveDirectoryPrincipalProperties&gt; userGroupProperties) { List&lt;ActiveDirectoryPrincipalProperties&gt; groupProperties = new List&lt;ActiveDirectoryPrincipalProperties&gt;(); foreach (ActiveDirectoryPrincipalProperties gProperties in userGroupProperties.FindAll(token =&gt; token.groupYesNo.Equals(true))) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, gProperties.groupDomain); try { GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, gProperties.groupName); foreach (Principal member in group.GetMembers(true)) { ActiveDirectoryPrincipalProperties memberProperties = new ActiveDirectoryPrincipalProperties(); memberProperties.fullGroupName = gProperties.fullGroupName; memberProperties.groupDomain = gProperties.groupDomain; memberProperties.groupName = gProperties.groupName; memberProperties.groupType = gProperties.groupType; memberProperties.groupYesNo = false; memberProperties.memberDomain = member.Context.Name.ToString(); memberProperties.memberName = member.SamAccountName.ToString(); memberProperties.memberType = member.StructuralObjectClass.ToString(); memberProperties.sqlUserOnlyYesNo = false; groupProperties.Add(memberProperties); } group.Dispose(); } finally { ctx.Dispose(); } } userGroupProperties.AddRange(groupProperties); } </code></pre>
[]
[ { "body": "<p>If you are writing this in Visual Studio 2010, it would be worth profiling your code to find out exactly what method calls take the longest.</p>\n\n<p>Here is a link where you can watch a video from Channel9 about using the built in performance analyser tool in Visual Studio 2010 to perform CPU Sampling on your code: <a href=\"http://channel9.msdn.com/Blogs/wriju/CPU-Sampling-using-Visual-Studio-2010-Performance-Analyzer-Tool\" rel=\"nofollow\">http://channel9.msdn.com/Blogs/wriju/CPU-Sampling-using-Visual-Studio-2010-Performance-Analyzer-Tool</a></p>\n\n<p>Once you've identified the methods that take the longest to execute, you can start to work out if you're making any redundant or excessive calls and remove them, or research each call to find ways of optimising each.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T12:28:50.050", "Id": "3658", "ParentId": "3090", "Score": "2" } } ]
{ "AcceptedAnswerId": "3658", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T17:50:31.840", "Id": "3090", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "How to improve execution of web service using System.DirectoryServies.AccountManagement that runs very slow?" }
3090
<p>Please critique my login and signup validation php files.. login.php;</p> <pre><code>&lt;?php session_start(); require("connect.php"); $email = $_POST['emaillogin']; $password = $_POST['passwordlogin']; $email = mysql_real_escape_string($email); $password = mysql_real_escape_string($password); if(empty($email)) { die('{status:2,txt:"Enter your email address."}'); } if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { die('{status:2,txt:"Invalid email or password"}'); } if(empty($password)) { die('{status:2,txt:"Enter your password."}'); } if(strlen($password)&lt;6 || strlen($password)&gt;16) { die('{status:2,txt:"Invalid email or password"}'); } $query = "SELECT password, salt FROM users WHERE Email = '$email';"; $result = mysql_query($query); if(mysql_num_rows($result) &lt; 1) //no such user exists { die('{status:2,txt:"Invalid email or password"}'); } $userData = mysql_fetch_array($result, MYSQL_ASSOC); $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); if($hash != $userData['password']) //incorrect password { die('{status:2,txt:"Invalid email or password"}'); } //////////////////////////////////////////////////////////////////////////////////// if('{status:3}') { session_regenerate_id (); //this is a security measure $getMemDetails = "SELECT * FROM users WHERE Email = '$email'"; $link = mysql_query($getMemDetails); $member = mysql_fetch_row($link); $_SESSION['valid'] = 1; $_SESSION['userid'] = $member[0]; $_SESSION['name'] = $member[1]; session_write_close(); mysql_close($con); echo '{status:3,txt:"success.php"}'; } ?&gt; </code></pre> <p>Signup and validation PHP</p> <pre><code>&lt;?php $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; $remail = $_POST['remail']; $gender = $_POST['gender']; $bdate = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day']; $bday = $_POST['day']; $bmon = $_POST['month']; $byear = $_POST['year']; $cdate = date("Y-n-j"); $password = $_POST['password']; $hash = hash('sha256', $password); $regdate = date("Y-m-d"); function createSalt() { $string = md5(uniqid(rand(), true)); return substr($string, 0, 3); } $salt = createSalt(); $hash = hash('sha256', $salt . $hash); if(empty($name) || empty($surname) || empty($email) || empty($remail) || empty($password) ) { die('{status:0,txt:"All the fields are required"}'); } if(!preg_match('/^[A-Za-z\s ]+$/', $name)) { die('{status:0,txt:"Please check your name"}'); } if(!preg_match('/^[A-Za-z\s ]+$/', $surname)) { die('{status:0,txt:"Please check your last name"}'); } if($bdate &gt; $cdate) { die('{status:0,txt:"Please check your birthday"}'); } if(!(int)$gender) { die('{status:0,txt:"You have to select your sex"}'); } if(!(int)$bday || !(int)$bmon || !(int)$byear) { die('{status:0,txt:"You have to fill in your birthday"}'); } if(!$email == $remail) { die('{status:0,txt:"Emails doesn&amp;sbquo;t match"}'); } if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { die('{status:0,txt:"Enter a valid email"}'); } if(strlen($password)&lt;6 || strlen($password)&gt;16) { die('{status:0,txt:"Password must be between 6-16 characters"}'); } if (!$_POST["recaptcha_challenge_field"]===$_POST["recaptcha_response_field"]) { die('{status:0,txt:"You entered incorrect security code"}'); } if('{status:1}') { require("connect.php"); function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } $rip = getRealIpAddr(); $ipn = inet_pton($rip); $checkuser = mysql_query("SELECT Email FROM users WHERE Email = '$email'"); $username_exist = mysql_num_rows($checkuser); if ( $username_exist !== 0 ) { mysql_close($con); die('{status:0,txt:"This email Address is already registered!"}'); } else { $query = "INSERT INTO users (name, surname, date, Email, Gender, password, salt, RegistrationDate, IP) VALUES ('$name', '$surname', '$bdate', '$email', '$gender', '$hash', '$salt', '$cdate', '$ipn')"; $link = mysql_query($query); if(!$link) { die('Becerilemedi: ' . mysql_error()); } else { mysql_close($con); echo '{status:1,txt:"afterreg.php"}'; } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T15:05:54.697", "Id": "4729", "Score": "0", "body": "really,only improvement i can see on that is using PDO for communicating with db" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T21:00:57.333", "Id": "4819", "Score": "2", "body": "what the hell is this: `if('{status:3}')`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-29T04:38:11.887", "Id": "284579", "Score": "0", "body": "why don't you only bind the variable when the POST is not empty, e.g. if(empty($_POST['email']))\n {\n die('{status:2,txt:\"Enter your email address.\"}');\n } else {\n$email = $_POST['email'];\n}" } ]
[ { "body": "<p>You should delimit your SQL field and table names because reserved words (e.g. <code>date</code>) can cause problems. Also I would use LIKE for something like an email address so it's not case-sensitive.</p>\n\n<pre><code>$query = \"SELECT `password`, `salt` FROM `users` WHERE `Email` LIKE '$email';\";\n</code></pre>\n\n<p>You might want to use a encryption package like <a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow\">phpass</a>. Some people argue that it's much more secure to use an open source crypt framework, since it will be updated if problems are found with the code or cryptographic algorithms.</p>\n\n<p>You might want to use <a href=\"http://php.net/mysqli\" rel=\"nofollow\">mysqli</a> functions rather than mysql, just because they are \"improved\". :-)</p>\n\n<p><code>require</code> is a language construct, not a function so you don't need the parentheses. They are ok here but can cause problems in some cases.</p>\n\n<p>RobertPitt is correct: <code>if('{status:3}')</code> will always return <code>TRUE</code>.</p>\n\n<p><code>$cdate = date(\"Y-n-j\");</code> should probably use <code>d</code> for day w/ leading zeros.</p>\n\n<p><code>if(!(int)$gender)</code> casting to int is confusing and will require an additional conversion. I'd let PHP figure this out on its own: <code>if(!$gender)</code></p>\n\n<p>Good job escaping user input (from $_POST) in the first file; be sure to <strong>escape all user input used in SQL queries</strong> in both files.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T14:07:44.630", "Id": "4945", "ParentId": "3093", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T00:51:57.207", "Id": "3093", "Score": "3", "Tags": [ "php", "mysql", "form" ], "Title": "Login and signup validation php critique" }
3093
<p>I have a big string resource (basically the "about" text of the application) which contains styles (such as <code>&lt;b&gt;</code>, <code>&lt;a&gt;</code> etc.). The string resource is written on multiple lines, like this:</p> <pre><code>&lt;string name="about_text"&gt;&lt;big&gt;&lt;b&gt;About&lt;/b&gt;&lt;/big&gt;\n Lorem ipsum dolor sit amet and all that stuff...\n \n More stuff.&lt;/string&gt; </code></pre> <p>Now, just like in HTML, Android treats actual new lines (not the special <code>\n</code>) as spaces, so the text ends up looking something like this:</p> <pre><code>About Lorem ipsum dolor sit amet and all that stuff... More stuff. </code></pre> <p>Which looks pretty stupid. Now, I have two options:</p> <ol> <li>Write the whole thing on one line. I did not go with this because: <ol> <li>It would be a pretty big line.</li> <li>The text needs to be translated, and putting it all on one line would give the translators a great headache.</li> </ol></li> <li>Remove the unneeded whitespace programatically.</li> </ol> <p>I went with the second solution, but I'm not sure my implementation is optimal:</p> <pre><code>CharSequence aboutText = getText(R.string.about_text); SpannableStringBuilder ssb = new SpannableStringBuilder(aboutText); for (int i=0; i &lt; ssb.length()-1; i++) { if (ssb.charAt(i) == '\n' &amp;&amp; ssb.charAt(i+1) == ' ') { ssb.replace(i+1, i+2, ""); } } this.aboutText = (TextView) findViewById(R.id.about_text); this.aboutText.setText(ssb); </code></pre> <p>It seems very hackish, but I could not find a better way. Is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T14:17:02.010", "Id": "64498", "Score": "0", "body": "How about [assigning](http://developer.android.com/reference/android/widget/TextView.html#setTransformationMethod%28android.text.method.TransformationMethod%29) a [`SingleLineTransformationMethod`](http://developer.android.com/reference/android/text/method/SingleLineTransformationMethod.html) to the TextView?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T15:54:32.050", "Id": "64499", "Score": "0", "body": "That just makes the entire text single line. I still **want** new lines, I just don't want spaces and beginning of lines caused by `TextView` interpreting actual new lines as spaces (like in HTML). I basically want the equivalent of `white-space: pre`." } ]
[ { "body": "<p>This should work:</p>\n\n<pre><code>String aboutText = getText(R.string.about_text).toString();\n\naboutText = aboutText.replace(\"\\n \", \"\\n\");\n</code></pre>\n\n<p><code>toString()</code> is there to convert to a <code>String</code> object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T14:03:12.630", "Id": "4701", "Score": "3", "body": "A `CharSequence` is not just a `String` in disguise. The `CharSequence` returned by `getText()` is actually an instance of `SpannableString`. Thus, when calling `toString()` all the formatting is lost, which is not the desired effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T01:49:51.413", "Id": "4732", "Score": "0", "body": "I successfully tested it on my emulator, and I also checked the class and it was a `String`. I wonder if we have different API versions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T09:52:01.657", "Id": "4740", "Score": "0", "body": "Did it preserve formatting? Seems kind of strange. What's your target API version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-25T15:57:09.580", "Id": "166454", "Score": "0", "body": "The `Resources` are clever enough not to construct a `SpannableString` if it's really just plain text. For more follow `getText()`->`getResourceText()`->`StringBlock.get()` and notice [`res = str`](https://github.com/android/platform_frameworks_base/blob/gingerbread-release/core/java/android/content/res/StringBlock.java#L83) and `res = applyStyles(str, ...` where [`applyStyles` shortcuts to `str` as well if there are no styles](https://github.com/android/platform_frameworks_base/blob/gingerbread-release/core/java/android/content/res/StringBlock.java#L137). Note that the links are Gingerbread." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T13:06:59.103", "Id": "3100", "ParentId": "3099", "Score": "1" } }, { "body": "<p>The answer is to put the newlines at the start of each line, directly before the text.</p>\n\n<pre><code>&lt;string name=\"about_text\"&gt;&lt;big&gt;&lt;b&gt;About&lt;/b&gt;&lt;/big&gt;\n \\nLorem ipsum dolor sit amet and all that stuff...\n \\n\\nMore stuff.\n&lt;/string&gt;\n</code></pre>\n\n<p>Therefore all the redundant whitespace appears at the <em>end</em> of each line (e.g. after \"About\") where it doesn't affect the appearance of your text.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-15T07:24:34.953", "Id": "420740", "Score": "0", "body": "Man, you're a genius" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T23:46:23.363", "Id": "4881", "ParentId": "3099", "Score": "9" } }, { "body": "<p>Since this is XML, you can use the method of ignoring whitespace using comments:</p>\n\n<pre><code>&lt;string name=\"about_text\"&gt;&lt;big&gt;&lt;b&gt;About&lt;/b&gt;&lt;/big&gt;\\n&lt;!--\n--&gt;Lorem ipsum dolor sit amet and all that stuff...\\n&lt;!--\n--&gt;\\n&lt;!--\n--&gt;More stuff.&lt;/string&gt;\n</code></pre>\n\n<p>It may be ugly, but this technique has the advantage that the actual <em>text content of your XML</em> is the exact string you wanted it to be; there are no workarounds in code and you are not depending on any quirks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T20:52:03.747", "Id": "4936", "ParentId": "3099", "Score": "2" } }, { "body": "<p>I'm not sure <code>string.xml</code> is such a good choice or long strings.</p>\n\n<p>For the about dialog, I chose to have HTML page in <code>assets</code> and use a WebView (use <code>strings.xml</code> to store the name of the html file for the locale)</p>\n\n<p>This is more flexible and feature rich.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-25T00:41:54.843", "Id": "166356", "Score": "0", "body": "or use `res/raw` so translation is automatic" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T12:47:38.507", "Id": "7108", "ParentId": "3099", "Score": "1" } }, { "body": "<p>I think your use of SpannableStringBuilder makes sense. You could adopt Character.isSpaceChar() or Character.isWhitespace() if you want to easily trim additional whitespace characters.</p>\n\n<p>I realize it doesn't directly address your question, but I wrote a similar function to remove trailing whitespace from a CharSequence this afternoon:</p>\n\n<pre><code>public static CharSequence trimTrailingWhitespace(CharSequence source) {\n\n if(source == null)\n return \"\";\n\n int i = source.length();\n\n // loop back to the first non-whitespace character\n while(--i &gt;= 0 &amp;&amp; Character.isWhitespace(source.charAt(i))) {\n }\n\n return source.subSequence(0, i+1);\n}\n</code></pre>\n\n<hr>\n\n<p><b>Edit:</b> I ran into a similar problem this morning where I needed to remove internal blank lines, so I took a stab at writing a method that:</p>\n\n<ul>\n<li>minimizes the number of calls to replace(), and</li>\n<li>handles other forms of whitespace such as linefeeds, tabs, etc.</li>\n</ul>\n\n<p>Again, this doesn't <i>exactly</i> solve your problem (and as the other answers have pointed out, there are ways to work around your issue in the source), but an approach similar to this would be suitable for strings you didn't author, e.g. downloaded strings.</p>\n\n<pre><code>public static CharSequence removeExcessBlankLines(CharSequence source) {\n\n if(source == null)\n return \"\";\n\n int newlineStart = -1;\n int nbspStart = -1;\n int consecutiveNewlines = 0;\n SpannableStringBuilder ssb = new SpannableStringBuilder(source);\n for(int i = 0; i &lt; ssb.length(); ++i) {\n final char c = ssb.charAt(i);\n if(c == '\\n') {\n if(consecutiveNewlines == 0)\n newlineStart = i;\n\n ++consecutiveNewlines;\n nbspStart = -1;\n }\n else if(c == '\\u00A0') {\n if(nbspStart == -1)\n nbspStart = i;\n }\n else if(consecutiveNewlines &gt; 0) {\n\n // note: also removes lines containing only whitespace,\n // or nbsp; except at the beginning of a line\n if( !Character.isWhitespace(c) &amp;&amp; c != '\\u00A0') {\n\n // we've reached the end\n if(consecutiveNewlines &gt; 2) {\n // replace the many with the two\n ssb.replace(newlineStart, nbspStart &gt; newlineStart ? nbspStart : i, \"\\n\\n\");\n i -= i - newlineStart;\n }\n\n consecutiveNewlines = 0;\n nbspStart = -1;\n }\n }\n }\n\n return ssb;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-17T08:05:30.477", "Id": "10945", "ParentId": "3099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T12:25:31.607", "Id": "3099", "Score": "13", "Tags": [ "java", "strings", "html", "android" ], "Title": "Remove useless whitespace from styled string" }
3099
<p>I've written some Javascript code with jQuery to display a dialog box on a web page that "floats" in the corder of the page.</p> <p>(1) It has the following features: the dialog follows as the user scrolls the page.</p> <p>(2) If the user holds down the [Ctrl] key, the dialog is hidden so that it doesn't obscure content.</p> <p>I know that I tend to intuitively treat Javascript as if it were C code because it looks like C code and this is a habit I've been working to break.</p> <p>Also, I'm working to write this code to be reusable and not litter the global namespace with various objects and functions.</p> <p>I refer to the dialog as the "Little Black Book".</p> <p>Bearing that in mind, please critique my code:</p> <pre><code>function getNewLittleBlackBook(blackBookId, blackBookWidth, blackBookHeight) { var jQueryBlackBook = $('#' + blackBookId); if (jQueryBlackBook.length == 0) throw "Could not locate the element specified by blackBookId"; if (!blackBookWidth &gt; 0 || !blackBookHeight &gt; 0) throw "Invalid width or height specified for Little Black Book"; var LittleBlackBook = { id: blackBookId, width: blackBookWidth, height: blackBookHeight, jQueryObj: jQueryBlackBook, // Functions to show and hide the little black book hide: function () { jQueryBlackBook.hide(); }, show: function () { jQueryBlackBook.show(); }, // This setPosition function determines the position based on the document scrolling. setPosition: function () { var windowHeight = $(self).height(); var windowWidth = $(self).width(); var scrollPosition = $(self).scrollTop(); var newModalTop = windowHeight - this.height + scrollPosition - 40; var newModalLeft = windowWidth - this.width - 40; this.jQueryObj.css('top', newModalTop + 'px'); this.jQueryObj.css('left', newModalLeft + 'px'); this.jQueryObj.css('height', this.height); this.jQueryObj.css('width', this.width); }, // end setPosition handlers: { ExternalScroll: function () { LittleBlackBook.setPosition(); }, // These next two handlers serve to show/hide the Little Black Book when the user holds down the [Ctrl] key. ExternalKeyDown: function (e) { if (e.keyCode == 17) LittleBlackBook.hide(); }, ExternalKeyUp: function (e) { if (e.keyCode == 17) LittleBlackBook.show(); } } // end handlers }; // end LittleBlackBook object // Attach event handlers. $(self).scroll(LittleBlackBook.handlers.ExternalScroll); $(document).keydown(LittleBlackBook.handlers.ExternalKeyDown); $(document).keyup(LittleBlackBook.handlers.ExternalKeyUp); LittleBlackBook.setPosition(); LittleBlackBook.show(); // Return the object return LittleBlackBook; } </code></pre>
[]
[ { "body": "<p>You can combine your <code>css</code> calls:</p>\n\n<pre><code>this.jQueryObj.css({\n top: newModalTop, \n left: newModalLeft,\n height: this.height,\n width: this.width\n});\n</code></pre>\n\n<p>jQuery automatically inserts <code>px</code> when setting dimension properties.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T19:33:27.750", "Id": "3105", "ParentId": "3103", "Score": "2" } }, { "body": "<p>You should throw <code>Error</code> objects rather than strings:</p>\n\n<pre><code>throw new Error(\"Invalid width or height specified for Little Black Book\");\n</code></pre>\n\n<p>This provides a stack trace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T20:04:52.427", "Id": "4707", "Score": "0", "body": "+1 Thank you for your answers. As for the overall structure of the code, do you have any suggestions? Does it look good?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T19:35:15.813", "Id": "3106", "ParentId": "3103", "Score": "3" } }, { "body": "<p>You should consider changing your library to a jQuery plugin.<br>\nThis way, people can write <code>$(\"any selector\").littleBlackBook()</code>.</p>\n\n<p>You should store the object in <code>$.data</code> so that you can return it if the plugin is called again on the same element.</p>\n\n<hr>\n\n<p>Also, you should figure out what should happen if someone calls your function on two different elements.<br>\nYou can force uniqueness without cluttering the global namespace by adding a property to the function.<br>\nIn a jQuery plugin, that would mean</p>\n\n<pre><code>$.fn.littleBlackBook.alreadyExists = true;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T20:07:56.190", "Id": "3107", "ParentId": "3103", "Score": "1" } }, { "body": "<p>I'd use the following pattern</p>\n\n<pre><code>; var _ = _ || {}; // Gets the _ object or creates it if it doesn't yet exist, think of it as your namespace, or your $ for jQuery\n\n_.Stuff = (function() {\n var _privateStuff = 1;\n var _morePrivateStuff = \"beer\";\n\n function _selectBox()\n {\n // stuff\n }\n\n function _checkBox()\n {\n // stuff\n }\n\n function _radioButton()\n {\n // stuff\n }\n\n return {\n SelectBox : _selectBox,\n CheckBox : _checkBox,\n RadioButton : _radioButton,\n ExposedVariable : _privateStuff\n };\n})();\n</code></pre>\n\n<p>this way, you call your functions in a kind of <code>\"Namespace.Class.Function\"</code> pattern, for <code>instance _.Stuff.SelectBox();</code>, you get to have private variables that may or may not be accessible from the outside of your pseudo-class, and you get the extensibility of being able to keep separate files for each of your classes by just using the pattern in them</p>\n\n<pre><code>; var _ = _ || {};\n\n_.MoreStuff = (function() {\n return {\n Moar : \"moar\"\n };\n})();\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/4015844/javascript-designpattern-suggestion-needed/4016084#4016084\">Here</a> I posted a similar, <em>perhaps</em> more detailed, similar answer.</p>\n\n<p>Update: You can also return functions like this:</p>\n\n<pre><code>; var _ = _ || {};\n\n_.Superb = (function() {\n return {\n Moar : function(a,b){\n alert(a);\n return b;\n }\n };\n})();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T17:31:45.833", "Id": "4730", "Score": "0", "body": "but if you have many many functions that you also want to be public, you will need to return all of them one by one. lots of extra code no? if you work in you own environment it's ok to have several large, global-scoped, functions no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T15:57:03.520", "Id": "4952", "Score": "0", "body": "What if I have some \"static\" functions on my object. How can I make it so that my object refers to the same function in each instance when I want a function to be \"static\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T18:06:36.067", "Id": "4953", "Score": "0", "body": "@Rice what do you mean by \"static\"?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T20:54:11.480", "Id": "3108", "ParentId": "3103", "Score": "1" } } ]
{ "AcceptedAnswerId": "3108", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T15:30:42.173", "Id": "3103", "Score": "2", "Tags": [ "javascript", "jquery", "css" ], "Title": "Simple Javascript Widget without cluttering global namespace?" }
3103
<p>I've just released a jQuery plugin that conditionally displays elements based on form values. I would appreciate any suggestions on how to improve both the code and its usefulness.</p> <p><a href="http://natedavisolds.com/workshop/react.js/demo/react.html" rel="nofollow noreferrer">Here's the demo page</a></p> <ol> <li>Would this be useful to you?</li> <li>What other functionality should I include?</li> <li>Any refactoring or structure changes that I should make?</li> <li>I am worried about exposing 4 different functions. Is this too many?</li> </ol> <h2>The Goal</h2> <p>The plugin helps in situations where an element should hide or show based on values in other elements. In particular, it excels when there are multiple conditions that need to be satisfied in order to hide or show. </p> <h3>Additional concepts to keep in mind</h3> <ul> <li>Use as jQuery plugin</li> <li>Easy to chain rules together</li> <li>Understandable by reading a line of code</li> <li>Can build/add custom conditions</li> </ul> <h3>Example of business rules to solve</h3> <p>Let's say we have the following rules for elements:</p> <ul> <li><p>Display a set of checkboxes if </p> <ol> <li>Zip is between 19000 and 20000</li> <li>Income is lower than 15000</li> </ol></li> <li><p>Display another set of checkboxes if </p> <ol> <li>City is 'Philadelphia'</li> <li>Income is lower than 40000</li> </ol></li> <li><p>Display city select box if </p> <ol> <li>Zip is between 19100 and 19400</li> </ol></li> </ul> <h3>Ideal look</h3> <pre><code>$('.elements_to_display') .reactIf( '#some_form_element', SatisfiesFirstCondition) .reactIf( '#some_other_form_element', SatisfiesAnotherCondition) .reactIf( '#some_other_form_element', SatisfiesAnotherCondition); </code></pre> <h3>Page JS</h3> <pre><code>var IS = $.extend({}, $.fn.reactor.helpers); $('.cities') .reactIf('#zip', IS.Between(19100, 19400)) .reactIf('#zip', IS.NotBlank); $('.philly_middle_to_low_income') .reactIf('#income_2011', IS.LessThan(40000)) .reactIf('#cities_select', IS.EqualTo('philadelphia')); $('.low_income_select_zips') .reactIf('#income_2011', IS.LessThan(15000)) .reactIf('#zip', IS.BetweenSameLength(19000, 20000)) .reactIf('#zip', IS.NotBlank); $('.reactor').trigger('change.reactor'); </code></pre> <h3>Plugin react.js</h3> <pre><code>(function($){ $.fn.reactTo = function(selector) { var $elements = $(selector), $reactor_element = $(this), _proxy_event = function() { $reactor_element.trigger('change.reactor'); }; $elements.filter('select').bind('change.reactor', _proxy_event); $elements.filter('input').bind('keyup.reactor', _proxy_event); return this; }; $.fn.reactIf = function(sel, exp_func) { var $sel = $(sel); var _func = function() { return exp_func.apply($sel); }; this.each(function() { if (!$(this).hasClass('reactor')) { $(this).reactor(); } var conditions_arry = $(this).data('conditions.reactor'); if (!$.isArray(conditions_arry)) { conditions_arry = []}; conditions_arry.push(_func); $(this).data('conditions.reactor', conditions_arry); }); $(this).reactTo(sel); return this; }; $.fn.react = function() { this.each(function() { $(this).trigger('change.reactor') }); return this; }; $.fn.reactor = function(options) { var settings = $.extend({}, $.fn.reactor.defaults, options); this.each(function() { // var opts = $.meta ? $.extend({}, settings, $this.data()) : settings; var $element = $(this); if (!$element.hasClass('reactor')) { $element.data('conditions.reactor', []).addClass('reactor'); } var is_reactionary = function() { var conditionalArray = $(this).data('conditions.reactor'); var r = true; $.each(conditionalArray, function() { r = (r &amp;&amp; this.call()); }); return r; } var reaction = function(evt) { evt.stopPropagation(); if (is_reactionary.apply(this)) { settings.compliant.apply($element); } else { settings.uncompliant.apply($element); } } $element.bind('change.reactor', reaction); }); return this; }; $.fn.reactor.defaults = { compliant: function() { $(this).show(); }, uncompliant: function() { $(this).hide(); } }; $.fn.reactor.helpers = { NotBlank: function() { return( $(this).val().toString() != "" ) }, Blank: function() { return( $(this).val().toString() == "" ) }, EqualTo: function(matchStr) { var _func = function() { var v = $(this).val(); if (v) { return( v.toString() == matchStr ); } else { return false; } } return _func; }, LessThan: function(number) { var _func = function() { var v = $(this).val(); return(!(v &amp;&amp; parseInt(v) &gt; number)); } return _func; }, MoreThan: function(number) { var _func = function() { var v = $(this).val(); return(!(v &amp;&amp; parseInt(v) &lt; number)); } return _func; }, Between: function(min, max) { var _func = function() { var v = $(this).val(); return(!(v &amp;&amp; (parseInt(v) &gt; max || parseInt(v) &lt; min))); } return _func; }, BetweenSameLength: function(min, max) { var len = min.toString().length; var _func = function() { var v = $(this).val(); return(!(v &amp;&amp; v.length == len &amp;&amp; (parseInt(v) &gt; max || parseInt(v) &lt; min))); } return _func; } }; })(jQuery); </code></pre> <h3>HTML react.html</h3> <pre><code>&lt;form id="portfolio_form"&gt; &lt;fieldset&gt; &lt;label&gt;Zip&lt;/label&gt; &lt;input id="zip" type="text" value="" /&gt;&lt;br /&gt; &lt;label&gt;2011 Income&lt;/label&gt; &lt;input id="income_2011" name="income[2011]" /&gt; &lt;/fieldset&gt; &lt;p&gt;Display cities only when zip is between 19100 and 19400&lt;/p&gt; &lt;fieldset class="cities"&gt; &lt;label&gt;Cities&lt;/label&gt; &lt;select id="cities_select"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="philadelphia"&gt;Philadelphia&lt;/option&gt; &lt;option value="media"&gt;Media&lt;/option&gt; &lt;option value="doylestown"&gt;Doylestown&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;p&gt;Display checkboxes only for Philadelphia and income less than 40000&lt;/p&gt; &lt;fieldset class="philly_middle_to_low_income"&gt; &lt;input type="checkbox" /&gt; Check One&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Two&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Three&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Four&lt;br /&gt; &lt;/fieldset&gt; &lt;p&gt;Display checkboxes when zip is between 19000 and 20000 and income is lower than 25000&lt;/p&gt; &lt;fieldset class="low_income_select_zips"&gt; &lt;input type="checkbox" /&gt; Check One&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Two&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Three&lt;br /&gt; &lt;input type="checkbox" /&gt; Check Four&lt;br /&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T20:32:16.807", "Id": "4785", "Score": "0", "body": "looks nice! i would prefer to call it like this: $('.elements_to_display').reactIf( $(\"div\") , SatisfiesFirstCondition)\nif you can provide a jquery element directly, you can be more flexible on the way to specify the element that you are dependent on. $('.elements_to_display').reactIf( $(\"div\").parents(0) , SatisfiesFirstCondition)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T21:15:27.863", "Id": "4788", "Score": "0", "body": "@meo - yup that first argument can be a selector or a jquery object, so either will work." } ]
[ { "body": "<ul>\n<li><p>The syntax is nice, but the necessity for the user to declare <code>IS</code> themselves is not ideal. You should look for a different solution. One possibility could be to supply the name of the conditional function as a string and its arguments as additional arguments of <code>reactIf</code>. That way the conditional functions would no longer need to be of higher-order (not that that is a bad thing). Example:</p>\n\n<pre><code>$('.cities').reactIf('#zip', \"Between\", 19100, 19400);\n\n// ...\n$.fn.reactIf = function(sel, exp_func) {\n\n var $sel = $(sel);\n var args = arguments.slice(2);\n var _func = function() {\n return $.fn.reactor.helpers[exp_func].apply($sel, args); \n };\n\n // ...\n}\n\n$.fn.reactor.helpers = {\n // ...\n Between: function(min, max) {\n var v = $(this).val();\n return(!(v &amp;&amp; (parseInt(v) &gt; max || parseInt(v) &lt; min)));\n },\n // ...\n}\n</code></pre></li>\n<li><p>These is one more problem with the conditional functions: You supply a jQuery object as the <code>this</code> argument to<code>apply</code>, so it's not needed to wrap <code>this</code> in another jQuery call inside the conditional functions. You should either change to apply call to:</p>\n\n<pre><code>return exp_func.apply($sel[0]);\n</code></pre>\n\n<p>or in the conditional functions:</p>\n\n<pre><code>var v = this.val();\n</code></pre></li>\n<li><p>I'm not sure if it's a good idea to mark elements with a class. This can go wrong, for example, if a second JavaScript removes all classes from an element. Instead of </p>\n\n<pre><code> if (!$(this).hasClass('reactor')) { $(this).reactor(); }\n\n var conditions_arry = $(this).data('conditions.reactor');\n if (!$.isArray(conditions_arry)) { conditions_arry = []};\n</code></pre>\n\n<p>I would use</p>\n\n<pre><code> var conditions_arry = $(this).data('conditions.reactor');\n if (!$.isArray(conditions_arry)) {\n $(this).reactor();\n conditions_arry = [];\n };\n</code></pre>\n\n<p>and similarly in <code>reactor()</code>.</p></li>\n<li><p>You should consider short-circuiting the <code>$.each()</code> loop calling the conditional functions (which also makes the <code>&amp;&amp;</code> unnecessary):</p>\n\n<pre><code> $.each(conditionalArray, function() {\n r = this.call();\n return r; // Stops the `each` loop if r is `false`\n });\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:50:03.230", "Id": "4775", "Score": "0", "body": "Thanks for your feedback. Very nice insights. I've incorporated all these into the plugin except for the first. I will probably check the type of the second argument. If it is string then do as you've suggested. If a function then I will just add it like I've done. The \"IS\" variable isn't required at all. I just put it in because it looks better. All of your suggestions made it in, can I give you credit in the plugin code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T12:27:18.987", "Id": "4796", "Score": "0", "body": "You are welcome. I just saw one more thing: You can simplify `this.filter(...).length > 0` to `this.is(...)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:10:08.690", "Id": "3178", "ParentId": "3104", "Score": "5" } } ]
{ "AcceptedAnswerId": "3178", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-24T19:16:45.580", "Id": "3104", "Score": "6", "Tags": [ "javascript", "jquery", "html", "form" ], "Title": "Plugin that conditionally displays elements based on form values" }
3104
<p>Okay, I'll try and keep this as short as I can. First, I need to keep various options available to the user:</p> <pre><code>if ($c_verb eq 'on') { if ($c_enabling) ##if need eq, add || '' at declaration. {$category_id = 'xcomp';} elsif ($c_subject) {$category_id = 'subj';} elsif ($c_object) {$category_id = 'obj';} elsif ($c_prep) {$category_id = 'prep';} else {$category_id = 'allverb';} ... </code></pre> <p>After this, a loop through different forms of the search word (verb) is done. In the loop there is a chain of if-elsif with that checking which of the $category_id was chosen, and correctly acting on the corpus as a result.</p> <p>Then a second "heading" (over-arching radio buttons), with subheadings is examined:</p> <pre><code>elsif ($c_adj eq 'on') { if ($c_modnoun) {$category_id = 'amod';} else {$category_id = 'alladj';} ... </code></pre> <p>Again same structure as before this elsif, but a different file is opened, and a there is no need to loop through different forms of the search word.</p> <p>Finally, to check if no button was pressed:</p> <pre><code>else ##No buttons, like original search. { $category_id = "all"; ... </code></pre> <p>And again a similar structure is used, but no need to loop through forms and a different print is used.</p> <p>This is common to all of them (except different files are opened and some regex's are modified for different things):</p> <pre><code>local $/ = 'Parsing'; ##Instead of breaking at standard newline (avoid join and split) open my $parse_corpus, '&lt;', "/Users/jon/Desktop/stanford-postagger-full-2011-04-20/rootparsedLife1.txt" or die $!; while (my $sentblock = &lt;$parse_corpus&gt;) { chomp $sentblock; next unless ($sentblock =~ /\[sent. \d+ len. \d+\]: \[(.+)\]/); $sentencenumber++; $sentence = $1; $sentence =~ s/, / /g; if ($sentence =~ /\~\s([\d+F][\.I_][\d\w]+)\s/ ) { $chapternumber = $1; $sentencenumber = 0; ##Reset sentence number with new chapter } next unless ($sentblock =~ /\b$search_key/i); ##Ensure the sentence contains the searchkey next unless ($sentblock =~ /\(JJ\w*\s+\b$search_key\w*[\)\s]+/i); ##THIS Line is different for each my ($arg1, $arg2, $goodmatch); my @lines = split ("\n",$sentblock); ##Split by a newline for (my $l=0; $l &lt; @lines; $l++) { $goodmatch = 0; if ($category_id eq "subj") { if (($lines[$l] =~ /subj\w*\(|agent\w*\(/) &amp;&amp; ($lines[$l] =~ /\b$verbform\b/i)) { #.............. -elsif for each $category_id....... </code></pre> <p>And due to all the above options, there is an if(all)-else(everything else) used for the large, in-depth sort and print section.</p> <p><strong>Question</strong> Is there a common way to restructure this, I don't want to put my 500 line code here, so if there is no general method, I'll just delete the question. Even applying given/when? (recommended by Perl::Critic)</p> <p><strong>Constraints</strong> I'm running into memory problems, so it can't be inefficient (are subroutines more efficient or less??)</p> <p>THANKS for your time! Let me know if something is unclear.</p> <hr> <h1>EDIT</h1> <p>Here is the breakdown of the project:</p> <p>I am creating a search engine. User inputs search word and then has options to choose from (as radio buttons on a form):</p> <pre><code>--Show results where search word is a verb -------enabling -------subject -------object ... --Show results where search word is adjective -------a modified noun (amod) --Else show any instance search word appears </code></pre> <p>Then, the script searches through a file of format:</p> <pre><code>Parsing [sent. 2 len. 10]: [Radially, symmetrical, animals, move, slowly, or, not, at, all, .] (ROOT(S(NP(ADJP (RB Radially) (JJ symmetrical))(NNS animals))(VP (VBP move)(ADVP (RB slowly)(CC or)(RB not))(ADVP (IN at) (DT all))) (. .))) nsubj(move-4, animals-3) advmod(move-4, at-8) pobj(at-8, all-9) </code></pre> <p>And takes the info necessary depending on the user's input choices. Example:</p> <p>Search: 'move'</p> <p>Click: 'verbs only'-->'subjects'</p> <p>Output (from excerpt above): </p> <blockquote> <p>1 match(es) in which the subject of move is animals :</p> <p>Section 1_1: Radially symmetrical animals move slowly or not at all .</p> </blockquote> <p>That sums it up. The data structure I used was AoA, where the inner array contains all the info for each match. Memory has continued to pop in and out. From malloc_errors to one instance where the browser crashed. I don't think the script is at fault, but I do need it to be as fast as possible for searches, and CGI seems to be the 'bottleneck' there.</p>
[]
[ { "body": "<p>In order to provide meaningful help, I would need to know more about your application and what you are trying to accomplish. You are asking about if..else, but I suspect the real question/answer that you need is along the lines of: \"what data structure and approach is appropriate?\". There are a number of look-up table driven techniques that might be appropriate - huge hunks of this if..else code may just wind up disappearing. But I cannot give you a concrete example without knowing a bit more.</p>\n\n<p>I am curious where things like $c_subject come from? A bit more about the overall flow of your app would help put things in context.</p>\n\n<p>Can you show an example of what the input looks like? From your other question, perhaps it is sections like this:</p>\n\n<pre><code>Parsing [sent. 1 len. 31]:\n nsubj(85-7, Processes-3)\n nn(Transport-6, Membrane-5)\n prep_of(Processes-3, Transport-6)\n nsubj(examined-10, We-8)\n nsubjpass(used-17, it-15)\n xsubj(perform-19, it-15)\n conj_and(examined-10, used-17)\n xcomp(used-17, perform-19)\n dobj(perform-19, function-22)\n prep_of(binding-25, cell-28)\nParsing [sent.2 len. 50]\n more of these tag descriptions here? \n</code></pre>\n\n<p>So what does your application do with this? Is the full text part of this same file, a different file or data structure?</p>\n\n<p><em>> I'm running into memory problems</em> .. The code will not be a problem. More likely is some data storage/structure issue or perhaps even a memory leak. BTW, what leads you to believe that you have a memory problem? What symptom do you see?</p>\n\n<p>Oh, using a better indenting style would help the readability of your code. Move the { and } back to the previous level of indenting:</p>\n\n<pre><code>if (some condition)\n{\n statement...\n}\nelse\n{\n some other statement\n}\n</code></pre>\n\n<p>I like the above better, but this is also acceptible:</p>\n\n<pre><code>if (something){\n statement1\n statement2\n}elsif (something else){\n statement3\n statement4\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T04:25:44.483", "Id": "4946", "Score": "0", "body": "Thanks for the tips, I will edit my question with some more details." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T02:39:55.483", "Id": "3289", "ParentId": "3110", "Score": "2" } }, { "body": "<p>You should probably use a hash to store the information.</p>\n\n<pre><code>my %data = (\n xcomp =&gt; $c_enabling,\n subj =&gt; $c_subject,\n obj =&gt; $c_object,\n prep =&gt; $c_prep,\n);\n</code></pre>\n\n<p>If you had done it that way, it would be simple to set the value, without a huge <code>if</code> <code>elsif</code> chain.</p>\n\n<pre><code>my $category_id = 'allverb'; # set default\n\nfor my $category ( qw'xcomp subj obj prep' ){\n if( $data{$category} ){\n $category_id = $category;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:00:09.187", "Id": "6926", "ParentId": "3110", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:44:36.363", "Id": "3110", "Score": "2", "Tags": [ "perl" ], "Title": "Ideas on shortening this if-elsif chain with embedded if-elsif" }
3110
<p>This has been tested and compiled under Visual Studio 2010. Are there any serious problems with this implementation?</p> <p>PS. This implementation is fully lambda expression based. If I can make <code>fixpoint::fix</code> a real member function it will be simpler than this.</p> <pre><code>//As decltype(variable)::member_name is invalid currently, //the following template is a workaround. //Usage: t2t&lt;decltype(variable)&gt;::t::member_name template&lt;typename T&gt; struct t2t { typedef T t; }; template&lt;typename R, typename V&gt; struct fixpoint { typedef std::function&lt;R (V)&gt; func_t; typedef std::function&lt;func_t (func_t)&gt; tfunc_t; typedef std::function&lt;func_t (tfunc_t)&gt; yfunc_t; class loopfunc_t { public: func_t operator()(loopfunc_t v)const { return func(v); } template&lt;typename L&gt; loopfunc_t(const L &amp;l):func(l){} typedef V Parameter_t; private: std::function&lt;func_t (loopfunc_t)&gt; func; }; static yfunc_t fix; }; template&lt;typename R, typename V&gt; typename fixpoint&lt;R, V&gt;::yfunc_t fixpoint&lt;R, V&gt;::fix = [](fixpoint&lt;R, V&gt;::tfunc_t f) -&gt; fixpoint&lt;R, V&gt;::func_t { fixpoint&lt;R, V&gt;::loopfunc_t l = [f](fixpoint&lt;R, V&gt;::loopfunc_t x) -&gt; fixpoint&lt;R, V&gt;::func_t{ //f cannot be captured since it is not a local variable //of this scope. We need a new reference to it. auto &amp;ff = f; //We need struct t2t because template parameter //V is not accessable in this level. return [ff, x](t2t&lt;decltype(x)&gt;::t::Parameter_t v){ return ff(x(x))(v); }; }; return l(l); }; int _tmain(int argc, _TCHAR* argv[]) { int v = 0; std::function&lt;int (int)&gt; fac = fixpoint&lt;int, int&gt;::fix([](std::function&lt;int (int)&gt; f) -&gt; std::function&lt;int (int)&gt;{ return [f](int i) -&gt; int{ if(i==0) return 1; else return i * f(i-1); }; }); int i = fac(10); std::cout &lt;&lt; i; //3628800 return 0; } </code></pre>
[]
[ { "body": "<p>I hav tried the same thing in G++ (version 4.5 from Ubuntu 11.04 original), and the result is quite impressing me. We now do have a lot more features to generise the solution. </p>\n\n<ol>\n<li><p>we can now support any number of parameters without modifying the code.</p></li>\n<li><p>the t2t class is no longer needed as G++ lambda supports accessing all identifiers in scope, including global things. </p></li>\n</ol>\n\n<p>I also tried write a free template function to access the internal function. And the result looks good. I just wanted to say: it is elegant!</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;functional&gt;\n\ntemplate&lt;typename R, typename... V&gt;\nstruct fixpoint\n{\n typedef std::function&lt;R (V...)&gt; func_t;\n typedef std::function&lt;func_t (func_t)&gt; tfunc_t;\n typedef std::function&lt;func_t (tfunc_t)&gt; yfunc_t;\n\n class loopfunc_t {\n public:\n func_t operator()(loopfunc_t v)const {\n return func(v);\n }\n template&lt;typename L&gt;\n loopfunc_t(const L &amp;l):func(l){}\n loopfunc_t(){}\n private:\n std::function&lt;func_t (loopfunc_t)&gt; func;\n };\n static func_t Fix(tfunc_t f){\n return [](loopfunc_t x){ return x(x); }\n ([f](loopfunc_t x){ return [f, x](V... v){ return f(x(x))(v...); }; });\n }\n};\ntemplate&lt;typename T&gt;\nstruct getfixpoint\n{\n typedef typename getfixpoint&lt;decltype(&amp;T::operator())&gt;::fp fp;\n};\ntemplate&lt;typename R, typename T, typename... V&gt;\nstruct getfixpoint&lt;std::function&lt;R (V...)&gt; (T::*)(std::function&lt;R (V...)&gt;)&gt;\n{\n typedef fixpoint&lt;R, V...&gt; fp;\n};\ntemplate&lt;typename R, typename T, typename... V&gt;\nstruct getfixpoint&lt;std::function&lt;R (V...)&gt; (T::*)(std::function&lt;R (V...)&gt;)const&gt;\n{\n typedef fixpoint&lt;R, V...&gt; fp;\n};\ntemplate&lt;typename R, typename... V&gt;\nstruct getfixpoint&lt;std::function&lt;R (V...)&gt; (*)(std::function&lt;R (V...)&gt;)&gt;\n{\n typedef fixpoint&lt;R, V...&gt; fp;\n};\n\ntemplate&lt;typename T&gt;\nauto getFix(T f) -&gt; typename getfixpoint&lt;T&gt;::fp::func_t {\n return getfixpoint&lt;T&gt;::fp::Fix(f);\n};\n\nint main(int argc, char* argv[])\n{\n auto fac = getFix([](std::function&lt;int (int)&gt; f) -&gt; std::function&lt;int (int)&gt;{\n return [f](int n)-&gt;int { if(n==0) return 1; else return n * f(n-1); };\n });\n std::cout&lt;&lt;fac(10)&lt;&lt;std::endl; //3628800\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:57:41.657", "Id": "36638", "Score": "0", "body": "You don't need `yfunc_t` anymore." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:52:28.393", "Id": "37229", "Score": "0", "body": "You are right. I leave it there because it may still be useful when I choose to make `fixpoint::Fix` a closure rather than a function. In this case, the type of `fixpoint::Fix` will be `yfunc_t`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T10:21:44.153", "Id": "3120", "ParentId": "3111", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T11:03:19.930", "Id": "3111", "Score": "6", "Tags": [ "c++", "c++11", "lambda" ], "Title": "Fixed point combinator in C++1x" }
3111
<p>I'm creating a class which uses a custom buffer. I want to offer the possibility to pass an external memory address (for higher interoperability between languages) or (for convenience) to specify a custom <code>allocator</code> type. The following code outlines what I mean:</p> <pre><code>template&lt;typename int_type, class alloc = void&gt; class uses_custom_buffers : uses_custom_buffers&lt;int_type, void&gt; { public: uses_custom_buffers&lt;int_type, alloc&gt;* set_buffer(std::size_t count, std::size_t size) { typename alloc::rebind&lt;int_type*&gt;::other pointer_alloc; int_type** buffer = pointer_alloc.allocate(count); for (std::size_t i = 0; i &lt; count; ++i) buffer[i] = this-&gt;m_alloc.allocate(size); this-&gt;uses_custom_buffers&lt;int_type, void&gt;::set_buffer(count, buffer, size); return this; } private: using uses_custom_buffers&lt;int_type, void&gt;::set_buffer; alloc m_alloc; }; template&lt;typename int_type&gt; class uses_custom_buffers&lt;int_type, void&gt; { public: uses_custom_buffers&lt;int_type, void&gt;* set_buffer(std::size_t count, int_type** buffers, std::size_t size) { this-&gt;m_buf = buffers; this-&gt;m_count = count; this-&gt;m_size = size; return this; } private: int_type** m_buf; std::size_t m_count, m_size; }; </code></pre> <p>Please note: This example doesn't care about deallocating any resource or exception safeness (to simplify matters). Do you see any kind of problems with that design?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T10:49:30.623", "Id": "4714", "Score": "0", "body": "Is this the entire code? Where is the base declaration of `uses_custom_buffers`? And is it an option to follow the STL allocator design?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T11:06:25.907", "Id": "4715", "Score": "0", "body": "@Kerrek: The base is a specialization of itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T11:24:56.673", "Id": "4716", "Score": "0", "body": "@Xeo: Does that work? I think I misread one of my compiler errors! D'oh. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:07:25.920", "Id": "4717", "Score": "0", "body": "@Kerrek SB - I'm following the STL allocator design. The template argument \"alloc\" could be any STL conform allocator type. That's exactly the same technique the STL containers are using." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:10:52.330", "Id": "4718", "Score": "0", "body": "I see. Hm. My compiler suggests you say `typename alloc::template rebind<int_type*>::other pointer_alloc;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:10:58.370", "Id": "4719", "Score": "0", "body": "@Kerrek SB - Using a specialization of itself as a base actually works. The class is not related to another class of the same template, when their template arguments differ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:16:11.190", "Id": "4720", "Score": "0", "body": "@FrEEzE2046: I see -- so you must take care not to ask for `uses_custom_buffers<T>`, or otherwise you'd be deriving from yourself? Why not make the base template `<typename T, class alloc = std::alloc<T>>`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:18:30.440", "Id": "4721", "Score": "0", "body": "@Kerrek SB - It's not that much to take care of. However, that won't even compile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:20:01.920", "Id": "4722", "Score": "0", "body": "@FrEEzE2046: Strange, works fine for me (GCC 4.6)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:20:35.243", "Id": "4723", "Score": "0", "body": "@Kerrek SB - Using `std::allocator<>` (please note, their's no `std::alloc<>`) wouldn't work here. I'm using `void` to indicate, that you don't want to use an allocator, but passing external memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:22:26.070", "Id": "4724", "Score": "0", "body": "@FrEEzE2046: Sorry about the typo. Hm. How about allowing the allocator class to decide whether you have external memory or want to allocate? That way you'd get a uniform interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:29:05.490", "Id": "4725", "Score": "0", "body": "@Kerrek SB - The idea behind passing external memory is compatibility to a library which could be used from other programming languages. So, it's not possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T12:29:39.607", "Id": "4726", "Score": "0", "body": "@KerrekSB let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/630/discussion-between-freeze2046-and-kerrek-sb)" } ]
[ { "body": "<p>I think that in order to be a good review candidate, this should be more than an \"outline.\" Like, there should be an example of how you intend to use it.</p>\n\n<p>But here's some stylistic feedback:</p>\n\n<ul>\n<li><code>CamelCase</code> your template parameter names: <code>IntType</code> (or just <code>T</code>), <code>Alloc</code>.</li>\n<li>You can (and should) use the injected class-name <code>uses_custom_buffers</code> inside the class itself, rather than typing out <code>uses_custom_buffers&lt;int_type, alloc&gt;</code> every time.</li>\n<li>Don't define multiple (member) variables on the same line.</li>\n<li>Mark your constructors <code>explicit</code> unless you <em>want</em> to enable the implicit conversion for some specific reason.</li>\n<li>Explicitly mark your base classes <code>public</code> and <code>private</code>, for clarity.</li>\n<li>Writing <code>std::size_t</code> instead of <code>size_t</code>, or <code>typename</code> instead of <code>class</code>, is just extra keyboard practice. Personally, I always go for the shorter versions.</li>\n<li>Always brace your <code>if</code> and <code>for</code> bodies. Don't <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"nofollow noreferrer\">goto fail</a>!</li>\n</ul>\n\n<hr>\n\n<pre><code> this-&gt;uses_custom_buffers&lt;int_type, void&gt;::set_buffer(count, buffer, size);\n</code></pre>\n\n<p>This seems complicated. Ideally we'd just write</p>\n\n<pre><code> set_buffer(count, buffer, size);\n</code></pre>\n\n<p>But since that <code>set_buffer</code> is located in a dependent base class, we actually have to write <code>this-&gt;</code> in front:</p>\n\n<pre><code> this-&gt;set_buffer(count, buffer, size);\n</code></pre>\n\n<p>And then we <em>still</em> have trouble, because the declaration of <code>set_buffer</code> in <code>uses_custom_buffers&lt;int_type, alloc&gt;</code> <em>hides</em> the declaration of <code>set_buffer</code> in <code>uses_custom_buffers&lt;int_type, void&gt;</code>! There are two clean ways to fix this, depending on what you want to do. <a href=\"https://godbolt.org/z/kzAApY\" rel=\"nofollow noreferrer\">The first</a> is to bring the hidden <code>set_buffer</code> back into scope with a <a href=\"https://en.cppreference.com/w/cpp/language/using_declaration\" rel=\"nofollow noreferrer\">using-declaration</a>:</p>\n\n<pre><code>using uses_custom_buffers&lt;int_type, void&gt;::set_buffer;\n</code></pre>\n\n<p>The second is to pick a different name for one or both of the functions in this overload set.</p>\n\n<blockquote>\n <p><em>\"If you have two [functions] that are doing something very very different, please, name them differently.\"</em> —<a href=\"https://www.youtube.com/watch?v=xTdeZ4MxbKo&amp;t=6m07s\" rel=\"nofollow noreferrer\">Titus Winters, 2018</a></p>\n</blockquote>\n\n<hr>\n\n<p>I would even argue that <code>uses_custom_buffers&lt;int_type, void&gt;</code> is doing something \"very very different\" from <code>uses_custom_buffers&lt;int_type, alloc&gt;</code>, and therefore it should be named differently.</p>\n\n<hr>\n\n<p>Very important:</p>\n\n<pre><code>typename alloc::rebind&lt;int_type*&gt;::other pointer_alloc;\n</code></pre>\n\n<p>This is (A) missing a <code>template</code> keyword, and (B) waaay too complicated for one line of code. Break it down by using a typedef:</p>\n\n<pre><code>using PointerAlloc = typename alloc::template rebind&lt;int_type *&gt;::other;\nPointerAlloc pointer_alloc;\n</code></pre>\n\n<p>However, this is (C) still broken, because it fails to use <code>allocator_traits</code>. You need to write this instead:</p>\n\n<pre><code>using PointerTraits = typename std::allocator_traits&lt;alloc&gt;::template rebind_traits&lt;int_type *&gt;;\nusing PointerAlloc = typename std::allocator_traits&lt;alloc&gt;::template rebind_alloc&lt;int_type *&gt;;\nPointerAlloc pointer_alloc;\n</code></pre>\n\n<p>And then on the next line:</p>\n\n<pre><code>int_type** buffer = pointer_alloc.allocate(count);\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>int_type **buffer = PointerTraits::allocate(pointer_alloc, count);\n</code></pre>\n\n<p>However, after all that, I am <em>still</em> super duper confused about where your allocator is supposed to come from! You just default-constructed it and immediately used it to allocate some memory? Where is the memory supposed to come from?</p>\n\n<p>If you want to use the standard allocator model, you need to provide a way for the user to <em>pass in</em> an allocator for you to use. You can't just default-construct one and expect it to magically know where its heap is located. (That happens to work for <code>std::allocator</code> because it just uses <code>new</code> and <code>delete</code>, which are global; but it is highly unlikely to work for any user-provided allocator type.)</p>\n\n<hr>\n\n<p>Let's put it all together and see how it looks:</p>\n\n<pre><code>template&lt;class T&gt;\nclass use_custom_buffers_base {\npublic:\n use_custom_buffers_base *set_buffers(size_t count, T **buffers, size_t size) {\n this-&gt;m_buf = buffers;\n this-&gt;m_count = count;\n this-&gt;m_size = size;\n return this;\n }\n\nprivate:\n T **m_buf;\n size_t m_count;\n size_t m_size;\n};\n\ntemplate&lt;class T, class Alloc&gt;\nclass use_custom_buffers : private use_custom_buffers_base&lt;T&gt;\n{\n using Base = use_custom_buffers_base&lt;T&gt;;\n using ATraits = std::allocator_traits&lt;Alloc&gt;;\n using PTraits = typename ATraits::template rebind_traits&lt;T*&gt;;\n using PAlloc = typename PTraits::allocator_type;\n\npublic:\n explicit use_custom_buffers(Alloc alloc) : m_alloc(std::move(alloc)) {}\n\n use_custom_buffers *set_buffers(size_t count, size_t size) {\n PAlloc pointer_alloc(m_alloc);\n T **buffers = PTraits::allocate(pointer_alloc, count);\n for (size_t i = 0; i &lt; count; ++i) {\n buffers[i] = ATraits::allocate(m_alloc, size);\n }\n this-&gt;Base::set_buffers(count, buffers, size);\n return this;\n }\n\nprivate:\n Alloc m_alloc;\n};\n</code></pre>\n\n<p>There's still work to do. <code>count</code> and <code>size</code> are strange names, especially since <code>size</code> is <em>also</em> a count (of <code>T</code> objects), not the \"size\" of any entity in the program. I decided to punt on the question of what to call <code>Base::set_buffers</code>. The arguments to <code>set_buffers</code> are in a weird order (length, pointer, other-length). It is unclear from your description whether anyone in the codebase actually cares about <code>use_custom_buffers_base</code> or whether it could be completely hidden away in a detail namespace — or, indeed, inlined into <code>use_custom_buffers</code>, since the inheritance relationship here seems like it's doing more harm than good.</p>\n\n<hr>\n\n<p>Finally, a possible performance issue: Why are you calling <code>allocate</code> in a loop?</p>\n\n<pre><code> for (size_t i = 0; i &lt; count; ++i) {\n buffers[i] = ATraits::allocate(m_alloc, size);\n }\n</code></pre>\n\n<p>Surely it would be more performant to allocate just <em>once</em> and then use pointers into different parts of that buffer?</p>\n\n<pre><code> auto ptr = ATraits::allocate(m_alloc, count * size);\n for (size_t i = 0; i &lt; count; ++i) {\n buffers[i] = ptr + (i * size);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T15:38:20.370", "Id": "402754", "Score": "0", "body": "Writing `size_t` instead of `std::size_t` means one of: (a) using C headers instead of C++ headers; (b) non-portable assumptions about the contents of headers; or (c) use of `using namespace std`. I don't recommend any of those, so consequently I disagree with you on that recommendation. Rest of the review is great: +1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T17:53:17.667", "Id": "402777", "Score": "0", "body": "@TobySpeight: FWIW, I have nothing against (a); I agree with your recommendation against (c). Can you elaborate on (b)? That is, let's assume that my assumption is specifically \"`size_t` is provided by `<cstddef>`.\" You claim this assumption is \"non-portable.\" I counter-claim that this assumption *is* portable (that is, code using this assumption will compile on every C++ platform in the world; which is the best anyone can hope for from \"portability\"). Can you name a platform where such code wouldn't compile? Lastly, there's at least (d): [`using std::size_t;`](https://godbolt.org/z/TAc7N1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:17:06.740", "Id": "402783", "Score": "0", "body": "The problem with (b) is that although it might work with the compilers you know of, the Standard does not mandate that it will work with all compilers (including the really good compilers we'll want to use in The Future). I prefer to rely as much as possible on what's documented (and therefore a reportable bug when I'm wrong) than on what's optional. To some extent, it's a version of the principle that made the Internet Protocol suite so successful - be conservative in what you emit and liberal in what you accept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-27T18:19:29.533", "Id": "402784", "Score": "0", "body": "And yes, (d) is better than (a) to (c)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T03:02:35.870", "Id": "208320", "ParentId": "3112", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T10:37:51.790", "Id": "3112", "Score": "8", "Tags": [ "c++", "design-patterns", "memory-management" ], "Title": "Use of external memory or a custom allocator" }
3112
<p>So I have this array:</p> <pre><code>$arr = ('a' =&gt; 343, 'b' =&gt; 34, 'c' =&gt; 65, 'd' =&gt; 465); </code></pre> <p>which could also be</p> <pre><code>$arr = ('a' =&gt; 343, 'b' =&gt; 34, 'c' =&gt; 65); </code></pre> <p>Can the following code be improved into one line?</p> <pre><code>if(isset($arr['d'])) $something = $arr['d']; unset($arr['d']); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T14:55:47.187", "Id": "4727", "Score": "1", "body": "What is your goal? To always remove elements called 'd'? Or to have a maximum of 3 key / values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T14:56:35.913", "Id": "4728", "Score": "1", "body": "yes, to remove 'd' keys" } ]
[ { "body": "<pre><code>if(isset($arr['d'])) $something = $arr['d'];\nunset($arr['d']);\n</code></pre>\n\n<p>Well... If <code>arr['d']</code> is not set, then you don't need to unset it. So this will save an unnecessary call sometimes:</p>\n\n<pre><code>if(isset($arr['d']))\n{\n $something = $arr['d'];\n unset($arr['d']);\n}\n</code></pre>\n\n<p>If you don't care for <code>$something</code>, then you can just do</p>\n\n<pre><code>unset($arr['d']);\n</code></pre>\n\n<p>Which is then one line. You could also write</p>\n\n<pre><code>if (isset($arr['d']) &amp;&amp; ($something = $arr['d']) !== null) unset($ar['d']);\n</code></pre>\n\n<p>That is one line as well, but will fail to do what you like if <code>$something</code> is <code>null</code>. And from the point of readability it's questionable whether this is an improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T20:58:27.980", "Id": "3131", "ParentId": "3113", "Score": "4" } }, { "body": "<p>No, there is no way to squash it into one line <em>and</em> keep it readable in any way.</p>\n\n<pre><code>$something = isset($arr['d'])\n ? $arr['d']\n : null;\nunset($arr['d']);\n</code></pre>\n\n<p>This is just a minor enhancement, I know, but I think if one is familiar with the ternary operator its slightly better readable. At the end I don't think there is anything more optimizable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T21:18:12.657", "Id": "3150", "ParentId": "3113", "Score": "2" } }, { "body": "<p>No reason why you can't right your own function to do this, obviously the function itself is more than 1 line but will make it a lot easier to use if you're calling it multiple times in your project.</p>\n\n<pre><code>function getValue(&amp;$array, $key) {\n $value = isset($array[$key]) ? $array[$key] : null;\n unset($array[$key]);\n return $value;\n}\n\n$arr = array('a' =&gt; 343, 'b' =&gt; 34, 'c' =&gt; 65, 'd' =&gt; 465);\n\n$val = getValue($arr, 'd');\n</code></pre>\n\n<p>If you <code>var_dump</code> the two variables it will give you </p>\n\n<pre><code>// $val\nint 465\n// $arr\narray\n 'a' =&gt; int 343\n 'b' =&gt; int 34\n 'c' =&gt; int 65\n</code></pre>\n\n<p>If the key does not exist <code>$val</code> will simply be <code>NULL</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:53:43.797", "Id": "3387", "ParentId": "3113", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T14:51:48.437", "Id": "3113", "Score": "7", "Tags": [ "php" ], "Title": "Fetching an array value and removing it" }
3113
<p>I want to be able to do <code>/contacts/Matt%20Phillips</code> and <code>/contacts/1</code> and have both of them return a contact. The way I did that was to try and parse an <code>int</code> from the captured parameter and call the <code>Id</code> method instead of the <code>byName</code> method like so:</p> <pre><code> [WebGet(UriTemplate="{param}"] public Contact SingleParam(string param) { int x; if (int.TryParse(param, out x)) { return GetContactById(x); } else { return GetContactByName(param); } } private Contact GetContactByName(string param) { var contact = from c in contacts where c.Name.Equals(param) select c; if (!contact.Any()) { return null; } return contact.Single(); } public Contact GetContactById(int id) { var contact = from c in contacts where c.ContactId == id select c; if (!contact.Any()) { return null; } return contact.Single(); } </code></pre> <p>But it seems clunky to me. Anyone have suggestions for a better way to do this?</p>
[]
[ { "body": "<p>There is an easier way. You can use uri templates to help you by making both handling methods operations.</p>\n\n<pre><code>[ServiceContract]\npublic class ContactsApi\n{\n [WebGet(UriTemplate=\"{id}\")]\n public string GetById(int id)\n {\n //return by id\n }\n\n [WebGet(UriTemplate=\"{first} {last}\")]\n public string GetByName(string first, string last)\n {\n //return by name\n }\n}\n</code></pre>\n\n<p>If you do a GET on /contacts/Matt%20Phillips the second method will get invoked. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T15:13:18.790", "Id": "4737", "Score": "0", "body": "Ah. I suppose the key is that I'm using the space between first and last name. If I was returning a list by first names for example then i wouldn't be able to do it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T08:10:22.937", "Id": "3118", "ParentId": "3117", "Score": "3" } }, { "body": "<p>Your question is already answered, but this is an addition to your LINQ statements.\nBy first using <code>Any()</code> and then <code>Single()</code>, you're executing two database queries.\nYou could save one, by using <code>SingleOrDefault()</code>, like this:</p>\n\n<pre><code>var contact = (from c in contacts\n where c.Name.Equals(param)\n select c).SingleOrDefault();\nreturn contact;\n</code></pre>\n\n<p>Another addition, if you choose not to use <code>SingleOrDefault()</code>, first write the expected condition, then the exception:</p>\n\n<pre><code>if (contact.Any())\n{\n return contact.Single();\n}\nreturn null;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T12:45:08.057", "Id": "3166", "ParentId": "3117", "Score": "1" } } ]
{ "AcceptedAnswerId": "3118", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T05:32:22.517", "Id": "3117", "Score": "4", "Tags": [ "c#", ".net", "linq", "asp.net", "wcf" ], "Title": "Is this a good way to handle Web API UriTemplates?" }
3117
<p>Is this the best way to get access to the parent scope when dealing with complex objects literals?</p> <p>I find this a bit ugly, and obviously the best solution would never be involving calling it by name directly, but by saving the state of the previous scope. I tried it with <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow">bind()</a> but didn't get it to work properly.</p> <pre><code>var object = {   name : 'foo',   getName : (function(){       return function(that){ return { a : 111, b : that.name, c : function(){ return this.b; } } }(this);  }) }; object.getName().b // 'foo' </code></pre>
[]
[ { "body": "<p>I understand that you are just experimenting with closures, because your code should be a simple geter like that... </p>\n\n<pre><code>var object = {\n  name : 'foo',\n  getName : function(){ //closure\n return {\n a : 111,\n b : this.name, // variable th is avaliable in the inner scope\n c : function(){\n return this.b;\n }\n }\n  }\n};\n\nobject.getName().b // 'foo'\n</code></pre>\n\n<p>This does the same as your example:</p>\n\n<pre><code>var object = {\n  name : 'foo',\n  getName : (function(){ //closure\n var th=this; // a new var introduced in a closure\n      return function(){ \n return {\n a : 111,\n b : th.name, // variable th is avaliable in the inner scope\n c : function(){\n return this.b;\n }\n }\n }();\n  })\n};\n\nobject.getName().b // 'foo'\n</code></pre>\n\n<p>[edit]</p>\n\n<p><code>this</code> in JS depends on where the function is called as well, so if you want a nice encapsulation Try this:</p>\n\n<pre><code>var object = {}\n(function(){\n\n var _name='foo';\n\n object.getName=function(){\n return _name;\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T12:32:21.853", "Id": "4733", "Score": "0", "body": "is it possible to make 'getName' an object by itself that has access to the parent object, without the need to invoke the function on every call?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T13:30:40.767", "Id": "4734", "Score": "0", "body": "There are at least two totally different ways (except yours) to do it. But I still don't see why `getName` should be an object. It looks like a simple getter function and it should be one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T13:37:47.660", "Id": "4735", "Score": "0", "body": "this is just an example code, and it seems that i picked the wrong names.. lets call it 'a' and 'b' then, instead of 'name' and 'getName'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T14:26:56.563", "Id": "4736", "Score": "0", "body": "Then I'd say that my second example - caching the correct `this` in a variable and managing its scope - suits your case. But i don't recommend using this keyword and trying to simulate object-oriented coding in JS. It might hurt some day." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T12:01:37.400", "Id": "3122", "ParentId": "3121", "Score": "4" } } ]
{ "AcceptedAnswerId": "3122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T11:01:44.253", "Id": "3121", "Score": "3", "Tags": [ "javascript" ], "Title": "this scope for parent object within inner object" }
3121
<p>This is my first attempt to write a simple C++ program:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; using namespace std; class Book { public: char title[30]; Book(char *tit) { strcpy(title,tit); }; char *gettitle() { return title; } }; int main() { Book miolibro((char *)"aaa"); cout &lt;&lt; miolibro.gettitle() &lt;&lt; endl; std::vector&lt;Book&gt; vettorelibri; for (int i=0; i&lt;10; i++) { Book l( (char *)"aaa" ); // i tried something like "aaa"+i but it does not work vettorelibri.push_back(l); } for(int i=0; i&lt;10; i++) { cout &lt;&lt; vettorelibri[i].gettitle() &lt;&lt; endl; } }; </code></pre>
[]
[ { "body": "<p>If you're using C++ instead of C, you should use <code>std::string</code> instead of <code>char</code> arrays. Include <code>&lt;string&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T17:27:19.367", "Id": "3125", "ParentId": "3123", "Score": "6" } }, { "body": "<p>There are several issues:</p>\n\n<ul>\n<li><p>If you use getter method for the title in <code>Book</code>, you probably want to hide the title field, so make it private</p></li>\n<li><p>If the title length constraint for 30 is arbitrary, you might want to change the title field to a pointer to string (learn more about what kind of strings you really want here: <a href=\"http://en.cppreference.com/w/cpp/string\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/string</a>)</p></li>\n<li><p>If you want to use the <code>Book</code> constructor with string literals (e.g. <code>\"aaa\"</code>), you should add const to the parameter type</p></li>\n<li><p>In the <code>Book</code> constructor <code>strcpy</code> is dangerous, because it doesn't check lengths of the strings (buffer overflow possible), you should better use <a href=\"http://en.cppreference.com/w/cpp/string/narrow/strncpy\" rel=\"nofollow noreferrer\"><code>strncpy</code></a>, or if you decide to use constants, you don't have to copy at all</p></li>\n<li><p>It is preferable to use camelcase or underscores for separating words in identifiers for readability, so rename the <code>gettitle</code> to <code>getTitle</code> or <code>get_title</code>, same holds for <code>miolibro</code> and <code>vettorilibri</code>.</p></li>\n<li><p>If you want to avoid casting string literals, use constants instead</p></li>\n<li><p>If you want to pass an object of a type you defined to an output stream (e.g. cout in your case), it is preferable to overload the <code>operator&lt;&lt;</code>.</p></li>\n<li><p>If you use a namespace (using keyword), you don't have to type the whole names unless a name clash is possible, in your case you can just write <code>vector</code> instead of <code>std::vector</code>.</p></li>\n<li><p>The proper way of constructing a new object is to call a constructor using the new operator, so you should replace the <code>Book l(...)</code>, which is implicit conversion AFAIK, with <code>new Book(...)</code>. Than should <code>vettorelibri.push_back(new Book(\"aaa\" + i));</code> work as expected, given you switch to constants (<code>const char*</code> instead <code>of char*</code>).</p></li>\n<li><p>The preferred way of iterating over a <code>vector</code> is using an iterator instead of explicit indexing. You can read about that here: <a href=\"https://stackoverflow.com/questions/409348/iteration-over-vector-in-c\">https://stackoverflow.com/questions/409348/iteration-over-vector-in-c</a></p></li>\n</ul>\n\n<p>There might be some more problems, but this should be enough for a start:).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T09:58:48.723", "Id": "4741", "Score": "0", "body": "thanks! camelcase and namespacing are good style advices. then, thanks for string reference link and also iterator is a good things i have to learn!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T12:01:02.090", "Id": "4871", "Score": "1", "body": "Why he should use new operator to build an object? Is complete \"legal\" to build objects without the new operator. Why waste resources dynamic allocating an object when this is not needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T17:01:45.213", "Id": "4874", "Score": "0", "body": "`push_back(new Book(/*...*/))` leaks memory when `push_back` throws. Also, there is no reason not to construct a `Book` on the stack." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T21:38:33.670", "Id": "4880", "Score": "0", "body": "I think the problem here is that he doesn't know how to create a Book object, I find new to be more general, but you are right, he could just as well use stack or malloc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T14:23:16.263", "Id": "5006", "Score": "1", "body": "In addition to making the constructor's char* parameter const, the member function gettitle() should be declared as a constant member function: `char *gettitle() const`. The const keyword at the end simply means that this function won't modify any member variables inside the class. This is part of the concept called \"const-correctness\", leading to better programs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T00:04:28.910", "Id": "13464", "Score": "0", "body": "-1; `new` is certainly the wrong way to go here, and you're advising the wrong way to handle the using-directive." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T17:35:11.333", "Id": "3126", "ParentId": "3123", "Score": "5" } }, { "body": "<p>It has been commented that when working in C++ you should use <code>std::string</code>. Assuming you want to stay with C style strings (or at least understand how you ought to work with them, in case you ever have to), I have the following suggestions:</p>\n\n<pre><code>strcpy(title,tit);\n</code></pre>\n\n<p><code>tit</code> can be larger than the buffer <code>title</code> allows.[1] In that case, your program will crash or worse, continue running while corrupting some other part of memory. To avoid that you should always use functions which let you track the size of the destination buffer and detect overflow. For example:</p>\n\n<pre><code>strncpy(title, sizeof(title)-1, tit);\ntitle[sizeof(title) - 1] = 0;\n</code></pre>\n\n<p>This has some undesirable traits in that it will silently truncate the string if the input is larger than the destination. If you are working on a system that has the non-standard <code>strlcpy</code>, that has some cleaner error conditions:</p>\n\n<pre><code>if (strlcpy(title, sizeof(title), tit) &gt;= sizeof(title)))\n{\n // TODO: decide how to handle the error (in your case maybe throw\n // an exception)\n}\n</code></pre>\n\n<p>Moving along the spectrum (from code that crashes given large input, to code that truncates the input, to code that errors out when the buffer in insufficient...), you might also want to dynamically allocate memory for this.</p>\n\n<pre><code>char *title;\n\nBook(const char *tit)\n{\n title = strdup(tit);\n if (!title) { throw std::bad_alloc(); }\n}\n</code></pre>\n\n<p>This creates complications if a <code>Book</code> object is ever copied, so you need to handle that:</p>\n\n<pre><code>Book(const Book &amp;b)\n{\n title = strdup(b.title);\n if (!title) { throw std::bad_alloc(); }\n}\n</code></pre>\n\n<p>And it needs to be freed when your object is destroyed:</p>\n\n<pre><code>~Book()\n{\n free(title);\n}\n</code></pre>\n\n<p>If this seems too complicated it's because for higher-level C++ code it probably is. <code>std::string</code> will take care of all of this for you. Note though that the memory layout of your object will be substantially different with these dynamic-memory approaches.[2]</p>\n\n<p>Next up...</p>\n\n<pre><code>Book miolibro((char *)\"aaa\");\n</code></pre>\n\n<p>As a general rule, having to do casts like this is often an indicator that you're doing something wrong. :-) When writing code and reviewing the work of others' I tend to try to avoid as many unnecessary casts as possible. A lot of times these mask bugs, for example casting a function to an incorrect function pointer type can produce crashes, or casting away <code>const</code> may crash when someone tries to modify a read-only buffer. For reasons like this it's a good habit to watch for inappropriate casts when reading code, and be sure not to introduce them yourself; code like this should <b>offend</b> your sensibilities. :-) [3]</p>\n\n<p>In your case, the issue is that string literals have the type <code>const char*</code>, so the compiler complains that you are passing this to something that doesn't have <code>const</code>. So what you need to do here is:</p>\n\n<pre><code>Book(const char *tit)\n{\n // ...\n}\n</code></pre>\n\n<p>Footnotes and tangential comments:<br/>\n[1] If there are any English speaking people who might read your code, I suggest you come up with a better name than <code>tit</code> for that variable.<br/>\n[2] In the earlier example, characters of <code>title</code> exists alongside any other members of the class. When using dynamic memory, there's now an extra pointer dereference going on to get to the characters. In most cases this won't make a difference but you can think of theoretical cases where the former is desired over the latter.<br/>\n[3] Side note: In my experience one way to tell that someone doesn't know what they're doing in C/C++ is the use of casts. A sloppy programmer will write code that the compiler rejects, and then to get it \"working\" quickly they'll introduce casts to silence compiler warnings instead of fixing the actual problem. If you are working on a team where people do this, I find it's sometimes a good indication to be skeptical of that person's work for other reasons.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T09:41:18.117", "Id": "4739", "Score": "0", "body": "thank you very much for comments!\nyes, the string stuffs seems to be like too-lowlevel for me (i've never used c before but i have to deal with it), and for now i think i'll use std even if is a good thing know c-style string handling, thanks very much for the examples and collateral problem explanation!\nthen, ok, i'll try to train my sensibility on bad use of cast, thanks for this life advice ahah : )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T14:19:14.283", "Id": "5005", "Score": "1", "body": "Please note that strdup() is not standard C/C++ and may not work on C/C++ compilers. I would not advise beginners to use non-standard functions like this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T00:08:41.447", "Id": "13465", "Score": "0", "body": "You might want to clarify that the advice on `strlcpy` with termination using `sizeof` and on `strdup` an dynamic allocation are not possible to follow at the same time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T20:25:05.803", "Id": "3128", "ParentId": "3123", "Score": "13" } }, { "body": "<p>I know I'm a little late, but let's take a look.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>There's no need for this. Really. You're already qualifying most of your names -- keep doing that.</p>\n\n<pre><code>class Book {\n public:\n char title[30];\n\n Book(char *tit) {\n strcpy(title,tit);\n };\n\n char *gettitle() {\n return title;\n }\n};\n</code></pre>\n\n<p>As others have said, use <code>std::string</code>. As others have not said: <strong>definitely</strong> use <code>std::string</code>. You cannot sanely mix raw C strings and exceptions without smart pointers. In fact, mixing any dynamic allocation with exceptions without smart pointers is a great way to drive yourself insane, but in this case it's not even remotely justified as there's a class that does exactly what you want.</p>\n\n<p>Now, let's see how <code>Book</code> can be rewritten:</p>\n\n<pre><code>class Book {\n std::string title;\n\n public:\n Book(std::string const&amp; t) : title(t)\n {}\n\n std::string get_title() const {\n return title;\n }\n};\n</code></pre>\n\n<p>Notice the funny syntax in the constructor. That's called a constructor-initializer, and it's a good idea to initialise your objects that way when possible -- it might be faster, and it makes it more explicit.</p>\n\n<p>Notice that the string is passed by const reference. This means you don't copy it, but that you also can't change it -- you don't want to change it, so that's okay. It has another benefit, but I'll show that later.</p>\n\n<p>Finally, we make <code>get_title</code> const so that you can call it on a const instance of <code>Book</code>. Not very important in your minimal code, but it pays off to be as <a href=\"http://www.parashift.com/c++-faq-lite/const-correctness.html\" rel=\"nofollow\">const-correct</a> as possible.</p>\n\n<pre><code>int main() {\n Book my_book(\"aaa\");\n std::cout &lt;&lt; my_book.get_title() &lt;&lt; '\\n';\n</code></pre>\n\n<p>Yay, you know about how to initialise objects that don't have a default constructor. That's a handy thing to know, and less common than I'd like to see it. Notice that we don't need the cast any more -- in fact, we don't even need to explicitly call <code>std::string</code>s constructor. That's because <code>std::string</code> can be constructed from a <code>char const*</code>, which <code>\"aaa\"</code> converts to. (If you're curious, <code>\"aaa\"</code> <em>isn't</em> itself <code>char const*</code> -- it's <code>char const[4]</code>.)</p>\n\n<p>You used <code>std::endl</code> here, but there's no need for that. You can just output a newline character, and it'll get printed eventually -- <code>std::endl</code> makes sure it gets printed immediately, but unless the program crashes, it'll be outputted equally soon without it as far as the user can tell.</p>\n\n<pre><code> std::vector&lt;Book&gt; vector_of_books; \n for (int i=0; i&lt;10; i++)\n vector_of_books.push_back(Book(\"aaa\"));\n</code></pre>\n\n<p>Here's code that does exactly what you were doing, but with <code>Book</code>'s new constructor and with no temporary. I think this is just as clear, but some may disagree. An even clearer way to do this is</p>\n\n<pre><code> std::vector&lt;Book&gt; vector_of_books(10, Book(\"aaa\"));\n</code></pre>\n\n<p>That'll do the same thing, and describes the intent more clearly.</p>\n\n<p>As an aside: you say that <code>\"aaa\"+i</code> didn't work. That is indeed something that won't work, partly because C++ doesn't provide an all-that-easy way of joining a string together with something else. Your best bet would be <code>\"aaa\" + boost::lexical_cast&lt;std::string&gt;(i)</code>, unless you wanted to go through the trouble of explicitly creating a <code>stringstream</code>. There are also functions like <code>atoi</code> and <code>snprintf</code>, but those are generally less safe or harder to use.</p>\n\n<pre><code> for (int i = 0; i &lt; 10; ++i) {\n std::cout &lt;&lt; vector_of_books[i].get_title() &lt;&lt; '\\n';\n }\n};\n</code></pre>\n\n<p>This code is perfectly fine to use -- I applied some cosmetic changes, but they don't particularly matter. Gabriel is suggesting you use iterators, but I don't think those make things any better:</p>\n\n<pre><code> for (std::vector&lt;Book&gt;::iterator it = vector_of_books.begin();\n it &lt; vector_of_books.end();\n ++it) {\n std::cout &lt;&lt; *it &lt;&lt; '\\n';\n }\n</code></pre>\n\n<p>The code is much longer and the bonus in efficiency isn't going to matter. Granted, with C++11 you could change the <code>std::vector&lt;Book&gt;::iterator</code> into <code>auto</code>, and then it would be decent, but in C++11 you could also just do:</p>\n\n<pre><code> for (std::string const&amp; book : vector_of_books)\n std::cout &lt;&lt; book &lt;&lt; '\\n';\n</code></pre>\n\n<p>If this looks confusing, don't worry about it; it's most important that you get the basics down (like using <code>std::string</code>), and iterating is just a nice option that you can keep in mind for when it's more efficient/clearer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T14:04:32.923", "Id": "13475", "Score": "0", "body": "Great answer!! BTW, you wrote `Bool` in one place where you meant `Book`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-03T00:33:43.053", "Id": "8610", "ParentId": "3123", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T16:26:57.240", "Id": "3123", "Score": "10", "Tags": [ "c++" ], "Title": "Critique my first C++ \"Hello World\" program" }
3123
<p>I need to write some JavaScript code that will take a JSON string, parse it, and return the names of the most-deeply nested properties. For example, for this input:</p> <pre><code>var json = "{\ foo: {\ bar: 'something',\ baz: {\ jack: 'other',\ },\ bob: {\ bill: 'hello',\ bilbo: 11,\ baggins: {\ fizz: 'buzz'\ finger: 'bang'\ }\ }\ }\ }"; </code></pre> <p>it should return <code>['fizz', 'finger']</code>. There are a couple of caveats:</p> <ul> <li>the parsing must be done "manually"- i.e. I can't use <code>eval</code> or a JS library to parse the JSON</li> <li>the JSON property values are guaranteed to be strings, numbers, or objects, i.e. no arrays</li> </ul> <p>Here's what I've come up with so far. The main function is <code>findDeepestLeaveNodes</code>. At the moment the code is a bit inefficient as it has to iterate twice over the whole input String. I'd like to improve this if possible, and am also looking for suggestions for improving the code quality.</p> <pre><code>var constants = { BLOCK_START: '{', BLOCK_END: '}' }; function findDeepestLeaveNodes(json) { var maxNesting = getMaxNesting(json); var currentNestLevel = 0; var results = []; var jsonLength = json.length; for (var currentCharIndex = 0; currentCharIndex &lt; jsonLength; currentCharIndex++) { var currentChar = json.charAt(currentCharIndex); //console.log("Nesting level " + currentNestLevel + " at character '" + currentChar + "'"); if (currentChar == constants.BLOCK_START) { // FIXME The following parsing is fairly fragile. It doesn't handle the possibility // that a '}' or ',' way occur inside a String and therefore do always close a block or // separate sibling JSON properties. To handle this we'd need to write a proper JSON parser. if (++currentNestLevel == maxNesting) { // read the content of the current block var blockEndIndex = json.indexOf(constants.BLOCK_END, currentCharIndex); var currentBlock = json.substring(currentCharIndex + 1, blockEndIndex); // Each position in the properties array will contain a property name and it's value var properties = currentBlock.split(','); for (var i = 0; i &lt; properties.length; i++) { // parse out the property name var property = properties[i]; var separatorPosition = properties[i].indexOf(':'); var propertyName = property.substring(0, separatorPosition); results.push(propertyName.trim()); } } } else if (currentChar == constants.BLOCK_END) { --currentNestLevel; } } return results; } function getMaxNesting(json) { var jsonlength = json.length; var currentNestLevel = 0; var maxNestLevel = 0; for (var i = 0; i &lt; jsonlength; i++) { var currentChar = json.charAt(i); if (currentChar == constants.BLOCK_START) { ++currentNestLevel; } else if (currentChar == constants.BLOCK_END) { // update maxNestLevel if necessary maxNestLevel = Math.max(currentNestLevel, maxNestLevel); --currentNestLevel; } } return maxNestLevel; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-26T03:29:38.427", "Id": "6599", "Score": "2", "body": "Technically that isn't valid JSON, the keys aren't strings since they don't have quotes around them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T08:01:36.527", "Id": "19999", "Score": "0", "body": "Why are you not allowed to use library code?" } ]
[ { "body": "<p>I'd write it as a recursive descent parser since this is quite simple:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Recursive_descent_parser</a></p>\n\n<p>Actually I already did this a couple of years back, when I wanted to create something that simply formats and highlights JSON a bit. If you can understand it, then you can modify it to your needs:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n.str\n{\n color: green;\n}\n\n.obj\n{\n font-weight: bold;\n}\n\n.num\n{\n color: red;\n}\n &lt;/style&gt;\n &lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n\nString.prototype.repeat = function(n) {\n result = '';\n for (var i = 0; i &lt; n; i++) result += this;\n return result;\n}\n\nfunction jsonFormater() {\n this.reset = function() {\n this.txt = '';\n this.pos = 0;\n this.result = '';\n this.indent = 0;\n this.classes = Array();\n };\n\n this.undoindent = function() {\n this.indent -= 4;\n this.nline();\n };\n\n this.doindent = function() {\n this.indent += 4;\n this.nline();\n };\n\n this.nline = function() {\n this.result += '&lt;br /&gt;' + '&amp;nbsp;'.repeat(this.indent);\n };\n\n this.chClass = function(neu) {\n if (this.classes.length &gt; 0) this.result += '&lt;/span&gt;';\n this.result += '&lt;span class=\"' + neu + '\"&gt;';\n this.classes.push(neu);\n };\n\n this.endClass = function() {\n this.classes.pop();\n this.result += '&lt;/span&gt;';\n if (this.classes.length &gt; 0) this.result += '&lt;span class=\"' + this.classes[this.classes.length - 1] + '\"&gt;';\n };\n\n this.formatJson = function(txt) {\n this.txt = txt;\n this.pos = 0;\n this.result = '';\n while (this.pos &lt; this.txt.length) {\n if (this.txt[this.pos] == '{') this.parseObj();\n else if (this.txt[this.pos] =='[') this.parseArray();\n this.pos++;\n }\n\n return this.result;\n }\n\n this.parseObj = function(ende) {\n if (typeof ende =='undefined') var ende = '}';\n this.chClass('obj');\n\n do {\n if ((this.txt[this.pos] == '{') || (this.txt[this.pos] == '[')) this.nline();\n this.result += this.txt[this.pos];\n if (this.txt[this.pos] == ',') this.nline();\n if ((this.txt[this.pos] == '{') || (this.txt[this.pos] == '[')) this.doindent();\n this.pos++;\n if (this.txt[this.pos] == '{') this.parseObj();\n if (this.txt[this.pos] == '[') this.parseArray();\n if (this.txt[this.pos] == '\"') this.parseString();\n if (/\\d/.test(this.txt[this.pos])) this.parseNum();\n if ((this.txt[this.pos] == '}') || (this.txt[this.pos] == ']')) this.undoindent();\n } while ((this.pos &lt; this.txt.length) &amp;&amp; (this.txt[this.pos] != ende));\n\n this.result += this.txt[this.pos];\n this.pos++;\n this.endClass();\n };\n\n this.parseArray = function() {\n this.parseObj(']');\n };\n\n this.parseString = function() {\n this.chClass('str');\n do {\n this.result += this.htmlEscape(this.txt[this.pos]);\n this.pos++;\n } while ((this.pos &lt; this.txt.length) &amp;&amp; ((this.txt[this.pos] != '\"') || (this.txt[this.pos - 1] == '\\\\')));\n\n this.result += this.htmlEscape(this.txt[this.pos]);\n this.pos++;\n this.endClass();\n };\n\n this.parseNum = function() {\n this.chClass('num');\n do {\n this.result += this.txt[this.pos];\n this.pos++;\n } while ((this.pos &lt; this.txt.length) &amp;&amp; (/[\\d\\.]/.test(this.txt[this.pos])));\n\n this.endClass();\n };\n\n this.htmlEscape = function(txt) {\n return txt.replace(/&amp;/,'&amp;amp;').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;').replace(/\"/g, '&amp;quot;');\n };\n\n this.reset();\n}\n\nvar parser = new jsonFormater();\n\nfunction go(txt) {\n document.getElementById('ausgabe').innerHTML = parser.formatJson(txt);\n parser.reset();\n}\n\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body onLoad=\"go(document.getElementById('thetextarea').value);\"&gt;\n &lt;textarea id=\"thetextarea\" rows=\"25\" cols=\"70\" onKeyUp=\"go(this.value);\"&gt;[{\"Dies\":\"Ist ein Beispiel...\",\"mit\":[\"Arrays\",\"und\",\"so\"]},{\"alles\":\"sch&amp;ouml;n verschachtelt...\"},\"tippt einfach json-zeugs in dem grossen Feld.\",\"Die Anzeige aktualisiert sich sofort...\",\"Die Formatierungen sind als &amp;lt;style&amp;gt; gespeichert. Ihr k&amp;ouml;nnt sie so beliebig &amp;auml;ndern.\",{\"Zahlen\":1,\"sind\":[1,4,55.67],\"auch\":\"sch&amp;ouml;n\"}]&lt;/textarea&gt;\n &lt;div id=\"ausgabe\"&gt;&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T20:36:58.357", "Id": "3129", "ParentId": "3124", "Score": "3" } }, { "body": "<p>I would do this in two steps:</p>\n\n<ol>\n<li>Parse the json</li>\n<li>Find the deepest node of that object. </li>\n</ol>\n\n<p>When you separate your code like that, you wind up with two reusable functions instead of one single-use function, which is always a good thing.</p>\n\n<p>I wrote the json parser as a self executing anonymous function that returns an object. What this does is encapsulate all the helper functions so they aren't exposed to outside functions and results in a object with just one method: <code>decode</code>.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var JSON = (function() {\n function charIsLetter(c) {\n return ('A' &lt;= c &amp;&amp; c &lt;= 'Z') || ('a' &lt;= c &amp;&amp; c &lt;= 'z');\n }\n function charIsNumber(c) {\n return '0' &lt;= c &amp;&amp; c &lt;= '9';\n }\n\n function decodeInt(s) {\n for ( //iterate through the string while it is a number\n var i = 0, c = s.charAt(0);\n i &lt; s.length &amp;&amp; charIsNumber(c);\n c = s.charAt(++i)\n );\n\n //return [integer, the rest of the string]\n return [parseInt(s.substring(0,i), 10), s.substring(i)];\n }\n\n function decodeString(s) {\n var q = s.charAt(0), //what quotation wraps the string?\n str = \"\";\n\n for (var i=1;i&lt;s.length;i++) { //iterate through the string\n c = s.charAt(i);\n if (c == \"\\\\\") {//if the next quotation is escaped, skip it\n i++;\n continue;\n }\n\n if (c == q)\n return [str, s.substring(i+1)]; //return [the string, what comes after it]\n\n str += c;\n }\n\n throw \"String doesn't have closing quote (\"+q+\") at: \" + s;\n }\n\n function decodeObject(s) {\n s = s.substring(1); //remove first {\n var ob = {}, key, val;\n\n while (true) {\n if (s.length == 0)\n throw \"Reached end of string while looking for '}'\";\n\n s = s.replace(/^\\s+/m, \"\"); //remove excess whitespace\n\n if (s.charAt(0) == \"}\")\n return [ob, s.substring(1)]; //return the object and what's left over\n\n key = decode2(s); //key = [decoded string/number/etc, string remaining]\n s = key[1].substring(1); //s is now the leftovers, remove \":\"\n\n val = decode2(s); //val = [decoded string/number/etc, string remaining]\n s = val[1]; //s is now the leftovers\n\n if (s.charAt(0) == \",\") //if there is a comma after the value, remove it\n s = s.substring(1);\n\n ob[key[0]] = val[0];\n }\n }\n\n function decodeImproperString(s) {\n for ( //iterate the string while the character is a letter\n var i = 0, c = s.charAt(0);\n i &lt; s.length &amp;&amp; charIsLetter(c);\n c = s.charAt(++i)\n ); \n return [s.substring(0,i), s.substring(i)]; //return [the string, what comes after it]\n }\n\n function decode2(s) {\n s = s.replace(/^\\s+/m, \"\"); //remove whitespace from the beginning of the string\n var c = s.charAt(0);\n\n if ('0' &lt;= c &amp;&amp; c &lt;= '9') //value is a number\n return decodeInt(s);\n if (c == \"'\" || c == '\"') //value is a string\n return decodeString(s);\n if (c == '{') //value is an object\n return decodeObject(s);\n\n if (charIsLetter(c))\n return decodeImproperString(s);\n\n throw \"Unexpected character \" + c + \" at:\" + s;\n }\n\n\n return {\n decode: function(s) {\n var result = decode2(s);\n return result[0];\n }\n };\n})();\n</code></pre>\n\n<p>Now that we've got a way to parse the json, we need a way to find the deepest child. The way I went about doing this is a recursive function that returns the depth of it's children, 0 if it has no object as a child. It increments this depth for it's children and returns the child with the maximum depth.</p>\n\n<pre><code>function deepestObject(ob) {\n var ar = []; //array of objects and their depth\n\n for (var key in ob) {\n if (ob.hasOwnProperty(key)) {\n if (Object.toType(ob[key]) == \"object\") {\n var child = deepestObject(ob[key]);\n child.depth++;\n ar.push(child);\n }\n }\n }\n\n var max = {depth: 0, children: ob};\n for (var i=0; i&lt;ar.length;i++) {\n if (ar[i].depth &gt; max.depth)\n max = ar[i];\n }\n\n return max;\n}\n</code></pre>\n\n<p>I use a helper function is this, <code>Object.toType</code>. This is a wonderful function thought up by Angus Croll at <a href=\"http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/\" rel=\"nofollow\" title=\"the Javascript Weblog\">the Javascript Weblog</a>.</p>\n\n<pre><code>Object.toType = function(obj) {\n return ({}).toString.call(obj).match(/\\s([a-z|A-Z]+)/)[1].toLowerCase();\n}\n</code></pre>\n\n<p>The deepestObject function doesn't return multiple children if they have the same depth though, this can be changed by using the following instead:</p>\n\n<pre><code>function deepestObject(ob) {\n var ar = []; //array of objects and their depth\n\n for (var key in ob) {\n if (ob.hasOwnProperty(key)) {\n if (Object.toType(ob[key]) == \"object\") {\n var children = deepestObject(ob[key]); //array of deepest children\n for (var i=0;i&lt;children.length;i++) { //for each child\n var child = children[i];\n //console.log(child)\n child.depth++;\n ar.push(child);\n }\n }\n }\n }\n\n var max = [{depth: 0, children: ob}];\n for (var i=0; i&lt;ar.length;i++) {\n if (ar[i].depth &gt; max[0].depth)\n max = [ar[i]];\n else if (ar[i].depth == max[0].depth)\n max.push(ar[i]);\n }\n\n return max;\n}\n</code></pre>\n\n<p>You can see both working here: <a href=\"http://jsfiddle.net/7jJv3/33/\" rel=\"nofollow\">single child</a> and <a href=\"http://jsfiddle.net/7jJv3/36/\" rel=\"nofollow\">mulitple child</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-26T14:53:03.997", "Id": "4414", "ParentId": "3124", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-06-26T16:59:11.487", "Id": "3124", "Score": "6", "Tags": [ "javascript", "parsing", "json", "reinventing-the-wheel" ], "Title": "Parsing JSON with JavaScript" }
3124
<p>After realizing that I was spending a lot of time getting the latest version of Chromium, I figured I would throw together a quick script. Over time, I wanted to make the script more efficient, cleaner, and pythonic. Here is what I came up with:</p> <pre><code>from zipfile import ZipFile from os import rename, remove, path from shutil import rmtree, copytree from httplib2 import Http from sys import argv, exit from easygui import indexbox h = Http('.cache') saveDir = 'C:\\Program Files\\Chromium\\' def getLatestVersion(): verSite = ('http://build.chromium.org/f/chromium/snapshots/' + 'Win/LATEST') re, ver = h.request(verSite) ver = str(ver, encoding='utf8') return ver def delCurrent(): try: rmtree(path.join(saveDir, 'Current')) except Exception: print('Chromium could not be removed.') def delBackup(): try: rmtree(path.join(saveDir, 'Backup')) except Exception: print('Backup could not be removed.') def downloadChromium(ver): site = ('http://build.chromium.org/buildbot/snapshots/Win/' + ver + '/chrome-win32.zip') re, chrome = h.request(site) file = open(path.join(saveDir, 'latest.zip'), 'wb') file.write(chrome) file.close() def unzip(): zip = ZipFile(saveDir + 'latest.zip', 'r') zip.extractall(saveDir) rename(path.join(saveDir, 'chrome-win32'), path.join(saveDir, 'Current')) zip.close() remove(path.join(saveDir, 'latest.zip')) def revert(): delCurrent() copytree(path.join(saveDir, 'Backup'), path.join(saveDir, 'Current')) def backup(): delBackup() copytree(path.join(saveDir, 'Current'), path.join(saveDir, 'Backup')) def gui(): ver = getLatestVersion() choices = ['Download version %s' % ver, 'Backup', 'Revert', 'Exit'] choice = indexbox('What do you want to do?', 'Chromium Downloader', choices) if choice == 0: delCurrent() downloadChromium(ver) unzip() elif choice == 1: backup() elif choice == 2: revert() elif choice == 3: exit() gui() def usage(): print('-h Display help text\n' + '-g Launches the GUI Program\n' + '-v Only gets the version\n' + '-r Reverts to last backup\n' + '-b Saves a new backup\n' + '-o Specify version to download\n') def main(): if '-g' in argv: gui() exit() elif '-h' in argv: usage() exit(2) elif '-r' in argv: revert() exit() if '-o' in argv: ver = argv.index('-o') + 1 else: ver = getLatestVersion() print('Latest Version: ', ver) if '-v' in argv: exit() delCurrent() downloadChromium(ver) unzip() if '-b' in argv: backup() if __name__ == "__main__": main() </code></pre> <p>Are there any major things that should be changed to make this code better?</p>
[]
[ { "body": "<p>I assume you are aware of Chrome Canary, which I gather is able to use binary deltas? I don't think it's pure Chromium though.</p>\n\n<p>Your code is pretty clean. You could be using argparse for parsing the command line, currently you are ignoring flags that don't match. You could wrap the exit call around main, like this: <code>exit(main())</code>, and use <code>return</code> / <code>return 2</code> statements instead. You could replace <code>\"C:\\\\Program Files\"</code> with <code>%PROGRAMFILES%</code>, or pick up some defaults from the registry, but that's not necessary unless you plan for a larger audience. You could also reduce the window Chromium is unavailable by unzipping somewhere else, then moving the directories, then clearing the previous one (but I don't think you can make it atomic without something like symlinks or hardlinks).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T22:20:15.940", "Id": "3132", "ParentId": "3127", "Score": "2" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li><p>In Python 2, <code>file</code> is a built-in function, so avoid using the name for anything else. More serious is <code>zip</code>, since it's still a built-in function in Python 3.</p></li>\n<li><p>Take advantage of the <a href=\"http://docs.python.org/reference/compound_stmts#with\" rel=\"nofollow\"><code>with</code> statement</a>:</p>\n\n<pre><code># old\nfile = open(path.join(saveDir, 'latest.zip'), 'wb')\nfile.write(chrome)\nfile.close()\n\n# new\nwith open(path.join(saveDir, 'latest.zip'), 'wb') as f:\n f.write(chrome)\n</code></pre>\n\n<p>The same applies to <code>Zipfile</code>.</p>\n\n<p>The advantage, beyond brevity, is that regardless of what happens, the file will always be closed.</p></li>\n<li><p>Use string formatting only when needed:</p>\n\n<pre><code># old\n'Download version ' + ver\n\n# new\n'Download version %s' % ver\n</code></pre>\n\n<p>if you insist on using string formatting, use the newer form:</p>\n\n<pre><code>'Download version {}'.format(ver)\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T21:00:59.913", "Id": "3149", "ParentId": "3127", "Score": "0" } }, { "body": "<pre><code>from zipfile import ZipFile\nfrom os import rename, remove, path\nfrom shutil import rmtree, copytree\nfrom httplib2 import Http\nfrom sys import argv, exit\nfrom easygui import indexbox\n</code></pre>\n\n<p>Its a personal preference thing, but I suggest not using from x import y, unless you use the imported name repeatedly. For example, you only use zipfile once. I'd rather import zipfile and then use zipfile.ZipFile for that one occourance. I think it makes the code a bit cleaner.</p>\n\n<pre><code>h = Http('.cache')\n</code></pre>\n\n<p>h isn't a very descriptive name. I recommend picking something that gives a better idea what is going on.</p>\n\n<pre><code>saveDir = 'C:\\\\Program Files\\\\Chromium\\\\'\n</code></pre>\n\n<p>The python style guide recommends ALL_CAPS for global constants</p>\n\n<pre><code>def getLatestVersion():\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for global function names</p>\n\n<pre><code> verSite = ('http://build.chromium.org/f/chromium/snapshots/' +\n 'Win/LATEST')\n</code></pre>\n\n<p>If the URL is long enough to require breaking across multiple lines, its probably long enough to move into a global constant. Also, why are you concatenation two constant strings?</p>\n\n<pre><code> re, ver = h.request(verSite)\n</code></pre>\n\n<p>I'm left clueless as to what re and ver are. </p>\n\n<pre><code> ver = str(ver, encoding='utf8')\n</code></pre>\n\n<p>Is ver a string? Why not use the decode method?</p>\n\n<pre><code> return ver\n</code></pre>\n\n<p>Don't assign the value into a local variable and then return it. Just return it.</p>\n\n<pre><code>def delCurrent():\n try:\n rmtree(path.join(saveDir, 'Current'))\n except Exception:\n print('Chromium could not be removed.')\n</code></pre>\n\n<p>Firstly, you are catching all exceptions. This is especially bad in python since everything can be an exception. Its better to catch only those exceptions you actually expect. Secondly, you try to continue on after a failure. If you can't remove the current version, you should probably abort and not try to blund on. Thirdly, you don't display any information about what happened. The exception may contain useful information about why it couldn't delete the files. </p>\n\n<pre><code>def delBackup():\n try:\n rmtree(path.join(saveDir, 'Backup'))\n except Exception:\n print('Backup could not be removed.')\n\n\ndef downloadChromium(ver):\n site = ('http://build.chromium.org/buildbot/snapshots/Win/'\n + ver + '/chrome-win32.zip')\n</code></pre>\n\n<p>I string use of string formatting would make this nicer.</p>\n\n<pre><code> re, chrome = h.request(site)\n file = open(path.join(saveDir, 'latest.zip'), 'wb')\n file.write(chrome)\n file.close()\n</code></pre>\n\n<p>Does the api you are using support downloading to a file? If the zip file is very big, downloading it into a string variable may not be a good plan.</p>\n\n<pre><code>def unzip():\n zip = ZipFile(saveDir + 'latest.zip', 'r')\n zip.extractall(saveDir)\n rename(path.join(saveDir, 'chrome-win32'), path.join(saveDir, 'Current'))\n zip.close()\n remove(path.join(saveDir, 'latest.zip'))\n\n\ndef revert():\n delCurrent()\n copytree(path.join(saveDir, 'Backup'), path.join(saveDir, 'Current'))\n\n\ndef backup():\n delBackup()\n copytree(path.join(saveDir, 'Current'), path.join(saveDir, 'Backup'))\n\n\ndef gui():\n ver = getLatestVersion()\n choices = ['Download version %s' % ver, 'Backup', 'Revert', 'Exit']\n choice = indexbox('What do you want to do?',\n 'Chromium Downloader', choices)\n if choice == 0:\n delCurrent()\n downloadChromium(ver)\n unzip()\n</code></pre>\n\n<p>I recommend moving this in a function to match the other options.</p>\n\n<pre><code> elif choice == 1:\n backup()\n elif choice == 2:\n revert()\n elif choice == 3:\n exit()\n</code></pre>\n\n<p>I'd put all these functions in a list and then index them. </p>\n\n<pre><code> gui()\n</code></pre>\n\n<p>Don't use recursion here, use a while True loop.</p>\n\n<pre><code>def usage():\n print('-h Display help text\\n' +\n '-g Launches the GUI Program\\n' +\n '-v Only gets the version\\n' +\n '-r Reverts to last backup\\n' +\n '-b Saves a new backup\\n' +\n '-o Specify version to download\\n')\n\n\ndef main():\n</code></pre>\n\n<p>I'd suggest passing in argv to main. That way another piece of code could drive this code by passing arguments to main.</p>\n\n<pre><code> if '-g' in argv:\n gui()\n exit()\n elif '-h' in argv:\n usage()\n exit(2)\n elif '-r' in argv:\n revert()\n exit()\n\n if '-o' in argv:\n ver = argv.index('-o') + 1\n else:\n ver = getLatestVersion()\n print('Latest Version: ', ver)\n if '-v' in argv:\n exit()\n</code></pre>\n\n<p>Using exit to avoid following anymore logic is considered bad form. Use an else block. </p>\n\n<pre><code> delCurrent()\n downloadChromium(ver)\n unzip()\n\n if '-b' in argv:\n backup()\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T23:51:35.497", "Id": "3154", "ParentId": "3127", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T19:32:27.297", "Id": "3127", "Score": "2", "Tags": [ "python" ], "Title": "Chromium Nightly Build Downloader" }
3127
<p>It's somewhat odd that Java's collection framework has no iterator for recursive data structures. Since I needed something like this, I wrote my own. First off, I need recursive elements:</p> <pre><code>public interface RecursiveElement&lt;T&gt; { public Iterator&lt;T&gt; getChildrenIterator(); } </code></pre> <p>And then an <code>Iterator</code>:</p> <pre><code>public class RecursiveIterator&lt;T&gt; implements Iterator&lt;T&gt; { private Deque&lt;Iterator&lt;T&gt;&gt; stack; private Iterator&lt;T&gt; currentStackItem; /** * Creates a new instance * * @param root * all children of this node are iterated. The root node itself * is not returned * @throws NullPointerException * if root is null */ public RecursiveIterator(final RecursiveElement&lt;T&gt; root) { if (root == null) throw new NullPointerException( "root argument to this iterator must not be null"); stack = new LinkedList&lt;Iterator&lt;T&gt;&gt;(); currentStackItem = root.getChildrenIterator(); } @Override public boolean hasNext() { return currentStackItem != null; } @Override public T next() { final T result = currentStackItem.next(); if (result instanceof RecursiveElement) { stack.addLast(currentStackItem); // Here is the warning: currentStackItem = ((RecursiveElement&lt;T&gt;)result).getChildrenIterator(); } while (currentStackItem != null &amp;&amp; !currentStackItem.hasNext()) currentStackItem = stack.pollLast(); return result; } @Override public void remove() { currentStackItem.remove(); } } </code></pre> <p>That code works very well, but I do get a warning from the compiler in the <code>next()</code> method in the line I marked. It is clear to me why this warning occurs, but I have not come up with any solution on how to solve the problem without this warning (save suppressing the warning). Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:39:56.750", "Id": "82999", "Score": "0", "body": "I don't think you can. Java's generics doesn't allow compound types such as `Iterator<T | RecursiveElement<T>>`." } ]
[ { "body": "<p>I don't think you can do anything about this. You have to cast here, and in the process you lose all information about the type parameter: The compiler can't know that if you have a <code>RecursiveElement</code>, it's always a <code>RecursiveElement&lt;T&gt;</code>, and \"thanks\" to type erasure it can't check the runtime type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:34:36.703", "Id": "82998", "Score": "1", "body": "As @JvR points out, the problem isn't type erasure but the fact that each collection may contain both items and other collections. This necessitates a cast from `T` to `RecursiveElement<T>` which the compiler does not like (rightly so)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T07:17:47.660", "Id": "3140", "ParentId": "3130", "Score": "6" } }, { "body": "<p>The type checker is marking a real issue here. To visualise this, replace your <code>RecursiveElement&lt;T&gt;</code> with a generic <code>Iterable&lt;T&gt;</code>, which provides identical type guarantees.</p>\n\n<p>When different layers mix different types, <code>RecursiveIterator</code> unfortunately breaks down. Here is an example:</p>\n\n<pre><code>public class Main {\n public static void main(String[] args) {\n final RecursiveIterator&lt;IntElem&gt; itr = new RecursiveIterator&lt;IntElem&gt;(new MixedRecursiveElem());\n while ( itr.hasNext() ) {\n IntElem elm = itr.next();\n }\n }\n}\n\nclass IntElem implements RecursiveElement&lt;Integer&gt; {\n public Iterator&lt;Integer&gt; getChildrenIterator() {\n return Arrays.asList(1, 2, 3).iterator();\n }\n}\n\nclass MixedRecursiveElem implements RecursiveElement&lt;IntElem&gt; {\n public Iterator&lt;IntElem&gt; getChildrenIterator() {\n return Arrays.asList(new IntElem(), new IntElem()).iterator();\n }\n}\n\nOutput:\nException in thread \"main\" java.lang.ClassCastException: java.lang.Integer cannot be cast to IntElem\n at Main.main(Main.java:7)\n</code></pre>\n\n<p>Your options are:</p>\n\n<ul>\n<li>try to push the responsibility of recursing to your actual elements;</li>\n<li>try some wizardry to accept a finite amount of recursion by adding type variables;</li>\n<li>drop type safety and wrap in a filtering iterator.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T16:02:32.597", "Id": "47360", "ParentId": "3130", "Score": "3" } } ]
{ "AcceptedAnswerId": "3140", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T20:54:51.990", "Id": "3130", "Score": "11", "Tags": [ "java", "recursion", "casting", "iterator" ], "Title": "How can I avoid unchecked cast warning in my generic recursive Iterator?" }
3130
<p>I often argue with the voices about the correctness of having assignments within an <code>if</code> statement (or equivalent), meaning having this:</p> <pre><code>if($thing = someFunction()){ //do stuff } </code></pre> <p>Instead of this:</p> <pre><code>$thing = someFunction(); if($thing){ //Do stuff } </code></pre> <p>A part of me says its a bad practice because:</p> <ul> <li>If read quickly (by someone who is not that familiar with the practice) it might be hard to notice that its not a <code>==</code>, and look like a mistake.</li> <li>It is not possible in all languages (IIRC, Java explodes with that).</li> </ul> <p>But the voices say its good because:</p> <ul> <li>Less lines, looks cleaner.</li> <li>The practice is not that uncommon (C/C++, PHP).</li> <li>The variable acquires more semantics (it generally won't be used outside the <code>if</code> scope)</li> <li>It is actually easy to get used to reading it and not miss it the after seeing it a couple of times.</li> </ul> <p>So, could the voices be right? Or, is it an aberrant practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T00:43:38.027", "Id": "5221", "Score": "0", "body": "Belongs on Programmers.SE" } ]
[ { "body": "<p>I prefer the second way of doing it (not having it in the <code>if</code>-clause):</p>\n\n<blockquote>\n <p>The practice is not that uncommon (C/C++, PHP).</p>\n</blockquote>\n\n<p>There are a lot of bad practices out there. Just being common does not mean it is good.</p>\n\n<blockquote>\n <p>The variable acquires more semantics (it generally won't be used outside the if scope)</p>\n</blockquote>\n\n<p>Scope really should not be a problem. If it is, either your function is way too long or your variables are not named properly. </p>\n\n<blockquote>\n <p>Less lines, looks cleaner.</p>\n</blockquote>\n\n<p>Remove all comments from your code - it is even less lines then. Does this mean it is better?</p>\n\n<blockquote>\n <p>It is actually easy to get used to reading it and not miss it the after seeing it a couple of times.</p>\n</blockquote>\n\n<p>You already gave an argument against this by yourself:</p>\n\n<blockquote>\n <p>If read quickly (by someone who is not that familiar with the practice) it might be hard to notice that its not a \"==\", and look like a mistake.</p>\n</blockquote>\n\n<p>In my opinion this is the only argument against this practice. But it beats all other arguments by far. For example if someone else reads your code (fast fast-reading over it), he probably will not notice this - even if he is familiar with this. If you code has any chance of being misread, you should avoid it.</p>\n\n<p>But this is my opinion only, there are probably supporters with good arguments for it out there. I guess this is something of personal style/preference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:24:21.367", "Id": "4998", "Score": "0", "body": "This is most definitely not just a simple style issue, see the answer I posted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T12:34:02.953", "Id": "3145", "ParentId": "3135", "Score": "2" } }, { "body": "<p>I agree with what @Fge says.</p>\n\n<p>Another way that I've seen:</p>\n\n<pre><code>if (($thing = some_function()) == true) {\n do_something();\n}\n</code></pre>\n\n<p>I'd still argue for the second way you present (assignment before the if statement). I believe it's more readable, since the assignment is separated from the comparison. There are idiomatic exceptions, like in C:</p>\n\n<pre><code>if ((ptr = malloc(sizeof(int) * size)) == null) {\n run_away_screaming();\n}\n</code></pre>\n\n<p>I've seen this a lot, so much so that it's very easy for me to tell if the allocation is wrong. This is a common operation though, and I wouldn't use this method anywhere else.</p>\n\n<p>(<br />\nThis all assumes that the return value isn't boolean &amp;&amp; the return value is used elsewhere. If not, it should be:</p>\n\n<pre><code>if (some_function()) {\n do_something();\n}\n</code></pre>\n\n<p>Just covering the bases :)<br />\n)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T16:52:33.143", "Id": "4747", "Score": "0", "body": "Yep, that was just the alternative I was looking for. It is kind of easy to say \"Oh, I'll simplify that; who uses x == true anyways?\", so, putting in coding standards =)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T14:07:11.170", "Id": "3146", "ParentId": "3135", "Score": "3" } }, { "body": "<p>Here are some serious concerns why assignment inside conditions is bad:</p>\n\n<ol>\n<li><p>The classic <code>==</code> versus <code>=</code> newbie bug. Instead of adopting an obfuscated coding style to prevent this bug, ie <code>if(NULL == var)</code>, simply avoid assignment inside conditions.</p></li>\n<li><p>Assignment inside conditions makes it harder for a compiler or static analyser to find actual bugs in your code.</p></li>\n<li><p>Order of evaluation issues. For most operators in C/C++, the order of evaluation is implementation-defined behavior. This means that you cannot know whether the left side or the right side of the <code>=</code> is evaluated first, which may or may not lead to fatal bugs. A typical example of a possibly fatal bug is <code>x=y=0;</code>, which the compiler is free to interpret as \"put uninitialized garbage in <code>x</code>, then put <code>0</code> in <code>y</code>\". Bugs like this are more likely to occur inside conditions.</p></li>\n<li><p>Undefined behavior issues. This is related to the order of evaluation issue above, but even more severe. It occurs when you write code like <code>while(arr[i] &lt; i++)</code>. This is undefined behavior and your program is free to crash &amp; burn if your code contains it.\n<a href=\"https://stackoverflow.com/search?q=i%2B%2B+undefined+behavior\">https://stackoverflow.com/search?q=i%2B%2B+undefined+behavior</a></p></li>\n</ol>\n\n<p>Reason 1 and 2 above are taken from the widely-recogniced industry standard MISRA-C:2004, which bans assignment inside conditions in rule 13.1. Assignment inside conditions is also banned by CERT C, EXP18-C.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T15:00:12.973", "Id": "5007", "Score": "0", "body": "About 1) In my opinion the NULL == var statement has another purpose then I think you mean: I use it to force compiler errors when i accidentally forgot the second = (this happens more often then you might think) - not to make clear this should be an assignment. NULL = var gives you an error at write-time (*by your IDE) while var = NULL will even compile. Thus this is not a obfuscated coding style in my opinion ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T17:45:26.337", "Id": "5011", "Score": "0", "body": "@Fge That was true in the 80s when that style was popular for that reason. Since around 1991 almost every known compiler warns for assignment inside conditions. And in modern programming, static analysers are used, making that style even more obsolete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T19:12:47.540", "Id": "5013", "Score": "0", "body": "Not every language has highly optimized compilers, analyzers or IDEs (e.g. many script-languages, but then again, the null = var assignment does even work sometimes). However, I guess that's pretty much a personal taste :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:22:19.733", "Id": "3346", "ParentId": "3135", "Score": "2" } }, { "body": "<p>The answer really depends on who will be viewing the code. While both methods are correct and acceptable, if you are working with inexperienced/beginner level programmers then it will make everyone's life easier to use:</p>\n\n<pre><code>$thing = someFunction();\nif($thing){\n //Do stuff\n}\n</code></pre>\n\n<p>However, if your code will be looked at by medium to experienced programmers then they should have no problem in deciphering: </p>\n\n<pre><code>if($thing = someFunction()){\n //do stuff\n}\n</code></pre>\n\n<p>At the end of the day, what is more critical is the run time of your code. Both techniques give O(1) run times thus either can be used depending on which level programmer will be viewing the code etc. </p>\n\n<p><strong>EDIT</strong>: As Lundin points out, it is more appropriate to use the first method. It seems that there are more pros for the first method, thus that should be used. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T17:46:53.303", "Id": "3427", "ParentId": "3135", "Score": "0" } } ]
{ "AcceptedAnswerId": "3146", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-26T23:03:40.017", "Id": "3135", "Score": "5", "Tags": [ "php", "c++", "c" ], "Title": "Truthy assignments" }
3135
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html">SICP</a>:</p> <blockquote> <p>Exercise 3.64. Write a procedure stream-limit that takes as arguments a stream and a number (the tolerance). It should examine the stream until it finds two successive elements that differ in absolute value by less than the tolerance, and return the second of the two elements. Using this, we could compute square roots up to a given tolerance by</p> </blockquote> <pre><code>(define (sqrt x tolerance) (stream-limit (sqrt-stream x) tolerance)) </code></pre> <p>I wrote this answer:</p> <pre><code>(define (stream-limit s tol) (if (stream-null? s) (error "End of stream found before limit reached:" tol) (let* ((a (stream-car s)) (b (stream-car (stream-cdr s))) (diff (abs (- a b)))) (if (&gt; tol diff) b (stream-limit (stream-cdr s) tol))))) </code></pre> <p>Can it be improved?</p>
[]
[ { "body": "<p>Looks good. Is it OK to just say it looks good? If it's not, here are two comments:</p>\n\n<ul>\n<li>Why do you use <code>let*</code> here? Isn't <code>let</code> enough?</li>\n<li>You could define <code>stream-cadr</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T23:44:54.263", "Id": "30916", "Score": "3", "body": "The initializer for `diff` uses the values of `a` and `b`. Since `let` doesn't create the variable bindings until *after* evaluating all of the initializer expressions, it won't work here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-07T21:03:31.930", "Id": "9794", "ParentId": "3137", "Score": "0" } }, { "body": "<p>Looks fine to me. I would only suggest changing <code>(&gt; tol diff)</code> to <code>(&lt; diff tol)</code> because it reads more like the problem specification and is easier to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T17:33:34.767", "Id": "31439", "ParentId": "3137", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T01:58:06.500", "Id": "3137", "Score": "7", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Write a procedure stream-limit that finds" }
3137
<p>I have a simple implementation for a LRU cache using <code>LinkedHashMap</code>. </p> <ul> <li>I want it to be as generic as possible. </li> <li>This is not for production use, just practice, so I don't care if its thoroughly robust as far as it is correct. However, I will welcome any comments, especially the ones which might make this better with simple changes :) </li> <li>Are there any other ways of doing this?</li> </ul> <pre><code>class LRUCache&lt;E&gt; { @SuppressWarnings("unchecked") LRUCache(int size) { fCacheSize = size; // If the cache is to be used by multiple threads, // the hashMap must be wrapped with code to synchronize fCacheMap = Collections.synchronizedMap ( //true = use access order instead of insertion order new LinkedHashMap&lt;Object,E&gt;(fCacheSize, .75F, true) { @Override public boolean removeEldestEntry(Map.Entry eldest) { //when to remove the eldest entry return size() &gt; 99 ; //size exceeded the max allowed } } ); } public void put(Object key, E elem) { fCacheMap.put(key, elem); } public E get(Object key) { return fCacheMap.get(key); } private Map&lt;Object,E&gt; fCacheMap; private int fCacheSize; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T17:25:44.067", "Id": "4748", "Score": "2", "body": "Instead of using a synchronized wrapper for the internal map you could synchronize all methods of LRU cache itself, as shown here: http://www.source-code.biz/snippets/java/6.htm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T18:30:45.760", "Id": "8641", "Score": "0", "body": "There is a similar question in StackOverflow: http://stackoverflow.com/questions/221525/how-would-you-implement-an-lru-cache-in-java-6" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T17:19:05.493", "Id": "52142", "Score": "0", "body": "My only concern would be violation of dependency injection concept." } ]
[ { "body": "<p>First, use generics properly.</p>\n\n<p>Second, why do you track the cache size if when you need it, you get a hardcoded 99? I will assume that was some sort of mistake.</p>\n\n<p>Third, if you really want to annoy most truely professional java developers and course instructors (i.e, not these that write Java code as if they were programming in C#, C++ or Pascal), prefix your class and variable names. If you don't want to do so, do not make this.</p>\n\n<p>Fourth, I would personally prefer to handle synchronization myself. This way, if the class is expanded to include some method that makes two or more operations in the map, I will not break it. I added the <code>atomicGetAndSet</code> method to show this. If I relied in the synchronization provided by the <code>Collections.synchronizedMap</code> instead of my own, the <code>atomicGetAndSet</code> method would not be atomic and it would break if <code>LRUCache</code> instances are used concurrently.</p>\n\n<p>With this in mind, your code became this:</p>\n\n<pre><code>public class LRUCache&lt;K, V&gt; {\n\n private final Map&lt;K, V&gt; cacheMap;\n\n public LRUCache(final int cacheSize) {\n\n // true = use access order instead of insertion order.\n this.cacheMap = new LinkedHashMap&lt;K, V&gt;(cacheSize, 0.75f, true) { \n @Override\n protected boolean removeEldestEntry(Map.Entry&lt;K, V&gt; eldest) {\n // When to remove the eldest entry.\n return size() &gt; cacheSize; // Size exceeded the max allowed.\n }\n };\n }\n\n public synchronized void put(K key, V elem) {\n cacheMap.put(key, elem);\n }\n\n public synchronized V get(K key) {\n return cacheMap.get(key);\n }\n\n public synchronized V atomicGetAndSet(K key, V elem) {\n V result = get(key);\n put(key, elem);\n return result;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:55:10.377", "Id": "36844", "Score": "0", "body": "one improvement of above code from Victor is using lock instead of synchronized methods. Using lock will improve concurrency, e.g., get operations won't block each other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-24T05:48:20.230", "Id": "53116", "Score": "0", "body": "@Eric While non-blocking method calls are preferable, it does require that the caller handles situations where the lock isn't obtained. Furthermore, calls to the methods Victor describes are very short-lived (get, or put something on a LinkedHashMap), so I doubt it will ever be a problem with synchronized.\n\nDo you see any other advantages of using locks?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:29:00.573", "Id": "60473", "Score": "0", "body": "But this is not a true LRUCache. LRU = Least recently used. I don't see that the get method updates something in the cache. It should, because the get method to the last inserted object should be the youngest object in the cache." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T15:54:42.550", "Id": "107299", "Score": "0", "body": "@x-man the `get` method calls `cacheMap.get(key)` which in its implementation (inside LinkedHashMap) takes care of the LRU functionality." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T04:12:56.280", "Id": "7402", "ParentId": "3138", "Score": "10" } }, { "body": "<p>Note from LinkedHashMap's javadoc:</p>\n\n<blockquote>\n <p>Note that insertion order is not affected if a key is re-inserted into the map</p>\n</blockquote>\n\n<p>So this will not be an LRU map unless you make sure that all keys are unique.</p>\n\n<p>Further in the documentation, however:</p>\n\n<blockquote>\n <p>A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-26T08:31:39.037", "Id": "61055", "ParentId": "3138", "Score": "3" } }, { "body": "<p>From having implemented an LRU cache in production code using <code>LinkedHashMap</code>, I would say: why not go ahead and implement the full Map interface? At some point you may realize that you need a size() method and an entrySet() method, and maybe some other Map-like methods, so it might be good to go ahead and make <code>LRUCache</code> a facade to the contained <code>fCacheMap</code> by passing through all the other common Map methods. This opens up a whole world of utility classes that can be used to inspect or manipulate Maps, if desired.</p>\n\n<p>Like so:</p>\n\n<pre><code>public class LRUCache&lt;E&gt; implements Map&lt;Object, E&gt; {\n // ...\n\n public int size()\n {\n return fCacheMap.size(key);\n }\n\n // etc...\n}\n</code></pre>\n\n<p>Of course, you may decide that a subset of the <code>Map</code> interface is sufficient and perhaps use something like <code>Collection</code> instead. It really all depends on how you envision your <code>LRUCache</code> being used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-20T14:23:53.723", "Id": "78126", "ParentId": "3138", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T02:50:54.250", "Id": "3138", "Score": "11", "Tags": [ "java", "cache", "collections" ], "Title": "LinkedHashMap as LRU cache" }
3138
<p>I have developed a test app that works by getting webpages source and processing it. I have up to 100k URLs in queue and want to use a maximum of 25 threads. Please help me check if the code is good or point out any faults you might find.</p> <pre><code>Public Class frmMain Public Delegate Sub AddItemDelegate(ByVal Item As String, ByVal Status As String) Private TotalItems As Integer =0 Public Sub AddItem(ByVal item As String, ByVal status As String) If Me.InvokeRequired Then Me.Invoke(New AddItemDelegate(AddressOf AddItem), Item, Status) Else Dim objLock As Object = New Object() Dim lvItem As New ListViewItem With lvItem .Text = Item If Status.Length &lt; 200 Then .SubItems.Add(Status) Else .SubItems.Add(Status.Length.ToString) End If End With If listView1.Items.Count &lt;TotalItems-1 Then listView1.Items.Add(lvItem) Else tsslstatus.Text ="Done" btnStart.Enabled =true End If End If End Sub Public Sub DoWork(ByVal objItem As Object) static _sem as Semaphore = new Semaphore(5,10) Dim objUrl as String = DirectCast(objItem, string) Try If objUrl Is Nothing Then exit sub End If Dim URL as New Uri(objUrl) _sem.waitone() AddItem(URL.AbsoluteUri,gethtml(URL)) _sem.Release() Catch ex As Exception debug.Print("Error " &amp; ex.StackTrace ) End Try End Sub Private Sub btnStart_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStart.Click btnStart.Enabled =False dim blnResult as Boolean = ThreadPool.SetMaxThreads(25, 25) System.Threading.Thread.Sleep(1000) listView1.Items.Clear For Each sItem As String In txturls.Lines if sItem.Trim &lt;&gt;string.empty ' Queue a task If sItem.Contains("http://")=False Then sItem="http://" &amp; sItem End If ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DoWork), sItem) TotalItems+=1 tsslTotal.Text =String.Format ("Total Tasks: {0}",TotalItems) end if Next End Sub End Class </code></pre>
[]
[ { "body": "<ul>\n<li><p>Relying on the max number of thread pool threads to cap the number of concurrent downloads feels ... wrong. It may also cause problems if another component needs a thread pool while all 25 are waiting for a response from web servers.</p>\n\n<p>(slight correction) Although you use semaphores to limit the number of concurrent downloads to ten, you will still have up to 25 thread pool threads in the <code>DoWork()</code> method (15 blocked on the semaphore).</p>\n\n<p>Two alternatives:</p>\n\n<ul>\n<li>Manage you own task list and threads (since 4k URLs per thread could take more than a few seconds).</li>\n<li>Make your requests <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest.begingetresponse.aspx\" rel=\"nofollow\">asynchronously</a> and track the list of IAsyncResult objects (though this may get a little fiddly).</li>\n</ul></li>\n<li><p><strike>I'm not sure I like the idea of using a static Semaphore to protect instance data, you should store the semaphore in a local field. Even if you only ever have a single instance, I prefer to scope the lock similarly to the data to be protected.</strike> (sorry, I thought the semaphore was to protect the controls rather than used as a throttle)</p></li>\n<li><p>You should release your semaphore in a finally block.</p></li>\n<li><p><strike>Only the thread that created a control should be used to update it. I recommend using <code>ISynchronizeInvoke.Invoke()</code> to call <code>AddItem()</code> (implemented implicitly on Control). This will also remove the need to use a semaphore to protect the control (though you may still need one to protect a pending URL list depending on what you do about the first point).</strike> (this is already done, sorry, missed it).</p></li>\n<li><p>What is the purpose of the 1000 millisecond sleep? it appears before the tasks are even queued.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T12:30:13.290", "Id": "4743", "Score": "0", "body": "thanks for the tips. the semaphore is used to allow only `10` max concurrent downloads. when i click start, the button doesn't get disabled immediately, so the `1000ms` sleep, although it makes no difference, i'll remove it. if each threads perform the `GetHtml`, is there need for `asynchronously`? concerning threads management, am using .net 2.0. which way would i do this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T13:35:08.767", "Id": "4745", "Score": "0", "body": "@Smith: Sorry, I miss-read some of your code and have now updated my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T13:35:19.907", "Id": "4746", "Score": "0", "body": "If you use the asynchronous methods, you shouldn't create tasks for the thread queue. The asynchronous method call already does this for you. Ultimately, the goal of the two suggestions is to throttle the web requests before the thread pool thread is needlessly consumed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T11:09:37.363", "Id": "3143", "ParentId": "3141", "Score": "2" } } ]
{ "AcceptedAnswerId": "3143", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T08:57:30.710", "Id": "3141", "Score": "5", "Tags": [ ".net", "multithreading", "vb.net" ], "Title": "Processing a webpage source" }
3141
<pre><code>var AgeConvertor = { Age: function (formattedDate) { var now = new Date(); var yearNow = now.getFullYear(); var monthNow = now.getMonth() + 1; var dayNow = now.getDate(); // Calculating in days var ONE_DAY = 1000 * 60 * 60 * 24; var ONE_MONTH = 1000 * 60 * 60 * 24 * 30; var date1_ms = new Date().getTime() var date2_ms = formattedDate.getTime() var difference_ms = Math.abs(date1_ms - date2_ms) var yearAge = Math.round(difference_ms/ONE_DAY); if(yearAge &lt; 30) { return yearAge = Math.round(difference_ms/ONE_DAY) + 'D'; // This condition checks if the number of days is more than 30 } else if(yearAge &gt; 30 &amp;&amp; yearAge &lt; 365){ return yearAge = Math.round(difference_ms/ONE_MONTH) + 'M'; } else { // Calculating in years var today = new Date(yearNow,monthNow,dayNow); if (yearNow &lt; 100) { yearNow=yearNow+1900; } yearAge = yearNow - formattedDate.getFullYear(); if (monthNow &lt;= formattedDate.getMonth()) { if (monthNow &lt; formattedDate.getMonth()) { yearAge--; } else { if (dayNow &lt; formattedDate.getDay()) { yearAge--; } } } return yearAge + 'Y'; } } } </code></pre> <ol> <li>How well can this code be improved?</li> <li>Is there any fault in this code?</li> <li>Does this code give desired results?</li> </ol> <p>This code returns your age in days, months and years.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T10:18:24.820", "Id": "4742", "Score": "1", "body": "Why is it an object? it only has one method and you never use `this`" } ]
[ { "body": "<ul>\n<li>You should check if <code>formattedDate</code> is actually a <code>Date</code> object before using it (and change the variable name, since it sounds like it contains a formatted string).</li>\n<li>It's strange, if not wrong, to consider months to be exactly <code>30</code> days. </li>\n<li>You unnecessarily calculate <code>Math.round(difference_ms/ONE_DAY)</code> twice.</li>\n<li><code>yearAge</code> is a bad name for the variable at the beginning, since it doesn't contain anything concerning the year. And you reuse the variable later (then the name fits).</li>\n<li><code>var today = new Date(yearNow,monthNow,dayNow);</code> is wrong (and unnecessary), considering you just got <code>monthNow</code> from the current date and added <code>1</code>. Fortunately you don't actually use it.</li>\n<li>Testing for the full year to be below <code>100</code> is unnecessary. Only <code>getYear</code> returns such values.</li>\n<li>It probably would be better just to compare the day, month and year of the birthday and the current day, and do those calculation of the age in days and months only if needed.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T11:12:13.753", "Id": "3144", "ParentId": "3142", "Score": "4" } } ]
{ "AcceptedAnswerId": "3144", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T09:06:45.913", "Id": "3142", "Score": "5", "Tags": [ "javascript" ], "Title": "Age in days, months and years" }
3142
<p>I have a bunch of simple interfaces like this one (pretty enough formed, but not guarantee)</p> <pre><code>package com.example.sources; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.resources.client.ImageResource.ImageOptions; import com.google.gwt.resources.client.ImageResource.RepeatStyle; import com.example.sources.MainSceneResource; import com.example.sources.Preloadable; public interface MainSceneResources extends ClientBundle, Preloadable { @Source("com/example/sources/css/mainscene.css") public MainSceneResource mainSceneCss(); @Source("com/example/sources/img/panorama.jpg") @ImageOptions(repeatStyle = RepeatStyle.None) public ImageResource mainSceneBackground(); } </code></pre> <p><strong>I need to</strong>: </p> <ol> <li>remove line with <code>package</code>;</li> <li>change lines with <code>import</code> (delete the <code>import</code> keyword, whitespaces, semicolon at the end) and add stripped packages with the <code>Factory</code>'s method <code>addImport(line)</code>;</li> <li>change <code>Preloadable</code> to <code>Generated</code></li> <li>copy other lines without changes with the <code>SourceWriter</code>'s method <code>sw.println(line)</code></li> </ol> <p>Currently my code is like:</p> <pre><code>BufferedReader reader = new BufferedReader(new InputStreamReader(ris)); String line = null; try { while ((line = reader.readLine()) != null) { if (line.contains("package") || line.isEmpty()) { continue; } int index = line.indexOf("import"); if (index != -1) { line = line.substring(index + 6, line.lastIndexOf(";")).trim(); factory.addImport(line); continue; } if (line.contains("Preloadable")) { line = line.replace("Preloadable", "Generated"); } sw.println(line); } } catch (IOException e) { throw new UnableToCompleteException(); } </code></pre> <p>The one more notice is that I can't use <code>SourceWriter</code> method <code>sw.println(line)</code> before <code>Factrory</code> <code>factory.addImport(line)</code>;</p> <p>My most worries are about calling <code>line.contains("pattern")</code> in <code>while</code>-loop. As I know <code>"pattern"</code> will be compiled to Java regex <code>Pattern.class</code>. I'm aware it's not good to compile the same <code>Pattern</code> over and over till the loop ends, but don't know how to do this better. Also I doubt about this line (to strip <code>import</code> lines)</p> <pre><code>line = line.substring(index + 6, line.lastIndexOf(";")).trim(); </code></pre> <p>Is there a better way to do this?</p>
[]
[ { "body": "<p>Generally what you do is dangerous. More dangerous as you might expect. As soon as you have something odd like a line break in a package or import line, a double semicolon or multiple import statements in a line, the code will break. If your keywords (\"package\", \"import\", \"Generated\") are used somewhere inside the interface, it will break as well (note that these words could appear e.g. in comments).</p>\n\n<p>If you don't want to use a \"real\" Java parser, there are some things you can do to improve your code: If you don't find a closing semicolon for package or import, add the next line as long as you don't have one - or throw at least a meaningful error. You can also check if you have two semicolons in a package or import line. But I think the most important point is to break your loop in 4 parts in order to make your changes as \"local\" as possible. The first loop deals with the package, the second with the imports, the third with Generated and the fourth just adds the rest without changing. So your are safe that after a step is done, it can't do any harm to the following code. Another thing you could try is to preprocess the code with some formatter / pretty printer, which could get rid of some quirks. </p>\n\n<p>Before the code gets at least a little bit more secure, I wouldn't care about performance too much. Consider adding some JUnit tests (ask your colleagues for some \"mean\" input classes - you will be surprised which weird monsters they can imagine - and use the more realistic examples).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T05:24:04.960", "Id": "4753", "Score": "0", "body": "Code of interfaces is always checked by the GWT compiler before the manipulations. It's guaranteed to be a valid java source. I've also thought about multiple statements in a line and keywords. In the future when I can't control all input sources I'm going to make code more secure like a \"real\" java parser." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T22:23:42.120", "Id": "3152", "ParentId": "3147", "Score": "4" } } ]
{ "AcceptedAnswerId": "3152", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T18:47:48.863", "Id": "3147", "Score": "8", "Tags": [ "java", "parsing" ], "Title": "Parse Java source code" }
3147
<p>I have an experimental script that makes an animation of a <code>ul</code> list element background-position, when the list element is hovered. Is there another way to manage this task or just optimize this code? </p> <p>I want to make a menu that has elements with an animated background and have an idea about rotoscope style design or something in that direction. I'm thinking in cross-browser compatibility way too. In this stage this code runs fine in Opera, Internet Explorer 6, Chrome, Firefox 2.0, and Firefox 4.0.</p> <p><a href="http://jsfiddle.net/jurisKaste/nDgSE/" rel="nofollow">jsFiddle</a></p> <pre><code>$(document).ready(function(){ $("li.animate").hover( function () { var param = '0 0'; ids = setInterval(function() { if ( c &gt;= 5 ) { c = 1; $('.animate').css('backgroundPosition', '0 0'); } else { param = (-100 * c++ )+'px 0'; //alert(param); $('.animate').css('backgroundPosition', param); if ( c &gt; 4 ) $('.animate').css('backgroundPosition', '0 0'); } }, 40); }, function () { $('.animate').css('backgroundPosition', '0 0'); clearInterval(ids); } ); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T23:47:26.463", "Id": "4750", "Score": "2", "body": "since you already use a gif, you could use a animated gif on the hover. it would save you all this code and have the same visual effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T07:49:49.657", "Id": "4754", "Score": "0", "body": "yes, people already told me about this (gif animation), but I want to make navigation bar that uses css sprites... maybe it sounds awkward - but i need to control this animation fbf, it's just my idea :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T11:22:13.807", "Id": "4755", "Score": "0", "body": "i think its the total overkill to do this with JS... But i am willing to give you a feedback on your code" } ]
[ { "body": "<p>First of all i mention again, that i would use a GIF animation to solve this and not a JS. Its a very suboptimal solution to a simple problem.</p>\n\n<p>Your code in the code block is missing two var declarations you have in you jsFiddle example.</p>\n\n<p>Here are the things i would change:</p>\n\n<p>In the most cases, when you have to type the same value twice you do something wrong. Use variables to store your stuff. Makes code more maintainable, easy to read, faster in some cases etc... And give your variables names that speak for them selves. Since you don't write any comments, its even more important.</p>\n\n<p>Cache your jQuery objects in variables. By selecting them again and again, your code gets slow and is hard to mainain. Here an example:</p>\n\n<pre><code>$animate = $(\"li.animate\");\n$animate.hover(/* blabalbal */);\n</code></pre>\n\n<p>Put all your code in a function and pass variable stuff (things that could change) as parameters. Always ask your self what could change if you want to reuse the same code for a different CSS / HTML configuration. (Like different size of the element)</p>\n\n<pre><code>var yourFunction = function( $elem ){\n $elem.each(function(){\n //do something\n });\n};\n\n$(function(){ //document ready\n yourFunction( $(\"whatever element you want to handle\") );\n});\n</code></pre>\n\n<p>Then you can call your function in the document ready and you don't have to write all your stuff into your document ready function.</p>\n\n<p>In general split your code in as small generic functions as possible. (Morden browser compile functions that are used often, can make a huge performance differences)</p>\n\n<p>Inside your hover functions you reselect $('.animate'). What are you doing if you have more then one element that has this class? You can refer to the element you are hovering with <code>this</code> inside your hover function:</p>\n\n<pre><code> $(something).hover(function(){ $(this) //give you back a jQuery selection of the hovered element \n },function(){});\n</code></pre>\n\n<p>The biggest problem i see in your code is that you have declared your variables very globally, what are you doing if you need to apply this code twice on the same page?</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T12:48:09.073", "Id": "3167", "ParentId": "3148", "Score": "2" } }, { "body": "<ul>\n<li><p>You left out the declarations of the variables <code>ids</code> and <code>c</code> in the posted code. Also you shouldn't unnecessarily let them be global variables. You can move <code>ids</code> into the document ready function and <code>c</code> into the first hover function.</p></li>\n<li><p>You are very inconsistent:</p>\n\n<ul>\n<li><p>You first declare <code>c</code> to be <code>0</code>, but in the animation you reset it to <code>1</code> instead. Choose one.</p></li>\n<li><p>When <code>c</code> reaches <code>5</code> you first set the background position to <code>-500px 0</code> and then in the next line (<code>if ( c &gt; 4 ) ...</code>) immediately back to <code>0 0</code>, which happens in the next call of the interval function again. As I see it, the line <code>if ( c &gt; 4 ) ...</code> is completely unnecessary.</p></li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T18:09:07.327", "Id": "4783", "Score": "0", "body": "about inconsistent 'c' variable... i did it cause im using postfix increment... but yes i read the code another time and Your arguments are true! sometimes i just write code and if it works i leave it as is... only this time i thought about optimization and logic question and posted here, thx for replay" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T12:48:18.137", "Id": "3168", "ParentId": "3148", "Score": "2" } } ]
{ "AcceptedAnswerId": "3167", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T19:18:43.230", "Id": "3148", "Score": "3", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Making a ul list element animation on hover" }
3148
<pre><code>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun read-sim-file (filename) "Reads file. File is presumed to be the output from a simulation. Returns lines from the simulation as a list of strings We throw an error if TRAP ET is detected. Lines with DBG_INT are ignored." (let ((file-text-list (split "\\n" (batteries:read-text-file filename))) (return_list '())) (loop for line in file-text-list do (cond ((scan "DBG_INT" line) ) ; intentional newline. ((scan "TRAP ET" line) (error "Trap ET detected")) (t ;; There's got to be a cleaner method here. (setf return_list (append return_list (list line)))))) return_list)) </code></pre> <p>This code is ugly. In particular, the (setf X (append X Y)) idiom feels hideously clunky.</p> <p>Comments on how to make this more beautiful?</p> <p>Possibly REMOVE-IF?</p>
[]
[ { "body": "<p>At first glance, you're looking for <code>loop</code>s <code>collect</code> clause.</p>\n\n<pre><code>(defun read-sim-file (filename)\n (let ((file-text-list (split \"\\\\n\" (batteries:read-text-file filename))))\n (loop for line in file-text-list \n when (scan \"TRAP ET\" line)\n do (error \"Trap ET detected o_o\")\n unless (scan \"DBG_INT\" line)\n collect line)))\n</code></pre>\n\n<p>At second glance, you can do this much more efficiently using <code>with-open-file</code> instead of breaking your input file up into a list (this should save you two traversals of said file)</p>\n\n<pre><code>(defun read-sim-file (filename)\n (with-open-file (stream filename)\n (loop for line = (read-line stream nil 'eof) until (eq line 'eof)\n when (scan \"TRAP ET\" line)\n do (error \"Trap ET detected ಠ_ಠ\")\n unless (scan \"DBG_INT\" line)\n collect line)))\n</code></pre>\n\n<p>The first one is a fairly basic <a href=\"http://www.gigamonkeys.com/book/loop-for-black-belts.html\" rel=\"nofollow\">loop directive</a>, the second one is almost verbatum an example out of <a href=\"http://cl-cookbook.sourceforge.net/files.html\" rel=\"nofollow\">the CL Cookbook \"files\" section</a> (the whole cookbook contains many other useful recipes too).</p>\n\n<p>Just as a sidenote, do try to <a href=\"http://dept-info.labri.fr/~idurand/enseignement/lst-info/PFS/Common/Strandh-Tutorial/indentation.html\" rel=\"nofollow\">indent things properly</a>. It was more difficult than it should have been to read your initial program. If you ever catch yourself leaving comments like <code>;; intentional newline</code>, think hard about what you just wrote.</p>\n\n<hr>\n\n<p>Now that I've had some proper sleep, lets take the new one apart for educational purposes.</p>\n\n<pre><code> (with-open-file (stream filename)\n</code></pre>\n\n<p>This line opens up a file and creates a handle for it named <code>stream</code>. Nothing has actually been read yet, you've just got a stream to pull from.</p>\n\n<pre><code> (loop for line = (read-line stream nil 'eof) until (eq line 'eof)\n</code></pre>\n\n<p><code>loop</code> has a couple of non-obvious directives. This is one of them (and coincidentally, the reason that some lispers prefer the non-standard <a href=\"http://common-lisp.net/project/iterate/\" rel=\"nofollow\"><code>iterate</code></a> module; there's a feeling that infix notation isn't Lispy enough. I disagree, just like to point it out). </p>\n\n<p><code>read-line</code> takes a stream and a few options and returns the first line from that stream. <code>(read-line stream nil 'eof)</code> means \"Read the next line from <code>stream</code>, don't error at the end of file marker (that's the <code>nil</code>) and return the symbol <code>eof</code> when you reach the end of the file.</p>\n\n<p>The full line then reads \"Loop through the lines in <code>stream</code> until you hit <code>'eof</code>\".</p>\n\n<pre><code> when (scan \"TRAP ET\" line)\n do (error \"Trap ET detected ಠ_ಠ\")\n</code></pre>\n\n<p><code>loop</code> has conditional directives too, so you don't need to resort to <code>cond</code> here. <code>if</code>, <code>else</code>, <code>when</code> and <code>unless</code> are all valid forms.</p>\n\n<pre><code> unless (scan \"DBG_INT\" line)\n</code></pre>\n\n<p>Speaking of <code>unless</code>, you can use it to skip \"DBG_INT\" lines without devoting a separate clause to them.</p>\n\n<pre><code> collect line))\n</code></pre>\n\n<p>This does the same thing as</p>\n\n<pre><code> (setf tmp (append return_list (list line)))\n</code></pre>\n\n<p>which is to say, it creates a list where the elements are collected in order they're encountered (though there isn't an actual named variable that). The <code>loop</code> form also returns whatever you've collected if that's the last clause in the statement (so you don't need to explicitly return it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-31T18:21:39.067", "Id": "463480", "Score": "0", "body": "Very informative, thanks for the detailed advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-03T04:40:32.060", "Id": "4559", "ParentId": "3151", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-27T22:19:23.417", "Id": "3151", "Score": "3", "Tags": [ "common-lisp" ], "Title": "Critique & improve a file reading routine" }
3151