body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have an algorithm and the idea is to move over an array choosing as index the index of the neighboring cell that has the max value.<br> I.e. </p> <p>if array[i + 1][j + 1] has the largest value among the 3 then move there.</p> <p><img src="https://i.stack.imgur.com/Zhhmg.png" alt="enter image description here"> </p> <p>I have 2 versions of this, but I think it can be cleaner. </p> <p>version 1: </p> <pre><code>int maxI = i + 1; int maxJ = j + 1; if(array[i + 1][j] &gt; array[maxI][maxJ]){ maxI = i + 1; maxJ = j; } if(array[i][j + 1] &gt; array[maxI][maxJ]){ maxI = i; maxJ = j + 1; } i = maxI; j = maxJ; </code></pre> <p>version 2: </p> <pre><code>if(LCS[i + 1][j + 1] &gt; LCS[i][j + 1] &amp;&amp; LCS[i + 1][j + 1] &gt; LCS[i + 1][j]){ i++; j++; } else{ if(LCS[i][j + 1] &gt; LCS[i + 1][j]){ j++; } else{i++;} } </code></pre> <p>Both versions occur in a <code>while</code> loop which I omitted for clarity.<br> How can these versions become better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T21:14:58.233", "Id": "33562", "Score": "1", "body": "In *Version 1* you can remove the line ` maxI = i + 1; ` in the first `if`-block, because it does not do anything." } ]
[ { "body": "<p>I think it's easier to follow the second version. I've extracted out some helper variables:</p>\n\n<pre><code> final int b = array[i][j + 1];\n final int c = array[i + 1][j];\n final int d = array[i + 1][j + 1];\n\n if (d &gt; b &amp;&amp; d &gt; c) {\n i = i + 1;\n j = j + 1;\n } else if (b &gt; c) {\n j = j + 1;\n } else {\n i = i + 1;\n }\n</code></pre>\n\n<p>It seems a little bit readable for me but to be honest I'm not completely satisfied with the result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T06:48:08.190", "Id": "20973", "ParentId": "20929", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T11:35:08.997", "Id": "20929", "Score": "3", "Tags": [ "java", "algorithm", "array" ], "Title": "Code to find the proper index comparing 3 values for max one" }
20929
<p>I am building a web app with a single (not pooled) full time (jdbc) connection between static classes and the database. This is expected to be a low traffic site and the static methods are synchronized. In an effort to speed up access to product information, I am trying PreparedStatements for the first time. As I test, on localhost, sure that I'm the only one running the app., it seems clear to me that my the prepared statements are slower than the unprepared statements I use earlier in the process. This may not be a fair comparison. The unprepared statements get a single result set from one table and it's done. As you can see from the code below, what I'm doing with prepared statements involves three tables and multiple queries. But since this is my first time, I would appreciate review and comment. This does actually work; i.e. all data is retrieved as expected.</p> <p>The first method below (initialize()) is called once from a servlet init() method when the application is first started. The second method (getItemBatch()) retrieves information about as many product items as match a product name (Titel). My little development / test database has less than 100 (total) items and only 1-3 items matching each name; most often only 1. The server app and database are on the same machine and I'm accessing from a browser via localhost. I'm surprised by the consistent perceptible wait for this detailed product data compared to fetching a master product list (all items) mentioned above.</p> <pre><code> public static boolean initialize (Connection connArg, String dbNameArg, String dbmsArg) { con = connArg; dbName = dbNameArg; dbms = dbmsArg; sqlserver_con = connArg; ItemBatchStatement = "select Cartnr, Hgrupp, Prisgrupp, Moms from dbo.Centralartregister " + "where Titel = ?"; ForArtNrStatement = "select Artnr, Antal from dbo.Artikelregister " + "where Cartnr = ? and Antal &gt; 0"; ItemHgruppStatement = "select Namn from dbo.Huvudgrupper " + "where Hgrupp = ?"; try { con.setAutoCommit(false); getItemBatch = con.prepareStatement(ItemBatchStatement); getForArtNr = con.prepareStatement(ForArtNrStatement); getItemHgrupp = con.prepareStatement(ItemHgruppStatement); } catch (SQLException e) { return(false); } finally { try {con.setAutoCommit(true);} catch (SQLException e) {} } return(true); } </code></pre> <p>-</p> <pre><code>public static synchronized String getItemBatch (String Titel) throws SQLException { String ret_xml; ResultSet rs = null; ResultSet rs1 = null; ResultSet rs2 = null; Titel = charChange(Titel); ret_xml = "&lt;ItemBatch Titel='" + Titel + "'&gt;"; try { con.setAutoCommit(false); getItemBatch.setString(1,Titel); rs = getItemBatch.executeQuery(); while (rs.next()) { getForArtNr.setInt(1,rs.getInt("Cartnr")); rs1 = getForArtNr.executeQuery(); getItemHgrupp.setInt(1,rs.getInt("Hgrupp")); rs2 = getItemHgrupp.executeQuery(); if (rs1.next() &amp;&amp; rs2.next()) { ret_xml += "&lt;item&gt;&lt;Hgrupp&gt;" + rs2.getString("Namn") + "&lt;/Hgrupp&gt;&lt;Price&gt;" + rs.getInt("Prisgrupp") + "&lt;/Price&gt;&lt;Moms&gt;" + rs.getInt("Moms") + "&lt;/Moms&gt;&lt;Cartnr&gt;" + rs.getInt("Cartnr") + "&lt;/Cartnr&gt;&lt;Artnr&gt;" + rs1.getInt("Artnr") + "&lt;/Artnr&gt;&lt;/item&gt;"; } } ret_xml += "&lt;/ItemBatch&gt;"; return(ret_xml); } catch (SQLException e) { return("SQLException: " + e); } finally { try {con.setAutoCommit(true);} catch (SQLException e) {} if (rs != null) {rs.close();} if (rs1 != null) {rs1.close();} if (rs2 != null) {rs2.close();} } } </code></pre> <p>.</p> <p><strong>UPDATE:</strong> I'm still googling and looking for ways to do better. Let me add something for your consideration.</p> <p>I'm closing the prepared statements via the servlet's destroy() method; the same servlet that calls the method "initialize()" above in order to create them. The idea is to create them once (and only once) and have them available forever for all users (i.e. until the app or server is shut down). I'm going for a kind-of a pseudo-stored procedure. I would just use stored procedures straight out, but the database exists to support another application (their in-house sales system) and I'm going to use it for Internet sales read-only ... avoiding any potential conflict with their maintenance efforts or agreements etc. by not doing anything to change their database set-up. I have suggested that my app use a new account limited to read-only privileges. And come to think of it, I haven't tested whether I can use Prepared Statements in that mode; just seems like it should work.</p> <p>Each result set is closed in the finally block in the method where they are created. I guess that's ok? I reuse the same RS variable name for multiple result sets (on the second two) but close only once. But wait! Do I even need that? The ResultSets are declared within the scope of the method. If resetting them without closing the old ones doesn't cause leaks, then exiting the method should do just as well on its own. It is a static method, but the ResultSets will be reset every time it's used (at the very least). So, at most, there would just be a single set of ResultSet handles available for reuse; not run-away "leakage."</p> <p>I'm wondering if I can send the two select requests in the loop both at the same time, simply by turning them into one prepared statement separated by ';'. Or just found "MultipleActiveResultSets=True"; document allowing SQL Server to process multiple transaction requests on a single connection ... still investigating this. Or is there another way to create a prepared statement that would fetch ALL the data via a single submission? (Seems to me like there are too many round trips.) Finally, I might get a boost from using connection pooling, which I haven't done yet. It's low priority in my project right now, but I might have to do it before we go online. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T08:42:19.953", "Id": "33573", "Score": "0", "body": "So you need to restart the app if connection somehow is closed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T08:48:20.767", "Id": "33574", "Score": "0", "body": "what happens if the first of your three consecutive `ResultSet.close` invocations throws an `SQLException`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T08:51:42.400", "Id": "33575", "Score": "0", "body": "How much latency would be added to your page load that made you decide not to call preparestatement at each request?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:10:12.487", "Id": "33576", "Score": "0", "body": "Just edited and added a thought on closing the result sets. Do I even need to do that? See third paragraph in the UPDATE section (\"Each result set is closed ...). Good catch on exception ... but I don't know. Can it do that? Seemed safe since I'm checking to see if it's null first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:13:25.693", "Id": "33577", "Score": "0", "body": "Re: Latency. It wouldn't know beforehand whether the overhead of preparing the statements would be worth it. The number of products matching \"Titel\" returned can be anywhere from 1 to some much higher number. Oh wait. You're still suggesting doing it at \"page load\" rather than on each request for product data. There's a big difference between the first page load when the app is started and all subsequent page loads after it's initialized. I'll be wanting to configure Tomcat to initialize the app on start-up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:19:46.900", "Id": "33578", "Score": "0", "body": "Good questions abuzititin. Each time a request is made, I check to see if the connection is valid. If not, it requests another connection. Now that you mention it though, I don't know what happens to my prepared statements if the connection is dropped. Simple enough to test, I suppose. I'll just stop and restart the database system and see if it still works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:25:18.747", "Id": "33579", "Score": "0", "body": "http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#close%28%29 It has a `throws SQLException` declaration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:28:53.870", "Id": "33580", "Score": "0", "body": "I think I can just delete the close() calls: From your reference; \"Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.\"" } ]
[ { "body": "<p>Yes, you're doing it right. The performance differences you're seeing are most likely due, as you noted, to the differences between your data volumes. Since you're using SQL Server, you can use examine the database trace information to see how the queries perform when you have similar data volumes. Or you can just relax and smile smugly, knowing that <strong>your</strong> code will never be hacked by a SQL-injection exploit :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T23:27:21.043", "Id": "20945", "ParentId": "20931", "Score": "2" } }, { "body": "<p>There are a couple of issues I think you should be aware of.</p>\n\n<ul>\n<li><p>In JDBC, the default state of a connection is <code>getAutoCommit() == true</code>.</p>\n\n<p>you keep changing this to be false, then running some selects, and then setting it back to true.</p>\n\n<p>if it was true when you came in, then you set it to false. No problem, you then return it to true when you leave... but, if it was false, you keep it as false, then, when you leave, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#setAutoCommit%28boolean%29\" rel=\"nofollow\">you <strong>commit</strong> the transaction</a> that may have been open when your method was called.... this is probably not what you want.</p>\n\n<p>It is possible that there are other areas in your code where you are doing data changing statements, but, it is not apparent where. In your code, all the SQL statements are selects, and you are not changing anything, so your you are not doing any fancy locking. Why change the state of autoCommit at all?</p></li>\n<li><p>you are not closing your ResultSets.</p>\n\n<p>you have a very nice, neat final block which closes <code>rs</code>, <code>rs1</code>, and <code>rs2</code>, but, there are many, many <code>rs1</code> and <code>rs2</code> instances. You need to be closing them inside the inner <code>rs</code> loop:</p>\n\n<pre><code> rs = getItemBatch.executeQuery();\n while (rs.next()) {\n getForArtNr.setInt(1,rs.getInt(\"Cartnr\"));\n try {\n rs1 = getForArtNr.executeQuery();\n getItemHgrupp.setInt(1,rs.getInt(\"Hgrupp\"));\n rs2 = getItemHgrupp.executeQuery();\n if (rs1.next() &amp;&amp; rs2.next()) {\n ret_xml += \"&lt;item&gt;&lt;Hgrupp&gt;\" + rs2.getString(\"Namn\") + \"&lt;/Hgrupp&gt;&lt;Price&gt;\" + rs.getInt(\"Prisgrupp\") + \"&lt;/Price&gt;&lt;Moms&gt;\" + rs.getInt(\"Moms\") + \"&lt;/Moms&gt;&lt;Cartnr&gt;\" + rs.getInt(\"Cartnr\") + \"&lt;/Cartnr&gt;&lt;Artnr&gt;\" + rs1.getInt(\"Artnr\") + \"&lt;/Artnr&gt;&lt;/item&gt;\";\n }\n } finally {\n if (rs1 != null) {\n rs1.close();\n }\n rs1 = null;\n if (rs2 != null) {\n rs2.close();\n }\n rs2 = null;\n }\n\n }\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T22:52:12.967", "Id": "43460", "ParentId": "20931", "Score": "2" } } ]
{ "AcceptedAnswerId": "43460", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T12:05:18.587", "Id": "20931", "Score": "2", "Tags": [ "java", "sql", "sql-server" ], "Title": "SQL PreparedStatement; Am I doing it right?" }
20931
<p>I'm continuing to work on the <a href="http://rads.stackoverflow.com/amzn/click/0596007124" rel="nofollow noreferrer">Head First Design Patterns</a> book in an effort to become a more efficient and better Python programmer. Code review for the Strategy pattern in Chapter 1 is <a href="https://codereview.stackexchange.com/questions/20718/the-strategy-design-pattern-for-python-in-a-more-pythonic-way">here</a> with helpful explanations from the community.</p> <p>I've tried to implement the Observer design pattern from chapter 2 below in Python. In the book all the examples are in Java. I'm sure there are more idiomatic Python things that I can do to this code. In the first example in this chapter we implement the Subject so that it <em>pushes</em> data out to the individual observers. In my code I wanted the Subject to notify the observers that new data was available, and have the observers <em>pull</em> only the data that each individual observer was interested in. I also tried to unit test instead of just printing output.</p> <p>Some issues I don't know how to resolve:</p> <ul> <li><p>The <code>Observer</code> abstract class has an abstract method <code>update()</code>, but two other non-abstract methods <code>register_subject(self, subject)</code> and <code>remove_subject(self)</code>. So when I implement the concrete observers, it inherits these two methods. Is this a wrong way of using the Abstract Base Class?</p></li> <li><p>I've recently started to unit test and have had some trouble formulating my tests (for this particular example I wrote the tests after the code, although I know it's better to write the tests first). A particular example: I test that the Observers are in fact registered with the Subject by looking to see that the <code>observer</code> instance is in the <code>Subject._observer_list</code>, but this list is hidden. Is it ok for the test to be looking there?</p></li> <li><p>Any other comments or suggestions on the code?</p></li> </ul> <p><strong>Code</strong></p> <pre><code>#!/usr/bin/env python from abc import ABCMeta, abstractmethod import unittest """Implementation of the Observer pattern from Head First Design Patters (Chapter 2), using the pull method of passing data from the Subject to the Observer(s). """ ################################################################################ # Abstract classes ################################################################################ class Subject: __metaclass__ = ABCMeta @abstractmethod def register_observer(observer): """Registers an observer with Subject.""" pass @abstractmethod def remove_observer(observer): """Removes an observer from Subject.""" pass @abstractmethod def notify_observers(): """Notifies observers that Subject data has changed.""" pass class Observer: __metaclass__ = ABCMeta @abstractmethod def update(): """Observer updates by pulling data from Subject.""" pass def register_subject(self, subject): """Observer saves reference to Subject.""" self.subject = subject def remove_subject(self): """Observer replaces Subject reference to None.""" self.subject = None class DisplayElement: __metaclass__ = ABCMeta @abstractmethod def display(): """DisplayElement displays instance data.""" pass ################################################################################ # Concrete Subject class ################################################################################ class WeatherData(Subject): def __init__(self): self._observer_list = [] def register_observer(self, observer): """Registers an observer with WeatherData if the observer is not already registered.""" try: if observer not in self._observer_list: self._observer_list.append(observer) observer.register_subject(self) else: raise ValueError except ValueError: print "ERROR: Observer already subscribed to Subject!" raise ValueError def remove_observer(self, observer): """Removes an observer from WeatherData if the observer is currently subscribed to WeatherData.""" try: if observer in self._observer_list: observer.remove_subject() self._observer_list.remove(observer) else: raise ValueError except ValueError: print "ERROR: Observer currently not subscribed to Subject!" raise ValueError def notify_observers(self): """Notifies subscribed observers of change in WeatherData data.""" for observer in self._observer_list: observer.update() def set_measurements(self, temperature, humidity, pressure): """Function used to simulate weather station device and send out new data.""" self.temperature = temperature self.humidity = humidity self.pressure = pressure self.notify_observers() ################################################################################ # Concrete Observer/DisplayElement classes ################################################################################ class CurrentConditionDisplay(Observer, DisplayElement): """Returns the current temperature and humidity.""" def update(self): self.temperature = self.subject.temperature self.humidity = self.subject.humidity self.display() def display(self): print "Current conditions: %.1f F degrees and %.1f %% humidity" %\ (self.temperature, self.humidity) class ForecastDisplay(Observer, DisplayElement): """Returns the a forcast of the weather based on pressure readings.""" def __init__(self): self.current_pressure = 29.92 def update(self): self.last_pressure = self.current_pressure self.current_pressure = self.subject.pressure self.display() def display(self): if self.current_pressure &gt; self.last_pressure: print "Improving weather on the way!" elif self.current_pressure == self.last_pressure: print "More of the same" elif self.current_pressure &lt; self.last_pressure: print "watch out for cooler, rainy weather" class StatisticsDisplay(Observer, DisplayElement): """Returns the temperature statistics for all readings.""" def __init__(self): self._min_temp = 200 self._max_temp = 0 self._temp_sum = 0 self._num_readings = 0 def update(self): if self.subject.temperature &gt; self._max_temp: self._max_temp = self.subject.temperature if self.subject.temperature &lt; self._min_temp: self._min_temp = self.subject.temperature self._temp_sum += self.subject.temperature self._num_readings += 1 self.display() def display(self): print "Avg/Max/Min temperature = %.1f/%.1f/%.1f" %\ (float(self._temp_sum/self._num_readings), self._max_temp, self._min_temp) ################################################################################ # Unit tests ################################################################################ class TestWeatherData(unittest.TestCase): def setUp(self): self.weather_data = WeatherData() self.current_condition_display = CurrentConditionDisplay() self.forecast_display = ForecastDisplay() self.statistics_display = StatisticsDisplay() def test_register_observers(self): # Register observers with subject. self.weather_data.register_observer(self.current_condition_display) self.weather_data.register_observer(self.forecast_display) self.weather_data.register_observer(self.statistics_display) # Check registered observers in _observer_list. self.assertIn(self.current_condition_display, self.weather_data._observer_list) self.assertIn(self.forecast_display, self.weather_data._observer_list) self.assertIn(self.statistics_display, self.weather_data._observer_list) def test_register_remove_forcast_display(self): # Register observer with subject. self.weather_data.register_observer(self.forecast_display) # Check registered observer in _observer_list. self.assertIn(self.forecast_display, self.weather_data._observer_list) # Remove observer from subject. self.weather_data.remove_observer(self.forecast_display) # Check observer not in _observer_list. self.assertNotIn(self.forecast_display, self.weather_data._observer_list) def test_remove_nonexistant_display(self): # Check removing an observer already not in _observer_list throws a # ValueError. with self.assertRaises(ValueError): self.weather_data.remove_observer(self.forecast_display) def test_no_register_display_twice_display(self): # Check that adding an observer twice to in _observer_list throws a # ValueError. with self.assertRaises(ValueError): self.weather_data.register_observer(self.forecast_display) self.weather_data.register_observer(self.forecast_display) class TestDisplays(unittest.TestCase): def setUp(self): self.weather_data = WeatherData() self.current_condition_display = CurrentConditionDisplay() self.forecast_display = ForecastDisplay() self.statistics_display = StatisticsDisplay() self.weather_data.register_observer(self.current_condition_display) self.weather_data.register_observer(self.forecast_display) self.weather_data.register_observer(self.statistics_display) def test_set_measurements(self): # Setting measurements and making sure they are passed correctly. self.weather_data.set_measurements(80, 65, 30.4) self.assertEqual(self.current_condition_display.temperature, 80) self.assertEqual(self.current_condition_display.humidity, 65) self.assertEqual(self.forecast_display.current_pressure, 30.4) self.weather_data.set_measurements(82, 70, 29.2) self.assertEqual(self.current_condition_display.temperature, 82) self.assertEqual(self.current_condition_display.humidity, 70) self.assertEqual(self.forecast_display.current_pressure, 29.2) self.weather_data.set_measurements(87, 90, 29.2) self.assertEqual(self.current_condition_display.temperature, 87) self.assertEqual(self.current_condition_display.humidity, 90) self.assertEqual(self.forecast_display.current_pressure, 29.2) if __name__ == '__main__': unittest.main() </code></pre> <p><strong>Output</strong></p> <pre><code>Current conditions: 80.0 F degrees and 65.0 % humidity Improving weather on the way! Avg/Max/Min temperature = 80.0/80.0/80.0 Current conditions: 82.0 F degrees and 70.0 % humidity watch out for cooler, rainy weather Avg/Max/Min temperature = 81.0/82.0/80.0 Current conditions: 87.0 F degrees and 90.0 % humidity More of the same Avg/Max/Min temperature = 83.0/87.0/80.0 .ERROR: Observer already subscribed to Subject! ...ERROR: Observer currently not subscribed to Subject! . ---------------------------------------------------------------------- Ran 5 tests in 0.001s OK </code></pre>
[]
[ { "body": "<p>A few random comments on pieces of the code:</p>\n\n<pre><code>class Subject:\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def register_observer(observer):\n \"\"\"Registers an observer with Subject.\"\"\"\n pass\n\n @abstractmethod\n def remove_observer(observer):\n \"\"\"Removes an observer from Subject.\"\"\"\n pass\n\n @abstractmethod\n def notify_observers():\n \"\"\"Notifies observers that Subject data has changed.\"\"\"\n pass\n</code></pre>\n\n<p>Why aren't you defining these methods? It seems to me they'll be the same for all subclasses so you don't need to make them abstract and implement them there.</p>\n\n<pre><code> def register_observer(self, observer):\n \"\"\"Registers an observer with WeatherData if the observer is not\n already registered.\"\"\"\n try:\n if observer not in self._observer_list:\n self._observer_list.append(observer)\n observer.register_subject(self)\n else:\n raise ValueError\n</code></pre>\n\n<p>Don't throw generic exceptions that might get mistaken for something else. I'd <code>raise Exception(\"Observer already subscribed to Subject!\")</code> or a custom exception class.</p>\n\n<pre><code> except ValueError:\n print \"ERROR: Observer already subscribed to Subject!\"\n</code></pre>\n\n<p>Don't print error messages, just throw exceptions.</p>\n\n<pre><code> raise ValueError\n</code></pre>\n\n<p>Certainly don't catch an exception right after throwing it and then throw it again.</p>\n\n<blockquote>\n <p>The Observer abstract class has an abstract method update(), but two\n other non-abstract methods register_subject(self, subject) and\n remove_subject(self). So when I implement the concrete observers, it\n inherits these two methods. Is this a wrong way of using the Abstract\n Base Class?</p>\n</blockquote>\n\n<p>That is a perfectly valid and common way of abstract base classes.</p>\n\n<blockquote>\n <p>I've recently started to unit test and have had some trouble\n formulating my tests (for this particular example I wrote the tests\n after the code, although I know it's better to write the tests first).\n A particular example: I test that the Observers are in fact registered\n with the Subject by looking to see that the observer instance is in\n the Subject._observer_list, but this list is hidden. Is it ok for the\n test to be looking there?</p>\n</blockquote>\n\n<p>No, you shouldn't test the internal state of the object. You should test the external actions of the object. Here is a sample of how you should test it:</p>\n\n<pre><code>class MyObserver(Observer):\n def __init__(self):\n self.updated = False\n\n def update(self):\n self.updated = True\n\ndef test_it():\n temperature_data = TemperatureData()\n observer = MyObserver()\n temperature_data.register_observer(observer)\n assert not observer.updated()\n temperature_data.set_measurements(2,4,4)\n assert observer.updated()\n</code></pre>\n\n<p>But the observer pattern is really not a great fit for python. It is not flexible and doesn't take advantage of python's features. The pattern I use is something like this:</p>\n\n<pre><code>class Signal(object):\n def __init__(self):\n self._handlers = []\n\n def connect(self, handler):\n self._handlers.append(handler)\n\n def fire(self, *args):\n for handler in self._handlers:\n handler(*args)\n</code></pre>\n\n<p>On the <code>Subject</code> I'd do this:</p>\n\n<pre><code>class TemperatureData:\n def __init__(self):\n self.changed = Signal()\n\n def set_temperaturedata(self, foo, bar):\n ...\n self.changed.fire(self)\n</code></pre>\n\n<p>Then to hook things up I'd say</p>\n\n<pre><code>display = TemperatureDisplay()\ntemperature_data.changed.connect(display.update_temperaturedata)\n</code></pre>\n\n<p>I think this model is simpler. It lets objects emit multiple signals that could be observed, a given object can observer multiple other objects. The <code>TemperatureDisplay</code> object doesn't even know where the data is coming from, it just magically shows up on <code>update_temperaturedata</code> making it easier to test that object in isolation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T19:02:05.480", "Id": "20940", "ParentId": "20938", "Score": "16" } } ]
{ "AcceptedAnswerId": "20940", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-26T17:59:59.730", "Id": "20938", "Score": "14", "Tags": [ "python", "unit-testing", "observer-pattern" ], "Title": "The Observer design pattern in Python, with unit tests" }
20938
<p>I have the code below I probably did not need to post the entirety of it but you can see in the code that I make multiple data base queries to generate each of the multiple tables. I am curious if there is a way to make one query and yet get the same results, and possibly clean up the code.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C/DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Lieber Construction Time Clock&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-1.9.0.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="jsFunctions.js" type="text/javascript"&gt;&lt;/script&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /&gt; &lt;link media="Screen" href="timeCard.css" type="text/css" rel="stylesheet" /&gt; &lt;link media="only screen and (max-device-width: 480px) and (min-device-width: 320px)" href="mobile.css" type="text/css" rel="stylesheet" /&gt; &lt;/head&gt; &lt;body&gt; &lt;select size="1" name="equipmentTable" id="equipmentTable"&gt; &lt;option value=""&gt;Select Machine&lt;/option&gt; &lt;option value="Blade"&gt;Blade&lt;/option&gt; &lt;option value="Challenger"&gt;Challenger&lt;/option&gt; &lt;option value="Compactor"&gt;Compactor&lt;/option&gt; &lt;option value="Dozer"&gt;Dozer&lt;/option&gt; &lt;option value="Excavator"&gt;Excavator&lt;/option&gt; &lt;option value="Loader"&gt;Loader&lt;/option&gt; &lt;option value="Skid"&gt;Skid&lt;/option&gt; &lt;option value="Tractor"&gt;Tractor&lt;/option&gt; &lt;option value="Truck"&gt;Truck&lt;/option&gt; &lt;/select&gt; &lt;div class="tables"&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Challenger"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Challenger"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Dozer"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Dozer"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Truck"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Truck"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Excavator"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Excavator"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Skid"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Skid"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Compactor"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Compactor"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Loader"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Loader"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Tractor"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Tractor"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php require 'DB.php'; try { $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber'); $stmt-&gt;execute(); } catch(PDOException $e){ echo'ERROR: ' . $e-&gt;getMessage(); } ?&gt; &lt;div class="Blade"&gt; &lt;table class='tableTwo'&gt; &lt;tr&gt; &lt;th&gt;Equipment Type&lt;/th&gt; &lt;th&gt;Unit Number&lt;/th&gt; &lt;th&gt;Last Updated&lt;/th&gt; &lt;th&gt;Current Hours&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;th&gt;Hours on motor oil&lt;/th&gt; &lt;th&gt;Last Service&lt;/th&gt; &lt;/tr&gt; &lt;?php while ($row=$stmt-&gt;fetch()){ $equipType = $row['equipType']; if ($equipType == "Blade"){ echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $equipType . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['unitNumber'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['lastUpdate'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['currentHours'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['oilChange'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T21:35:35.790", "Id": "33566", "Score": "1", "body": "I'm not sure whether this is offtopic. If you are asking a specific question, try stackoverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T22:09:15.707", "Id": "33570", "Score": "1", "body": "Why are you fetching the same table again and again? Especially, without any limits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T23:33:14.057", "Id": "33571", "Score": "0", "body": "Everything I need is stored in the same table I am new to programming so if you have any advice that would be awesome" } ]
[ { "body": "<p>Unless I'm missing something, you're <code>SELECT</code>ing the entire table over an over, then do exactly the same thing with it every time (except with different HTML class names). If that's the case, you can replace the whole file with this:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C/DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"&gt;\n &lt;title&gt;Lieber Construction Time Clock&lt;/title&gt;\n &lt;script src=\"http://code.jquery.com/jquery-1.9.0.js\"&gt;&lt;/script&gt;\n &lt;script src=\"http://code.jquery.com/ui/1.10.0/jquery-ui.js\"&gt;&lt;/script&gt;\n &lt;script src=\"jsFunctions.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" /&gt;\n &lt;link media=\"Screen\" href=\"timeCard.css\" type=\"text/css\" rel=\"stylesheet\" /&gt;\n &lt;link media=\"only screen and (max-device-width: 480px) and (min-device-width: 320px)\" href=\"mobile.css\" type=\"text/css\" rel=\"stylesheet\" /&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;select size=\"1\" name=\"equipmentTable\" id=\"equipmentTable\"&gt;\n &lt;option value=\"\"&gt;Select Machine&lt;/option&gt;\n &lt;option value=\"Blade\"&gt;Blade&lt;/option&gt;\n &lt;option value=\"Challenger\"&gt;Challenger&lt;/option&gt;\n &lt;option value=\"Compactor\"&gt;Compactor&lt;/option&gt;\n &lt;option value=\"Dozer\"&gt;Dozer&lt;/option&gt;\n &lt;option value=\"Excavator\"&gt;Excavator&lt;/option&gt;\n &lt;option value=\"Loader\"&gt;Loader&lt;/option&gt;\n &lt;option value=\"Skid\"&gt;Skid&lt;/option&gt;\n &lt;option value=\"Tractor\"&gt;Tractor&lt;/option&gt;\n &lt;option value=\"Truck\"&gt;Truck&lt;/option&gt;\n &lt;/select&gt;\n &lt;div class=\"tables\"&gt;\n&lt;?php\nrequire_once 'DB.php';\ntry\n{\n $stmt = $conn-&gt;prepare('SELECT * FROM equipment ORDER BY equipType, unitNumber');\n $stmt-&gt;execute();\n}\ncatch(PDOException $e)\n{\n echo'ERROR: ' . $e-&gt;getMessage();\n}\n$lastType;\n$num = 0;\nwhile($row = $stmt-&gt;fetch())\n{\n $equipType = $row['equipType'];\n if($equipType !== $lastType)\n {\n if($num !== 0)\n {\n echo \"&lt;/table&gt;&lt;/div&gt;\";\n }\n echo \"&lt;div class=\\\"$equipType\\\"&gt;\n &lt;table class=\\\"tableTwo\\\"&gt;\n &lt;tr&gt;\n &lt;th&gt;Equipment Type&lt;/th&gt;\n &lt;th&gt;Unit Number&lt;/th&gt;\n &lt;th&gt;Last Updated&lt;/th&gt;\n &lt;th&gt;Current Hours&lt;/th&gt;\n &lt;th&gt;Last Service&lt;/th&gt;\n &lt;th&gt;Hours on motor oil&lt;/th&gt;\n &lt;th&gt;Last Service&lt;/th&gt;\n &lt;/tr&gt;\";\n }\n echo \"&lt;tr&gt;\";\n echo \"&lt;td&gt;$equipType&lt;/td&gt;\";\n echo \"&lt;td&gt;\" . $row['unitNumber'] . \"&lt;/td&gt;\";\n echo \"&lt;td&gt;\" . $row['lastUpdate'] . \"&lt;/td&gt;\";\n echo \"&lt;td&gt;\" . $row['currentHours'] . \"&lt;/td&gt;\";\n echo \"&lt;td&gt;\" . $row['oilChange'] . \"&lt;/td&gt;\";\n echo \"&lt;/tr&gt;\";\n $lastType = $equipType;\n $num++;\n}\necho \"&lt;/table&gt;&lt;/div&gt;\";\n?&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Additionally, I'd suggest reading up on your SQL for a start, this whole thing screams out <code>WHERE</code> clause. In every case, your database will be more efficient at sorting the results than whatever programming language you're using them in (and certainly PHP). Such as:</p>\n\n<pre><code>SELECT * FROM equipment WHERE equipType = \"Challenger\" ORDER BY unitNumber;\n</code></pre>\n\n<p>Another thing you should be careful about is <code>require</code>ing the same thing over and over, as it's usually unnecessary and can be replaced with a <code>require_once</code> which will ensure that it's only loaded if it hasn't been in the current session.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T05:09:20.380", "Id": "20949", "ParentId": "20943", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T20:55:23.883", "Id": "20943", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "Cleaner more efficient way of multiple database queries" }
20943
<p>Here's a small module I've written that implements an animation which fades through the child elements in a container div on a continual loop. </p> <p>I realise I could have done this way quicker using JQuery, but I wanted to write it from scratch in this case.</p> <p>The module works well enough, but I'd be very grateful for any comments on the code.</p> <pre><code>(function() { function fade(e, duration, direction, /* 'in', 'out' */ easing, /* func */ complete /* callback */) { // Set default values for parameters if (easing === undefined) easing = linear; if (complete === undefined) complete = function(){}; // initialise counter values var percentComplete = 0; var opacity = parseFloat(e.style.opacity); if (opacity &lt; 0) opacity = 0; if (opacity &gt; 1) opacity = 1; // initialise values that stay constant throughout execution var startOpacity = opacity; var framerate = 60; var startTime = (new Date()).getTime(); function animate() { if (percentComplete &gt;= 1.0) { return complete(); } var elapsedTime = (new Date()).getTime() - startTime; percentComplete = elapsedTime / duration; var easing_options = {elapsedTime: elapsedTime, endValue: 1, totalDuration: duration} if (direction === "in") { easing_options.startValue = startOpacity; opacity = easing(easing_options); } else if (direction === 'out') { easing_options.startValue = 1 - startOpacity; opacity = 1 - easing(easing_options); }; e.style.opacity = opacity; setTimeout(animate, 1000/framerate); } setTimeout(animate, 1000/framerate); }; function fadeIn(e, duration, easing, complete) { fade(e, duration, 'in', easing, complete); } function fadeOut(e, duration, easing, complete) { fade(e, duration, 'out', easing, complete); }; // default easing function var linear = function(options) { var elapsedTime = options.elapsedTime; var startValue = options.startValue; var endValue = options.endValue; var totalDuration = options.totalDuration; var difference = endValue - startValue; var result = startValue + ((elapsedTime / totalDuration) * difference) return result }; // Utility. Bidirectional circular iterator. function Cycle(arraylike) { this.values = arraylike; this.index = null; } Cycle.prototype._resetIndex = function() { this.index = this.index % this.values.length; }; Cycle.prototype.next = function() { if (this.index === null) { this.index = 0; } else { this.index += 1; this._resetIndex(); } return this.values[this.index] }; Cycle.prototype.previous = function() { this.index = (this.index === null ? 0 : this.index) + (this.values.length - 1) this._resetIndex(); return this.values[this.index]; }; Cycle.prototype.current = function() { return (this.index !== null ? this.values[this.index] : this.next()) }; // The main fader constructor. Fades through the child elements of a // container div on a continual loop. function Fader(options /* container, fadeLength, pauseLength */) { this.container = document.getElementById(options.container); var ch = this.container.children // Initialise opacity and position for child Elements of the // container div ch[0].style.opacity = 1; ch[0].style.position = "absolute"; ch[0].style.top = "0px"; ch[0].style.left = "0px"; for (i = 1; i &lt; ch.length; i++) { ch[i].style.opacity = 0; ch[i].style.position = "absolute"; ch[i].style.top = "0px"; ch[i].style.left = "0px"; } this.slides = new Cycle(ch); this.fadeLength = options.fadeLength; this.pauseLength = options.pauseLength; } Fader.prototype.start = function() { var self = this; var fadeLength = this.fadeLength; var pauseLength = this.pauseLength; setTimeout(function() { fadeOut(self.slides.next(), fadeLength); fadeIn(self.slides.next(), fadeLength); self.timer = setInterval(function() { fadeOut(self.slides.current(), fadeLength); fadeIn(self.slides.next(), fadeLength); }, fadeLength + pauseLength) }, pauseLength); }; Fader.prototype.stop = function() { clearInterval(this.timer); this.slides.previous(); }; // Exported object var exports = { fadeIn: fadeIn, fadeOut: fadeOut, noConflict: noConflict, Fader: Fader }; // Mechanism to remove naming conflicts if another module exports // the name Fader var noConflictName = window['fadeLib']; function noConflict() { window['fadeLib'] = noConflictName; return exports; } // Export public interface window['fadeLib'] = exports; })(); </code></pre> <p>Here's a html snippet showing how the module is used.</p> <pre><code>&lt;body&gt; &lt;div id="container" style="position:absolute; left:100px; width:500px;"&gt; &lt;h1 style="color:red;"&gt;Hello world!&lt;/h1&gt; &lt;h1 style="color:red;"&gt;Goodbye!&lt;/h1&gt; &lt;h1 style="color:red;"&gt;Farewell!&lt;/h1&gt; &lt;/div&gt; &lt;script src="faderLib.js"&gt;&lt;/script&gt; &lt;script&gt; window.addEventListener("load", function() { var fader = new fadeLib.Fader({container: "container", fadeLength: 5000, pauseLength: 5000}); fader.start(); }); &lt;/script&gt; &lt;/body&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:27:35.240", "Id": "33706", "Score": "0", "body": "Available for fiddling @ http://jsfiddle.net/vudC2/ (with a 2-second delay because I am impatient)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:33:46.383", "Id": "33714", "Score": "0", "body": "does `Cycle` really need that much complexity? Why do you set `style.top, style.left` to `0px`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:56:26.620", "Id": "33715", "Score": "0", "body": "`Cycle.Next` and `Cycle.Previous` use different idioms [is that the right word?] for basically the same code. Although Cycle.Previous makes an invariant call to `_resetIndex`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T22:12:17.713", "Id": "33719", "Score": "0", "body": "I suppose its not strictly necessary for the purpose at hand. But it seemed like a generally useful pattern. I'm not sure I understand what you mean by \"different idioms for the same code\" in this case. Can you elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T02:44:42.013", "Id": "33732", "Score": "0", "body": "I added my thoughts about mixed idioms, below." } ]
[ { "body": "<p>Small changes:</p>\n\n<p>Cache the length, and set the invariants only once:</p>\n\n<pre><code> // Initialise opacity and position for child Elements of the\n // container div\n for (var i = 0, l = ch.length; i &lt; l; i++) {\n ch[i].style.opacity = 0;\n ch[i].style.position = \"absolute\";\n ch[i].style.top = \"0px\";\n ch[i].style.left = \"0px\";\n }\n\n // only first element is visible\n ch[0].style.opacity = 1;\n</code></pre>\n\n<p>Multiple coding idioms in the Cycle object:\nclear <code>if...else</code> in <code>.next</code> changes to a ternary op and an invariant call to <code>.resetIndex</code> in <code>.previous</code>, and change to _resetIndex to handle negative movement.</p>\n\n<pre><code>Cycle.prototype._resetIndex = function() {\n this.index = this.index % this.values.length;\n};\nCycle.prototype.next = function() {\n if (this.index === null) {\n this.index = 0;\n }\n else {\n this.index += 1; \n this._resetIndex();\n }\n return this.values[this.index]\n};\nCycle.prototype.previous = function() {\n\n this.index = (this.index === null ? 0 : this.index) + (this.values.length - 1)\n this._resetIndex();\n return this.values[this.index];\n};\n</code></pre>\n\n<p>change to (perhaps):</p>\n\n<pre><code>Cycle.prototype._resetIndex = function() {\n this.index = (this.index + this.values.length) % this.values.length;\n};\n\nCycle.prototype.next = function() {\n if (this.index === null) {\n this.index = 0;\n }\n else {\n this.index++;\n this._resetIndex();\n }\n return this.values[this.index]\n};\n\nCycle.prototype.previous = function() {\n\n if (this.index === null) {\n this.index = (this.values.length - 1);\n }\n else {\n this.index--;\n this._resetIndex();\n }\n\n return this.values[this.index];\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T09:26:16.963", "Id": "33745", "Score": "0", "body": "Thanks. That clarifies your mixed idioms idioms comment. However, I believe there is a small error in the 'previous' method. For example, in a nodelist on length 6, where this.index starts at 3, calling previous would make this.index = 2 + (5 - 1) = 7. _resetIndex would then make this index 1, where we want index 2. I think the solution is just to say this.index += this.values.length - 1, and then call this,_resetIndex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:10:33.930", "Id": "33773", "Score": "1", "body": "I hadn't actually tried out the code, so fiddled with it a bit. Similar idioms can happen if we make a tweak to the _resetIndex method. Now next() and previous() are so similar it suggests some more refactoring might be possible (only the initial element on index === null and increment/decrement are different)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:34:57.677", "Id": "21003", "ParentId": "20947", "Score": "2" } } ]
{ "AcceptedAnswerId": "21003", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T01:30:30.313", "Id": "20947", "Score": "1", "Tags": [ "javascript", "dom", "easing" ], "Title": "Javascript looping fader animation" }
20947
<p>I am writing a small oauth2 library for Play! 2.1 scala. As I am still learning I got stuck trying to TDD and ended up writing the code first, then refactoring for testability. By testability I mean two things:</p> <ol> <li>make the code testable by me as the author</li> <li>make it easy for users (since I will be a user) to stub/mock it out.</li> </ol> <p>The first working version of the code looked like (<a href="https://github.com/jeantil/play-oauth2/blob/e492bd2822884587ed4ddb82a26c5e2956581ca8/src/main/scala/package.scala" rel="nofollow">complete file on github</a>):</p> <pre><code>object GoogleOAuth2 extends OAuth2(GoogleOAuth2Settings) { lazy val signIn = s"${settings.signInUrl}?client_id=${settings.clientId}&amp;redirect_uri=${settings.redirectUri}"+ "&amp;response_type=code&amp;approval_prompt=force&amp;hd=xebia.fr"+ "&amp;scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile" def requestAccessTockenWS(code: String): Future[Response] = WS.url(settings.accessTokenUrl).post( Map("client_id" -&gt; Seq(settings.clientId) , "client_secret" -&gt; Seq(settings.clientSecret) , "code" -&gt; Seq(code) , "redirect_uri" -&gt; Seq(settings.redirectUri) , "grant_type" -&gt; Seq("authorization_code"))) } </code></pre> <p>The <code>requestAccessTockensWS</code> method depends on the WS API in Play2! This API is exposed as a scala object whith methods which create builders. These builders allow you to compose and call HTTP requests. In a normal setting I might choose not to test <code>requestAccessTockenWS</code> since it is a very small method with almost no logic of its own. However it is a nice "simple" case of dependecy on a scala object for exploring design patterns which enable tests. </p> <p>Here is the testcase I ended up writing (<a href="https://github.com/jeantil/play-oauth2/blob/master/src/test/scala/play/module/oauth2/OAuth2Spec.scala" rel="nofollow">complete on github</a>):</p> <pre><code> "GoogleOAuth2" should { import play.api.libs.ws.WS import play.api.libs.ws.Response object TestSettings extends GoogleOAuth2Settings { override lazy val clientId = testConfig("oauth2.google.cliend_id") override lazy val clientSecret = testConfig("oauth2.google.cliend_secret") override lazy val signInUrl = testConfig("oauth2.google.signInUrl") override lazy val accessTokenUrl = testConfig("oauth2.google.accessTokenUrl") override lazy val userInfoUrl = testConfig("oauth2.google.userInfoUrl") override lazy val redirectUri = testConfig("oauth2.google.redirect_uri") } class MockedGoogleOauth2 extends GoogleOAuth2(TestSettings) { override def url = testUrl _ lazy val requestHolder: WS.WSRequestHolder = mock[WS.WSRequestHolder] def testUrl(s: String): WS.WSRequestHolder = { requestHolder.url returns s requestHolder } } "requestAccessTokens" in { import concurrent._ import ExecutionContext.Implicits.global import concurrent.duration._ import play.api.http.{ Writeable, ContentTypeOf } import org.mockito.Matchers.{ eq =&gt; mEq } import org.mockito.Matchers val underTest = new MockedGoogleOauth2() val mockWs = underTest.requestHolder val fakeResponse = mock[Response] val expected = Map("client_id" -&gt; Seq("client_id"), "client_secret" -&gt; Seq("client_secret"), "code" -&gt; Seq("code"), "redirect_uri" -&gt; Seq("http://redirect"), "grant_type" -&gt; Seq("authorization_code")) type Params = Map[String, Seq[String]] mockWs.post[Params](mEq(expected))(Matchers.any[Writeable[Params]], Matchers.any[ContentTypeOf[Params]]) returns Future.successful(fakeResponse) //when val willBeResponse = underTest.requestAccessTockenWS("code") there was one(mockWs).post(mEq(expected))(any, any) Await.result(willBeResponse, 5 milli) must beEqualTo(fakeResponse) } } </code></pre> <p>and the corresponding refactored code (<a href="https://github.com/jeantil/play-oauth2/blob/master/src/main/scala/play/module/oauth2/package.scala" rel="nofollow">complete on github</a>):</p> <pre><code>abstract class GoogleOAuth2[U &lt;: GoogleOAuth2Settings](override val settings: U) extends OAuth2(settings) { lazy val signIn = s"${settings.signInUrl}?client_id=${settings.clientId}&amp;redirect_uri=${settings.redirectUri}"+ "&amp;response_type=code&amp;approval_prompt=force&amp;hd=xebia.fr"+ "&amp;scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile" def url = WS.url _ def requestAccessTockenWS(code: String): Future[Response] = { val u = url(settings.accessTokenUrl) val params = Map("client_id" -&gt; Seq(settings.clientId) , "client_secret" -&gt; Seq(settings.clientSecret) , "code" -&gt; Seq(code) , "redirect_uri" -&gt; Seq(settings.redirectUri) , "grant_type" -&gt; Seq("authorization_code")) u.post(params) } } object GoogleOAuth2 extends GoogleOAuth2(GoogleOAuth2Settings) </code></pre> <p>The code and the tests work, and the client can use the same technique to mock it out. How can I improve on this?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T10:50:54.840", "Id": "20952", "Score": "3", "Tags": [ "object-oriented", "unit-testing", "scala", "authentication" ], "Title": "Testing Scala code which depends on objects" }
20952
<p>I'm still teaching myself C out of KN King's C Programming: Modern Approach. Actually pretty excited I go this problem solved in under 2 hours. I asked this over on Stack Overflow and it was recommended I post it here.</p> <p>The exercise is to print a magic square. My solution works but it feels incredibly convoluted. I'm wondering if it actually is? If anyone can help me reorganise the logic in this I'd appreciate it, or am I on the right track? Bear in mind this is Chapter 8, and we've only covered basics like loops, conditional statements, single and 2d arrays etc. I'm open to all constructive feedback.</p> <p><strong>The question:</strong></p> <blockquote> <p>Write a program that prints an \$n \times{} n\$ magic square (a square arrangement of the numbers \$1, 2, \ldots, n^2\$ in which the sums of the rows, columns and diagonals are all the same). The user will specify the value of \$n\$. </p> <p>Store the magic square in a 2D array. Start by placing the numbers 1 in the middle of row \$0\$. Place each of the remaining numbers \$2, 3, \ldots, n^2\$ by moving up one row and over one column.</p> <p>Any attempt to go outside the bounds of the array should "wrap around" to the opposite side of the array. For example, instead of storing the next number in row \$-1\$, we would store it in row \$n - 1\$ (the last row). Instead of storing the next number in column \$n\$, we would store it in column \$0\$.</p> <p>If a particular array element is already occupied, put the number directly below the previously stored number. If your compiler supports variable length arrays, declare the array to have \$n\$ rows and \$n\$ columns. If not, declare the array to have \$99\$ rows and \$99\$ columns.</p> </blockquote> <p><strong>My answer:</strong></p> <pre><code>// KN King Chapter 8 // Programming Projects // Exercise 17 - Magic Square #include &lt;stdio.h&gt; int main() { // Introductory message printf("This program creates a magic sqaure of a specified size.\n"); printf("The size must be an odd number between 1 and 99.\n"); // Get the users magic number and allocate to int n int n; printf("Enter size of magic square: "); scanf("%d", &amp;n); // Create the array (not using VLA) int magic[99][99]; int start = (n / 2); // The middle column int max = n * n; // The final number magic[0][start] = 1; // Place the number one in the middle of row 0 // Loop to start placing numbers in the magic square int row; int col; int next_row; int next_col; int i; for (i = 2, row = 0, col = start; i &lt; max + 1; i++) { if ((row - 1) &lt; 0) { // If going up one will leave the top next_row = n - 1; // Go to the bottom row } else { next_row = row - 1; } // Otherwise go up one printf("In row: %d\n", row); if ((col + 1) &gt; (n - 1)) { // If column will leave the side next_col = 0; // Wrap to first column printf("Column will leave side\n"); } else { next_col = col + 1; } // Otherwise go over one printf("In col: %d\n", col); if (magic[next_row][next_col] &gt; 0) { // If that position is taken if (row &gt; (n - 1)) { // If going to row below leaves bottom next_row = 0; // Go back to the top } else { next_row = row + 1; // Go to the row below next_col = col; // But stay in same column } } row = next_row; col = next_col; printf("About to put %d in row %d, col %d\n", i, row, col); magic[row][col] = i; // Put the current value in that position } // Now let's print the array int j; for (i = 0; i &lt; n; i++) { for (j = 0; j &lt; n; j++) { printf("%4d", magic[i][j]); } printf("\n"); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T16:03:48.150", "Id": "33587", "Score": "0", "body": "Starting the for-loop at i=2 seems a bit weird to me. I would recommend starting at i=1 and putting current value at be beginning of the loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T02:53:41.057", "Id": "33599", "Score": "0", "body": "I agree with you @sfk it does seem a little weird, but how do I place the 1 in the middle of the top row to start? I guess I could start the row and col one down and to the left so it goes up to the correct spot to place the starting 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-14T06:15:11.320", "Id": "216965", "Score": "0", "body": "[This](http://stackoverflow.com/questions/29957506/magic-square-code) will help you in the magic square. The only difference in this is that it doesn't asks the user to input the 9 numbers. Instead, it does itself. When you use the code, move the `srand` function outside of the `while` loop but remains in the `int main()` loop." } ]
[ { "body": "<p>I'm just using the <code>I</code>th row and <code>J</code>th column formula <a href=\"http://en.wikipedia.org/wiki/Magic_square#Method_for_constructing_a_magic_square_of_odd_order\" rel=\"nofollow\">here on wiki</a>.</p>\n\n<p>$$ n \\left(\\left(I + J - 1 + \\lfloor \\dfrac{n}{2} \\rfloor \\right) \\mod{n}\\right) + \\left( \\left( I + 2J - 2 \\right) \\mod{n} \\right) + 1 $$</p>\n\n<p>The loop will become:</p>\n\n<pre><code>for( i = 0; i &lt; n; i++ ) {\n for( j = 0; j &lt; n; j++ ) {\n magic[i][j] = n * ( (i + j - 1 + floor(n / 2)) % n ) + ( (i + 2 * j - 2) % n ) + 1;\n }\n}\n</code></pre>\n\n<p>Ofcourse, you'd need to include <code># include &lt;math.h&gt;</code> at the beginning so that <code>floor()</code> may work.</p>\n\n<p>Here's the <a href=\"http://ideone.com/N7eiPX\" rel=\"nofollow\">working</a> ideone link, with sample inputs. <strong>ignore the clutter by input = 99</strong> :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T02:52:22.027", "Id": "33598", "Score": "0", "body": "Thanks! I didn't even know it could be done this way. That certainly cleans it up a lot. I guess for the point of the way the author wanted the exercise done mine is the way it has to be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-14T10:43:31.667", "Id": "217001", "Score": "0", "body": "I'm sorry to criticise - but this is a completely different algorithm than posed in the exercise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T14:25:45.353", "Id": "506786", "Score": "0", "body": "Know your language. Including `<math.h>` and calling `floor()` is an unnecessary mess. It introduces a floating point arithmetics, while simple integer division `n/2` does exactly what is needed perfectly easily. The integer result of `n/2` is converted to `double`, then passed to `floor()` which returns it unchanged. Then that `double` result forces _the whole parenthese_ to be performed in FP till the `%` operator which forces a conversion back to `int`. And all that just for nothing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T12:47:23.097", "Id": "20954", "ParentId": "20953", "Score": "1" } }, { "body": "<p>I'm a beginner, studying on King. I've been doing this exercise last night.\nI found a simpler code, here's the ideone link: <a href=\"http://ideone.com/wD2EpN\" rel=\"nofollow\">http://ideone.com/wD2EpN</a></p>\n\n<p>The solution on the answer is really lean, but it doesn't work, rows and columns start from 0. Then it should be: </p>\n\n<pre><code>for(i = 0; i &lt; n; i++) {\n for(j = 0; j &lt; n; j++) {\n magic[(n -1 + i)%n][(n - 1 + j)%n] = n * ((i + j - 1 + (n - 1) / 2) % n) + ((i + 2 * j - 2) % n) + 1;\n }\n }\n</code></pre>\n\n<p>By the way, I guess this is what King was asking, since we had to use vectors and 'for' loops. The exercise was asking to move columns and row \"by hand\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T17:19:38.707", "Id": "26634", "ParentId": "20953", "Score": "1" } }, { "body": "<p>As the algorithm to use actually is described in the question I would like to point out a few issues.</p>\n\n<ol>\n<li>Actually this algorithm is only for odd magic squares. But as this was not part of the exercise ignore it for now.</li>\n<li>why not use n in the allocation of magic</li>\n<li>You have lots of ifs to implement the wrapping around. A neat trick to write it more compact is to use the modulo operator it would look like: <code>next_col = (col + 1) % n</code> </li>\n<li>Since you are processing input it is a good practice to check if the input is valid. e.g. numbers greater 99 will completely break this thing. Also negative numbers are kinda dangerous.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-14T10:50:08.797", "Id": "116768", "ParentId": "20953", "Score": "1" } }, { "body": "<p>You would save lots of code if you used a <code>%</code> operator to wrap indices at <code>0</code> and <code>n-1</code> boundaries:</p>\n\n<pre><code> int magic[99][99];\n int max = n * n;\n int row;\n int col;\n\n // make sure the array is properly initialized\n for (row = 0; row &lt; n; row++)\n for (col = 0; col &lt; n; col++)\n magic[row][col] = 0;\n\n // starting position\n row = 0;\n col = n / 2;\n\n int i;\n for (i = 1; i &lt;= max; i++) {\n magic[row][col] = i;\n\n int next_row = (row - 1 + n) % n;\n int next_col = (col + 2) % n;\n\n if (magic[next_row][next_col] &gt; 0) {\n row = (row + 1) % n;\n }\n else {\n row = next_row;\n col = next_col;\n }\n }\n</code></pre>\n\n<p>Note <code>+n</code> in <code>next_row</code> computation – it makes the left argument to <code>%</code> positive in the case of <code>row == 0</code>, so that the result is <code>n-1</code>. Without that the result might be minus one. (see e.g. <a href=\"https://stackoverflow.com/questions/11720656\">Modulo operation with negative numbers</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-14T13:56:07.717", "Id": "116781", "ParentId": "20953", "Score": "1" } } ]
{ "AcceptedAnswerId": "20954", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T12:03:21.897", "Id": "20953", "Score": "5", "Tags": [ "c", "array" ], "Title": "Magic Square in C" }
20953
<p>I am choosing to learn F# for my own enjoyment. I am getting to the point where concepts of F# seem to be pretty easy, but understanding some of the whys and whens is a bit harder.</p> <p>Before I get into the code and the explanation, let me put my question up front. I am asking where can I find better advice on formatting F# code for readability? Or can someone give me a few guiding tips based off of the example given below?</p> <p>So what are the best practices for code format and file layout?</p> <p>Now to the explanation of the code.</p> <p>I have started practicing coding Kata's in F# just to allow me to flex the language a little. The following program is an implementation of a <a href="http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html" rel="nofollow">natural sort</a>. This was my first attempt to solving the problem in a TDD fashion in F#, as such I chose to forgo any framework as I did not want to deal with figuring out how to use any of them and not break the functional paradigm.</p> <p>So the code below carries a light weight unit test framework.</p> <p>Here is the code for the natural sort:</p> <pre><code>namespace Katas open System.Linq module NaturalSortKata = exception InvalidException of string type Comparison = | Equal | Lesser | Greater static member Compare x y = if x = y then Equal elif x &gt; y then Greater else Lesser type ChunckType = | NumberType | StringType | Unknown static member GetType (c : char) = if System.Char.IsDigit(c) then NumberType else StringType member this.Compare other = match other with | ty when ty = this -&gt; Equal | Unknown -&gt; Lesser | NumberType when this = Unknown -&gt; Greater | NumberType -&gt; Lesser | StringType -&gt; Greater let natualCompare (left : string) (right : string) = if left = right then Equal else let fix str = new System.String( str |&gt; List.rev |&gt; List.toArray ) let gatherChunck str = let rec gather str acc = match str with | [] -&gt; let (ty, l) = acc (ty, fix(l)) | fistLetter::rest -&gt; match acc with | (ty, _) when ty = Unknown -&gt; let t = ChunckType.GetType(fistLetter) gather rest (t, fistLetter :: []) | (ty, l) when ty = ChunckType.GetType(fistLetter) -&gt; gather rest (ty, fistLetter::l) | (ty, l) -&gt; (ty, fix(l)) gather str (Unknown, []) let rec compare (left : string) (right : string) = if (not (left.Any())) || (not (right.Any())) then match left.Length, right.Length with | llen, rlen when llen = rlen -&gt; Equal | llen, rlen when llen &gt; rlen -&gt; Greater | llen, rlen when llen &lt; rlen -&gt; Lesser | _ -&gt; raise (InvalidException "Bad Data") else let lt, lChunk = left |&gt; Seq.toList |&gt; gatherChunck let rt, rChunk = right |&gt; Seq.toList |&gt; gatherChunck match lt.Compare rt with | Equal -&gt; if lChunk = rChunk then let lVal = left.Replace(lChunk, "") let rVal = right.Replace(rChunk, "") compare lVal rVal else match lt with | NumberType -&gt; Comparison.Compare (System.Int64.Parse(lChunk)) (System.Int64.Parse(rChunk)) | _ -&gt; Comparison.Compare lChunk rChunk | _ -&gt; lt.Compare(rt) compare left right </code></pre> <p>Here is the code for the tests:</p> <pre><code>namespace Katas.Testing open Katas.NaturalSortKata module Tests = let test left right expected title= let testRun x = let result = right |&gt; natualCompare left if result = expected then x |&gt; printfn "%d good" true else title + " fails" |&gt; printfn "%d %s" x result |&gt; sprintf "%d Actual: %A" x |&gt; sprintf "%d Expected: %A\r\n%s" x expected |&gt; printfn "%s" false testRun let testRunner tests= let rec runner x result tests = match tests with | [] -&gt; result | head::tests -&gt; let current = (head x) &amp;&amp; result tests |&gt; runner (x + 1) current tests |&gt; runner 1 true let test01 = "Simple Equality" |&gt; test "one" "one" Equal let test02 = "left &lt; right" |&gt; test "left" "right" Lesser let test03 = "beta &gt; alpha" |&gt; test "beta" "alpha" Greater let test04 = "\"9\" &lt; \"10\"" |&gt; test "9" "10" Lesser let test05 = "\"alpha9\" &lt; \"alpha10\"" |&gt; test "alpha9" "alpha10" Lesser let test06 = "\"alpha9Centary9\" &lt; \"alpha9Centary10\"" |&gt; test "alpha9Centary9" "alpha9Centary10" Lesser let test07 = "\"10\" &gt; \"9\"" |&gt; test "10" "9" Greater let test08 = "\"alpha10\" &gt; \"alpha9\"" |&gt; test "alpha10" "alpha9" Greater let test09 = "\"alpha9Centary9\" &lt; \"alpha9Centary10\"" |&gt; test "alpha9Centary10" "alpha9Centary9" Greater let tests = test01 :: test02 :: test03 :: test04 :: test05 :: test06 :: test07 :: test08 :: test09 ::[] let runTests = tests |&gt; testRunner |&gt; printfn "%b" </code></pre> <p>Here is the code that runs it all:</p> <pre><code>open Katas.NaturalSortKata open Katas.Testing.Tests [&lt;EntryPoint&gt;] let main argv = //Katas.Lockers.showLockerResults 300 runTests let _ = System.Console.ReadKey(true) 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T13:40:09.917", "Id": "33584", "Score": "0", "body": "BTW, I believe the idiomatic way of ignoring the result of something is `System.Console.ReadKey(true) |> ignore`, not declaring an unused local. Also, I think you don't even need to declare `main`, you can put the code directly at the top level of the file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T13:41:20.010", "Id": "33585", "Score": "0", "body": "Also, “chunck” is a typo, the correct spelling is “chunk”." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:37:26.313", "Id": "33954", "Score": "0", "body": "I did not know about ignore. Thank you. I started learning functional programming through Erlang, which an underscore is an ignore. I assumed that it would be the same." } ]
[ { "body": "<p>Your code formatting is very readable. The minor issue is that you don't have to indent after <code>namespace</code> declaration. I would choose to open module directly to save a level of indentation (see attached code later).</p>\n\n<blockquote>\n <p>So what are the best practices for code format and file layout?</p>\n</blockquote>\n\n<p>I think <a href=\"http://msdn.microsoft.com/en-us/library/dd233191.aspx\" rel=\"nofollow\">F# code formatting guidelines</a> have very concrete suggestions on these issues.</p>\n\n<p>There are a few small problems with your code:</p>\n\n<ol>\n<li><p>In <code>naturalCompare</code>, you should move local functions to the top so the logic of the function is clear.</p></li>\n<li><p>In <code>compare</code>, if you remove <code>when</code> in the last clause, you don't have to superficially throw an exception.</p></li>\n<li><p>Value <code>tests</code> is more readable in the form of normal list declaration.</p>\n\n<pre><code>let tests = [ test01; test02; test03; test04; test05; test06; test07; test08; test09; ]\n</code></pre></li>\n</ol>\n\n<p>Here is reformatted version of <code>Katas.NaturalSortKata</code> module. You could do the same for <code>Katas.Testing.Tests</code>.</p>\n\n<pre><code>// 0) Declare module to save a level of indentation\nmodule Katas.NaturalSortKata\n\nopen System.Linq\n\ntype Comparison =\n| Equal\n| Lesser\n| Greater\n static member Compare x y =\n if x = y then\n Equal\n elif x &gt; y then\n Greater\n else\n Lesser\n\ntype ChunckType =\n| NumberType\n| StringType\n| Unknown\n static member GetType (c : char) =\n if System.Char.IsDigit(c) then\n NumberType\n else\n StringType\n\n member this.Compare other = \n match other with\n | ty when ty = this -&gt; Equal\n | Unknown -&gt; Lesser\n | NumberType when this = Unknown -&gt; Greater\n | NumberType -&gt; Lesser\n | StringType -&gt; Greater\n\nlet naturalCompare (left : string) (right : string) = \n // 1) Move local functions on top\n let fix str =\n new System.String( str |&gt; List.rev |&gt; List.toArray )\n\n let gatherChunck str = \n let rec gather str acc =\n match str with\n | [] -&gt;\n let (ty, l) = acc\n (ty, fix(l))\n | fistLetter::rest -&gt;\n match acc with\n | (ty, _) when ty = Unknown -&gt;\n let t = ChunckType.GetType(fistLetter)\n gather rest (t, fistLetter :: [])\n | (ty, l) when ty = ChunckType.GetType(fistLetter) -&gt;\n gather rest (ty, fistLetter::l)\n | (ty, l) -&gt; (ty, fix(l))\n\n gather str (Unknown, [])\n\n let rec compare (left : string) (right : string) =\n if (not (left.Any())) || (not (right.Any())) then\n match left.Length, right.Length with\n | llen, rlen when llen = rlen -&gt; Equal\n | llen, rlen when llen &gt; rlen -&gt; Greater\n | llen, rlen -&gt; Lesser // 2) Remove superficial when guard\n else\n let lt, lChunk = left |&gt; Seq.toList |&gt; gatherChunck \n let rt, rChunk = right |&gt; Seq.toList |&gt; gatherChunck\n\n match lt.Compare rt with\n | Equal -&gt;\n if lChunk = rChunk then\n let lVal = left.Replace(lChunk, \"\")\n let rVal = right.Replace(rChunk, \"\")\n\n compare lVal rVal\n else\n match lt with\n | NumberType -&gt;\n Comparison.Compare (System.Int64.Parse(lChunk)) (System.Int64.Parse(rChunk))\n | _ -&gt;\n Comparison.Compare lChunk rChunk\n | _ -&gt;\n lt.Compare(rt)\n\n if left = right then\n Equal\n else\n compare left right\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>After answering your question, I started developing a source code formatter for F#. More information can be found <a href=\"https://github.com/dungpa/fantomas\" rel=\"nofollow\">on Gihub</a>.</p>\n\n<p>Results from the tool or <a href=\"https://github.com/dungpa/fantomas/blob/master/docs/FormattingConventions.md\" rel=\"nofollow\">its companion formatting guideline</a> can give you some hints for good formatting. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:26:20.920", "Id": "33779", "Score": "0", "body": "Thank you, the link is great, and the advice you give makes since." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T09:03:53.290", "Id": "20956", "ParentId": "20955", "Score": "6" } } ]
{ "AcceptedAnswerId": "20956", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T06:56:05.477", "Id": "20955", "Score": "5", "Tags": [ "unit-testing", "f#" ], "Title": "Kata: Natural Sort" }
20955
<p>I am trying to solve the 8 queens problem using a heuristic similar to "the accessibility heuristic" used in Knight's Tour problem. this heuristic simply means that each square of the chess board has the value of the numbers of squares that will be attacked if the queen is placed on that square. and asks me to place the next queen in the square that carries the lowest number (that attacks the least number of squares).</p> <p>I think I did it and here's my code, please check if there are an errors or better ways to do things.</p> <pre><code>public class Queen { private final int SIZE = 8;//board size private int[][] board;//chess board private int[]hor;//horizontal moves private int[]ver;//vertical moves private int eliminatedSquares; private int remainingSquares; public Queen () { //constructor initializes the board //initializes the moves board = new int[SIZE][SIZE]; //first row board[0][0] = 21; board[0][1] = 21; board[0][2] = 21; board[0][3] = 21; board[0][4] = 21; board[0][5] = 21; board[0][6] = 21; board[0][7] = 21; //second row board[1][0] = 21; board[1][1] = 23; board[1][2] = 23; board[1][3] = 23; board[1][4] = 23; board[1][5] = 23; board[1][6] = 23; board[1][7] = 21; //third row board[2][0] = 21; board[2][1] = 23; board[2][2] = 25; board[2][3] = 25; board[2][4] = 25; board[2][5] = 25; board[2][6] = 23; board[2][7] = 21; //forth row board[3][0] = 21; board[3][1] = 23; board[3][2] = 25; board[3][3] = 27; board[3][4] = 27; board[3][5] = 25; board[3][6] = 23; board[3][7] = 21; //fifth row board[4][0] = 21; board[4][1] = 23; board[4][2] = 25; board[4][3] = 27; board[4][4] = 27; board[4][5] = 25; board[4][6] = 23; board[4][7] = 21; //sixth row board[5][0] = 21; board[5][1] = 23; board[5][2] = 25; board[5][3] = 25; board[5][4] = 25; board[5][5] = 25; board[5][6] = 23; board[5][7] = 21; //seventh row board[6][0] = 21; board[6][1] = 23; board[6][2] = 23; board[6][3] = 23; board[6][4] = 23; board[6][5] = 23; board[6][6] = 23; board[6][7] = 21; //eighth row board[7][0] = 21; board[7][1] = 21; board[7][2] = 21; board[7][3] = 21; board[7][4] = 21; board[7][5] = 21; board[7][6] = 21; board[7][7] = 21; //initializing moves hor = new int[SIZE]; ver = new int[SIZE]; //right hor[0] = 1; ver[0] = 0; //left hor[1] = -1; ver[1] = 0; //up hor[2] = 0; ver[2] = -1; //down hor[3] = 0; ver[3] = 1; //upper right hor[4] = 1; ver[4] = -1; //upper left hor[5] = -1; ver[5] = -1; //down right hor[6] = 1; ver[6] = 1; //down left hor[7] = -1; ver[7] = 1; }//end constructor public void displayBoard () { //displays the board for (int row = 0; row &lt; board.length; row++) { for (int col = 0; col &lt; board[row].length; col++) { if (board[row][col] == -1) { System.out.printf("|%-2s|","*"); } else { System.out.printf("|%-2d|",board[row][col]); } if (board[row][col] == 0 || board[row][col] == -1) { ++eliminatedSquares; } }//end inner for System.out.println(); }//end for }//end displayBoard public boolean possibleMove (int move, int row, int col) { //tests whether a move is valid if (move &lt; 0 || move &gt; 7) { return false; }//end if else if (row + ver[move] &lt; 0|| row + ver[move] &gt; 7) { return false; }//end else if else if (col + hor[move] &lt; 0|| col + hor[move] &gt; 7) { return false; }//end else if else{ return true; }//end else }//end possibleMove public void placeQueen (int row, int col) { //eliminates the squares attacked by the current square of the queen board[row][col] = -1; ++eliminatedSquares; //try the eight possible moves for (int move = 0; move &lt; SIZE; move++) { int r = row; int c = col; while (possibleMove(move, r, c)) { r += ver[move]; c += hor[move]; if (board[r][c] != -1 &amp;&amp; board[r][c] &gt; 0) { board[r][c] = 0; decreaseAccessibilty(r, c); ++eliminatedSquares; } }//end while }//end for }//placeQueen public boolean testSquare (int row, int col) { if (board[row][col] &gt; 0) { return true; } else { return false; } } public void decreaseAccessibilty (int row, int col) { for (int move = 0; move &lt; SIZE; move++) { int r = row; int c = col; while (possibleMove(move, r, c)) { r += ver[move]; c += hor[move]; if (board[r][c] &gt; 0) { board[r][c]--; }//end if }//end while } }//end decrease accessibility public int getAccessibility (int row, int col) { //returns the accessibility number of a square return board[row][col]; } public int getEliminatedSquares () { return eliminatedSquares; } public int getRemainingSquares () { remainingSquares = 64 - eliminatedSquares; return remainingSquares; } }//end Queen public class QueenTest { private static int lowest; public static void main(String[] args) { Queen q = new Queen(); int nextRow = 0; int nextCol = 0; lowest = q.getAccessibility(nextRow, nextCol); int remaining = q.getRemainingSquares(); while (remaining != 0) { for (int row = 0; row &lt; 8; row++) { for (int col = 0; col &lt; 8; col++) { if (q.testSquare(row, col)) { lowest = q.getAccessibility(row, col); nextRow = row; nextCol = col; col = 8; row = 8; } } } for (int row = 0; row &lt; 8; row++) { for (int col = 0; col &lt; 8; col++) { if (q.getAccessibility(row, col) &gt; 0 &amp;&amp; q.getAccessibility(row, col) &lt;= lowest) { lowest = q.getAccessibility(row, col); nextRow = row; nextCol = col; } } } q.placeQueen(nextRow, nextCol); remaining = q.getRemainingSquares(); System.out.printf("queen placed at %d, %d\n", nextRow, nextCol); } q.displayBoard(); }} </code></pre>
[]
[ { "body": "<blockquote>\n <p>I think I did it and here's my code, please check if there are an errors or better ways to do things.</p>\n</blockquote>\n\n<p>Do not get it wrong, but to ask it in a direct way: Did you try to run the code? You could see directly that the proposed solution is not a solution. There are only 7 queens.</p>\n\n<p>Which shows the problem with the heuristic: It can help to find the next good move, but it could also fail and lead to a dead end.</p>\n\n<p>I do not think that it is a good approach to make comments about the style for the non working solution. First, you should get a working solution, probably with a backtracking approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T15:13:25.287", "Id": "20990", "ParentId": "20957", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T13:09:38.533", "Id": "20957", "Score": "1", "Tags": [ "java", "chess" ], "Title": "Eight Queens Heuristic" }
20957
<p>I am developing game portal content management system using java and j2ee technology. However i am stuck in my design implementation.</p> <p>Here is the scenario:</p> <p>Each Game object has attributes like id, name, developer, price, platformType, platformName and so on...</p> <p>However the release date may be different for each platform - PC, Mobile, Console and so on. Of course it is the same with the price.</p> <p>The other problem is that for example if the game is for PC platform it has requirements like RAM, Video card and so on. So I decided to make another class for the platformType.</p> <p>Do you think that the following design is good?</p> <p><strong>Here is the main Game object class:</strong></p> <pre><code>public class Game { private long systemId; private String name; private String developer; private Date registerDate; private ArrayList&lt;GamePlatform&gt; gamePlatforms; private GameScore gameScore; private GameRank gameRank; private ArrayList&lt;String&gt; genre; } </code></pre> <p><strong>Here is the GamePlatform class and its subclasses</strong></p> <pre><code>public abstract class GamePlatform { private Date releaseDate; private int price; private String name; private PlatformType platformType; public GamePlatform(Date releaseDate, int price, String name, PlatformType platformType) { this.releaseDate = releaseDate; this.price = price; this.name = name; this.platformType = platformType; } public abstract PlatformType getType(); } </code></pre> <p><strong>child class 1</strong></p> <pre><code>public class ConsolePlatform extends GamePlatform { public ConsolePlatform(Date releaseDate, int price, String name, PlatformType platformType) { super(releaseDate, price, name, platformType); } @Override public PlatformType getType() { return PlatformType.CONSOLE; } } </code></pre> <p><strong>child class 2</strong></p> <pre><code>public class MobilePlatform extends GamePlatform { public MobilePlatform(Date releaseDate, int price, String name, PlatformType platformType) { super(releaseDate, price, name, platformType); } @Override public PlatformType getType() { return PlatformType.MOBILE; } </code></pre> <p><strong>child class 3</strong></p> <pre><code>public class PCPlatform extends GamePlatform { private PCRequirements pcRequirements; public PCPlatform(Date releaseDate, int price, String name, PlatformType platformType, PCRequirements pcRequirements) { super(releaseDate, price, name,platformType); this.pcRequirements = pcRequirements; } public PCRequirements getPcRequirements() { return pcRequirements; } public void setPcRequirements(PCRequirements pcRequirements) { this.pcRequirements = pcRequirements; } @Override public PlatformType getType() { return PlatformType.PC; } } </code></pre> <p><strong>And finally i have Enum class for the platform types. Here it is:</strong></p> <pre><code>public enum PlatformType { MOBILE { @Override public String toString(){ return "Mobile";} }, CONSOLE { @Override public String toString(){ return "Console";} }, PC { @Override public String toString(){ return "PC";} }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T22:20:23.257", "Id": "33720", "Score": "0", "body": "`gameScore` and `gameRank` probably belong in `GamePlatform`, as a specific port may be considered 'bad'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:27:26.133", "Id": "33763", "Score": "0", "body": "Actually the boss refused this. When a new preview is made for the game if the realase for some platform is not good it will be mentioned. Actually i have an object GameReview which is a different story for now." } ]
[ { "body": "<ol>\n<li><p><code>ArrayList&lt;...&gt;</code> reference types should be simply <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>List&lt;GamePlatform&gt; gamePlatforms;\n</code></pre></li>\n<li><p>I'd consider using <code>BigDecimal</code> instead of <code>int price</code>. It can store numbers like <code>$1.99</code>.</p></li>\n<li><p>I'd rename <code>PCPlatform</code> to <code>PcPlatform</code>. From <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em>: </p>\n\n<blockquote>\n <p>While uppercase may be more common, \n a strong argument can made in favor of capitalizing only the first \n letter: even if multiple acronyms occur back-to-back, you can still \n tell where one word starts and the next word ends. \n Which class name would you rather see, HTTPURL or HttpUrl?</p>\n</blockquote></li>\n<li><p>The <code>PlatformType</code> enum seems as a duplication here and if I'm right it's purpose is to use it in switch-case statements. Consider polymorphism here. I'd put a <code>public abstract String getPlatformName()</code> method in the <code>GamePlatform</code> class and remove <code>PlatformType</code> completely. Two might be useful reading:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional with Polymorphism</a></li>\n</ul></li>\n<li><p>Constructor parameters should be validated. Does it make sense to create a <code>GamePlatform</code> with <code>null</code> or empty string <code>name</code>? If not, check it and throw a <code>NullPointerException</code> or an <code>IllegalArgumentException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:40:42.613", "Id": "33588", "Score": "0", "body": "If i completelety remove the PlarformType i will have to use the instanceof operator to get the type of the class. Do you think it is better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T20:44:52.977", "Id": "33593", "Score": "0", "body": "@JoroSeksa: `instanceof` is very similar to switch-case. Try to replace both with polymorphism. (Feel free to post a new question with that code.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T16:40:04.663", "Id": "20959", "ParentId": "20958", "Score": "2" } }, { "body": "<p>First read palascint item 4.</p>\n\n<p>If you want to continue using the enum, you should consider to restructure it in the following way. Beside the fact that it is easier to read, is is also easier and less error prone to add new enum values. Furthermore you could easily add an icon, an abbreviation or any other field for your platform.</p>\n\n<pre><code>public enum PlatformType {\n MOBILE(\"Mobile\"), CONSOLE(\"Console\"), PC(\"PC\");\n\n private String label;\n\n PlatformType(String label) {\n this.label = label;\n }\n\n public String toString() {\n return label;\n }\n}\n</code></pre>\n\n<p>In case you want to add more fields, you shouldn't use the <code>toString()</code> but a separate method. See <em>(Effective Java, Second Edition, Item 10)</em> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:19:35.487", "Id": "20960", "ParentId": "20958", "Score": "1" } }, { "body": "<p>Maybe you could move <code>private PCRequirements pcRequirements;</code> to <code>GamePlatform</code> and change it to <code>List&lt;Requirement&gt; requirements</code>. So you don't need to downcast to <code>PCPlatform</code>.</p>\n\n<p>Requirements for Console: Broadband-INet, ...</p>\n\n<p>Requirements for Mobile: Version OS/Browser/JS, ...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T19:26:41.460", "Id": "33591", "Score": "0", "body": "This seems good answer. Do i have to make the Requirements class abstract so i have to subclass with PcRequirements, ConsoleRequirements and MobileRequirements because each one accepts different parameters, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:34:07.600", "Id": "33683", "Score": "0", "body": "it depends. try a simple interface `Requirement`. So you can use the implementation `OSRequirement` for PC and Mobile." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T19:14:57.817", "Id": "20963", "ParentId": "20958", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T16:03:48.520", "Id": "20958", "Score": "1", "Tags": [ "java", "design-patterns" ], "Title": "Do you think this design pattern is good for game portal content management system" }
20958
<p>My task was to build a multi-thread file server and a client that can upload or download a named file over sockets. It is assumed that the client will finish after its operation and there is no need to supply a file list from the server (although I plan to add that). There is no error check if the client enters a file name that does not exist on the server.</p> <p>I think that the basic protocol I've set up is ugly at best and would like opinions on a better way to approach this. </p> <p>I'm quite sure this is barely doing the job, so criticism is welcomed.</p> <p>Flow:</p> <ul> <li>Start Server</li> <li>Start Client, connection made if possible.</li> <li>Client then chooses whether to upload or download a file.</li> <li>Server receives this initial message and takes appropriate action.</li> </ul> <p><strong><code>FileServer</code></strong></p> <pre><code>public class FileServer { private static ServerSocket serverSocket; private static Socket clientSocket = null; public static void main(String[] args) throws IOException { try { serverSocket = new ServerSocket(4444); System.out.println("Server started."); } catch (Exception e) { System.err.println("Port already in use."); System.exit(1); } while (true) { try { clientSocket = serverSocket.accept(); System.out.println("Accepted connection : " + clientSocket); Thread t = new Thread(new CLIENTConnection(clientSocket)); t.start(); } catch (Exception e) { System.err.println("Error in connection attempt."); } } } } </code></pre> <p><strong><code>CLIENTConnection</code></strong></p> <pre><code>public class CLIENTConnection implements Runnable { private Socket clientSocket; private BufferedReader in = null; public CLIENTConnection(Socket client) { this.clientSocket = client; } @Override public void run() { try { in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String clientSelection; while ((clientSelection = in.readLine()) != null) { switch (clientSelection) { case "1": receiveFile(); break; case "2": String outGoingFileName; while ((outGoingFileName = in.readLine()) != null) { sendFile(outGoingFileName); } break; default: System.out.println("Incorrect command received."); break; } in.close(); break; } } catch (IOException ex) { Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); } } public void receiveFile() { try { int bytesRead; DataInputStream clientData = new DataInputStream(clientSocket.getInputStream()); String fileName = clientData.readUTF(); OutputStream output = new FileOutputStream(("received_from_client_" + fileName)); long size = clientData.readLong(); byte[] buffer = new byte[1024]; while (size &gt; 0 &amp;&amp; (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) { output.write(buffer, 0, bytesRead); size -= bytesRead; } output.close(); clientData.close(); System.out.println("File "+fileName+" received from client."); } catch (IOException ex) { System.err.println("Client error. Connection closed."); } } public void sendFile(String fileName) { try { //handle file read File myFile = new File(fileName); byte[] mybytearray = new byte[(int) myFile.length()]; FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); //bis.read(mybytearray, 0, mybytearray.length); DataInputStream dis = new DataInputStream(bis); dis.readFully(mybytearray, 0, mybytearray.length); //handle file send over socket OutputStream os = clientSocket.getOutputStream(); //Sending file name and file size to the server DataOutputStream dos = new DataOutputStream(os); dos.writeUTF(myFile.getName()); dos.writeLong(mybytearray.length); dos.write(mybytearray, 0, mybytearray.length); dos.flush(); System.out.println("File "+fileName+" sent to client."); } catch (Exception e) { System.err.println("File does not exist!"); } } } </code></pre> <p><strong><code>FileClient</code></strong></p> <pre><code>public class FileClient { private static Socket sock; private static String fileName; private static BufferedReader stdin; private static PrintStream os; public static void main(String[] args) throws IOException { try { sock = new Socket("localhost", 4444); stdin = new BufferedReader(new InputStreamReader(System.in)); } catch (Exception e) { System.err.println("Cannot connect to the server, try again later."); System.exit(1); } os = new PrintStream(sock.getOutputStream()); try { switch (Integer.parseInt(selectAction())) { case 1: os.println("1"); sendFile(); break; case 2: os.println("2"); System.err.print("Enter file name: "); fileName = stdin.readLine(); os.println(fileName); receiveFile(fileName); break; } } catch (Exception e) { System.err.println("not valid input"); } sock.close(); } public static String selectAction() throws IOException { System.out.println("1. Send file."); System.out.println("2. Recieve file."); System.out.print("\nMake selection: "); return stdin.readLine(); } public static void sendFile() { try { System.err.print("Enter file name: "); fileName = stdin.readLine(); File myFile = new File(fileName); byte[] mybytearray = new byte[(int) myFile.length()]; FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); //bis.read(mybytearray, 0, mybytearray.length); DataInputStream dis = new DataInputStream(bis); dis.readFully(mybytearray, 0, mybytearray.length); OutputStream os = sock.getOutputStream(); //Sending file name and file size to the server DataOutputStream dos = new DataOutputStream(os); dos.writeUTF(myFile.getName()); dos.writeLong(mybytearray.length); dos.write(mybytearray, 0, mybytearray.length); dos.flush(); System.out.println("File "+fileName+" sent to Server."); } catch (Exception e) { System.err.println("File does not exist!"); } } public static void receiveFile(String fileName) { try { int bytesRead; InputStream in = sock.getInputStream(); DataInputStream clientData = new DataInputStream(in); fileName = clientData.readUTF(); OutputStream output = new FileOutputStream(("received_from_server_" + fileName)); long size = clientData.readLong(); byte[] buffer = new byte[1024]; while (size &gt; 0 &amp;&amp; (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) { output.write(buffer, 0, bytesRead); size -= bytesRead; } output.close(); in.close(); System.out.println("File "+fileName+" received from Server."); } catch (IOException ex) { Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); } } } </code></pre>
[]
[ { "body": "<p>The basic client / server code looks pretty good.</p>\n\n<p>If you want clearer vision for \"something\" in java, you need to start defining the boundary of that \"something\". In Java the ideal choice is the Class.</p>\n\n<p>Start by refactoring your code to separate what you consider the \"Protocol\" into a \"Protocol\" class. Later on, if you find that you want to support more than one \"Protocol\" write a second \"ProtocolTwo\" class, rename the \"Protocol\" class to something like \"ProtocolOne\" and make a common shared interface between the two called \"Protocol\".</p>\n\n<p>My imaginings for a \"Protocol\" class that would work with your code:</p>\n\n<pre><code>Protocol protocol = new Protocol();\nAction action = protocol.readAction(sock.getOutputStream());\naction.perform();\n</code></pre>\n\n<p>Of course, it is homework, so you'll get the joy of putting all the important bits into the right places. Good luck, and post back as you get closer to the goal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T18:50:42.863", "Id": "35664", "Score": "0", "body": "cheers. With exams looming it is time to refocus my attention. I'll revisit the code after. Thanks for the tips." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T19:07:53.570", "Id": "35665", "Score": "0", "body": "@chrisloughnane Fully understand, and good luck (though luck has nothing to do with it) on your exams!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T17:05:57.840", "Id": "23117", "ParentId": "20961", "Score": "3" } } ]
{ "AcceptedAnswerId": "23117", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:36:56.010", "Id": "20961", "Score": "10", "Tags": [ "java", "multithreading", "homework", "socket", "network-file-transfer" ], "Title": "Java multi-thread file server and client" }
20961
<p>Am supposed to capture user input as an integer, convert to a binary, reverse the binary equivalent and convert it to an integer.Am getting the right output but someone says the solution is wrong. Where is the problem?</p> <pre><code>x = 0 while True: try: x = int(raw_input('input a decimal number \t')) if x in xrange(1,1000000001): y = bin(x) rev = y[2:] print("the reverse binary soln for the above is %d") %(int('0b'+rev[::-1],2)) break except ValueError: print("Please input an integer, that's not an integer") continue </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:28:35.517", "Id": "33596", "Score": "2", "body": "If you are asking us to find an error in your code, then I'm afraid your question if off topic on Code Review. This is site is for reviewing code that you think is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:55:49.733", "Id": "33597", "Score": "1", "body": "I think ist's correct since it gives the required output, I just want to know if there's something I can do to make it work better" } ]
[ { "body": "<pre><code>x = 0\n</code></pre>\n\n<p>There is no point in doing this. You just replace it anyways</p>\n\n<pre><code>while True:\n\n try:\n x = int(raw_input('input a decimal number \\t'))\n\n\n if x in xrange(1,1000000001):\n</code></pre>\n\n<p>Probably better to use <code>if 1 &lt;= x &lt;= 100000000001:</code> although I'm really not sure why you are doing this check. Also, you should probably explain to the user that you've reject the number.</p>\n\n<pre><code> y = bin(x)\n\n rev = y[2:]\n</code></pre>\n\n<p>I'd use <code>reversed = bin(x)[:1::-1]</code> rather then splitting it out across the tree lines.</p>\n\n<pre><code> print(\"the reverse binary soln for the above is %d\") %(int('0b'+rev[::-1],2)) \n</code></pre>\n\n<p>I'd convert the number before the print to seperate output from the actual math.</p>\n\n<pre><code> break\n\n except ValueError:\n print(\"Please input an integer, that's not an integer\")\n continue\n</code></pre>\n\n<p>This continue does nothing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T23:45:58.330", "Id": "20968", "ParentId": "20965", "Score": "5" } } ]
{ "AcceptedAnswerId": "20968", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:48:57.497", "Id": "20965", "Score": "3", "Tags": [ "python" ], "Title": "Python Reverse the binary equivalent of input and output the integer equivalent of the reverse binary" }
20965
<p>I am trying to set a <code>OnClickListener</code> to a image in a loop. If the params platform is "android" then use market app, instead of default browswer. Is there a better solution to my exception handling or eliminatingsome of the <code>if-else</code> ?</p> <pre><code>private void setupListener(ImageView image, final String platform, final String urlLink) { image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (platform.equalsIgnoreCase(PLATFORM_ANDROID)) { // open with market app String packageName = extractPackageName(urlLink); if (packageName != null) { try { Intent market = new Intent(Intent.ACTION_VIEW); market.setData(Uri.parse("market://details?id=" + packageName)); activity.startActivity(market); } catch (Exception e) { e.printStackTrace(); startInBroswer(urlLink); } } else { startInBroswer(urlLink); } } else { // open with default broswer. startInBroswer(urlLink); } } }); } private void startInBroswer(String urlLink) { Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(urlLink)); activity.startActivity(browser); } </code></pre>
[]
[ { "body": "<p>Here is another version with <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clauses</a>:</p>\n\n<pre><code>private void setupListener(final ImageView image, final String platform, \n final String urlLink) {\n image.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (!platform.equalsIgnoreCase(PLATFORM_ANDROID)) {\n startInBroswer();\n return;\n }\n\n final String packageName = extractPackageName(urlLink);\n if (packageName == null) {\n startInBroswer();\n return;\n }\n\n try {\n final Intent market = new Intent(Intent.ACTION_VIEW);\n market.setData(Uri.parse(\"market://details?id=\" + packageName));\n activity.startActivity(market);\n } catch (final Exception e) {\n // TODO: log the exception\n startInBroswer();\n }\n }\n\n private void startInBroswer() {\n final Intent browser = new Intent(Intent.ACTION_VIEW, \n Uri.parse(urlLink));\n activity.startActivity(browser);\n }\n });\n}\n</code></pre>\n\n<p>Two things to notice:</p>\n\n<ol>\n<li><p>I've removed the <code>urlLink</code> parameter of the <code>startInBroswer</code> method.</p></li>\n<li><p>It is a <a href=\"https://stackoverflow.com/q/3855187/843804\">bad idea to use <code>printStackTrace()</code> in Android exceptions</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T06:11:23.943", "Id": "20972", "ParentId": "20966", "Score": "2" } }, { "body": "<p>Define field listener and assign it as OnClick handler.\nYou'll have only one object. </p>\n\n<pre><code>View.OnClickListener mListener\n\n@Override\npublic void onCreate(Bundle savedInstanceState) {\n\n mListener = new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (platform.equalsIgnoreCase(PLATFORM_ANDROID)) {\n // open with market app\n String packageName = extractPackageName(urlLink);\n if (packageName != null) {\n try {\n Intent market = new Intent(Intent.ACTION_VIEW);\n market.setData(Uri.parse(\"market://details?id=\"\n + packageName));\n activity.startActivity(market);\n } catch (Exception e) {\n e.printStackTrace();\n startInBroswer(urlLink);\n }\n } else {\n startInBroswer(urlLink);\n }\n\n } else {\n // open with default broswer.\n startInBroswer(urlLink);\n }\n\n }\n }\n super.onCreate(savedInstanceState);\n}\n\nprivate void setupListener(ImageView image, final String platform,\n final String urlLink) {\n image.setOnClickListener(mListener);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:34:44.690", "Id": "33868", "Score": "0", "body": "Nice tip. Thanks but it doesn't solve the problem with the clauses which I am more concerned about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T15:21:29.717", "Id": "20991", "ParentId": "20966", "Score": "2" } } ]
{ "AcceptedAnswerId": "20972", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:52:00.857", "Id": "20966", "Score": "1", "Tags": [ "java", "android" ], "Title": "Setting a OnClickListener in a loop" }
20966
<p>My code converts repeating decimals to fractions. It works but I am interested in feedback on how I could improve and/or simplify it?</p> <p>jsFiddle: <a href="http://jsfiddle.net/tfgTu/" rel="nofollow">http://jsfiddle.net/tfgTu/</a></p> <pre><code>&lt;script&gt; // Repeating decimal // 21.83(35745857) var decimal = 21.8335745857 // Total length of the decimal var decimalLength = 10; // Length of the decimal before the repeating part var decimalBeforeRepeatLength = 2; // 10 to the total length of the decimal var power1 = Math.pow(10, decimalLength); // 10 to the length of the decimal before the repeating part var power2 = Math.pow(10, decimalBeforeRepeatLength); var finalPower = power1 - power2; var decimal1 = decimal * power1; var decimal2 = parseInt(decimal * power2); var finalDecimal = decimal1 - decimal2; var output = simplifyFraction(0, finalDecimal, finalPower); document.write(output[1] + " / " + output[2]); // Finds the greatest common divisor of 2 non-zero integers // a = integer 1 // b = integer 2 function greatestCommonDivisor(a, b) { if (b === 0) { return a; } return greatestCommonDivisor(b, (a % b)); } // Simplifies all forms of fractions // Does not change form of fraction // i = number // n = numerator // d = denominator function simplifyFraction(i, n, d) { var gcd = greatestCommonDivisor(n, d); if (Math.abs(i) &gt; 0 &amp;&amp; n &gt;= d) { // If mixed number AND improper fraction, assume the user wants a simplified mixed number if (i &lt; 0) { n *= -1; } var temp = improperFractionToMixedNumber(n, d); return [temp[0] + i, temp[1] / gcd, temp[2] / gcd]; } return [i, n / gcd, d / gcd]; } &lt;/script&gt; </code></pre>
[]
[ { "body": "<ol>\n<li>While the general code quality is good, the contract should be formalized by adding <code>\"use strict\";</code></li>\n<li>Even though <code>var</code> is used, everything is still in the global namespace, thereby polluting it and risking name collisions. Moving things into a namespace also means some other parts of the code can/should be re-arranged.</li>\n<li>There's ideally no need to manually specify both the number, and how many digits there are after the <code>.</code>.</li>\n<li>I honestly fail to understand the problem the function solves, so it's unclear to me if <code>var decimalBeforeRepeatLength = 2</code> can also be derived automatically from the input, or if it needs to be a separate input parameter.</li>\n<li>There's no <code>radix</code> parameter to <code>parseInt()</code>. Without it, the \"correct\" behaviour is not guaranteed, so you really should specify it. See <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow\">Mozilla's documentation</a> for details.</li>\n<li>It's unclear to me why <code>parseInt()</code> is used, why not just <code>Math.floor()</code>?</li>\n<li>Separating the output from the functionality would be a nice improvement.</li>\n<li><code>improperFractionToMixedNumber</code> isn't included in the actual code you posted, so I can't really comment on that, nor test that the code gets the same results before and after my changes.</li>\n<li>Since <code>i</code> is hardcoded to 0, most of the original <code>simplifyFraction()</code> can actually be removed all together, but I'm guessing making <code>i</code> a parameter would be the solution instead.</li>\n<li>Why does <code>simplifyFraction()</code> return <code>i</code> when it's an unmodified input parameter?</li>\n<li>With some of the changes I've done, a few variables should probably have their names changed. I'll leave that as an exercise to the reader.</li>\n</ol>\n\n<p>Code below incorporating the above changes. I've removed all original comments and added my own, to make it easier to spot the differences.</p>\n\n<pre><code>// Isolate variables and functions from the global scope.\n// The namespace should of course not actually be named 'namespace'.\nvar simplifyFraction = function(decimal, decimalBeforeRepeatLength) {\n // Improve the code quality with strict mode.\n \"use strict\";\n\n // Figure out decimal length automatically.\n var indexOfDot = decimal.toString().indexOf('.');\n var decimalLength = decimal.toString().length - indexOfDot - 1;\n\n var power1 = Math.pow(10, decimalLength);\n var power2 = Math.pow(10, decimalBeforeRepeatLength);\n var finalPower = power1 - power2;\n var decimal1 = decimal * power1;\n // Explicitly set a radix of '10' to avoid unpredicatable results.\n var decimal2 = parseInt(decimal * power2, 10);\n // Preferred option.\n decimal2 = Math.floor(decimal * power2);\n var finalDecimal = decimal1 - decimal2;\n var i = 0;\n\n var greatestCommonDivisor = function(a, b) {\n if (b === 0) {\n return a;\n }\n\n return greatestCommonDivisor(b, (a % b));\n };\n\n var gcd = greatestCommonDivisor(finalDecimal, finalPower);\n\n // Since simplifyFraction() is now what we use for namespacing, it's not\n // kept as a function in here.\n if (Math.abs(i) &gt; 0 &amp;&amp; finalDecimal &gt;= finalPower) {\n if (i &lt; 0) {\n finalDecimal *= -1; \n }\n\n var temp = improperFractionToMixedNumber(finalDecimal, finalPower);\n\n return [temp[0] + i, temp[1] / gcd, temp[2] / gcd];\n }\n\n return [i, finalDecimal / gcd, finalPower / gcd];\n};\n\n// The function no longer forces a certain outout. We get back the answer and treat it anyway we want.\n//\nvar answer = simplifyFraction(21.8335745857, 2);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T12:20:38.740", "Id": "23904", "ParentId": "20969", "Score": "2" } }, { "body": "<p>In addition to @Letharion's response, I would suggest copying the function <code>Ratio.getRepeatProps()</code> to get the value for <code>decimalBeforeRepeatLength</code>.</p>\n\n<p>Ratio.getRepeatProps() - <a href=\"https://github.com/LarryBattle/Ratio.js/blob/master/lib/Ratio-0.4.0.js#L311\" rel=\"nofollow\">https://github.com/LarryBattle/Ratio.js/blob/master/lib/Ratio-0.4.0.js#L311</a></p>\n\n<p>Example:</p>\n\n<pre><code>// Note that the repeating decimal must have the pattern occur at least twice for this to work.\n// The pattern in this case is `35745857`\nvar parts = Ratio.getRepeatProps(\"21.833574585735745857\");\n// parts == [\"21\", \"83\", \"35745857\"]\n// index 1 contains the numbers before the repeating pattern.\nvar decimalBeforeRepeatLength = (parts.length) ? parts[1].length : 0;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-30T16:35:54.437", "Id": "29184", "ParentId": "20969", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T00:34:02.817", "Id": "20969", "Score": "4", "Tags": [ "javascript" ], "Title": "Convert Repeating Decimal to Fraction" }
20969
<p>The following is an implementation of Guava's <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Equivalence.html">Equivalence</a> for Jackson's <code>JsonNode</code> for the needs of JSON Schema: in certain situations, all JSON numbers need to be compared mathematically (ie, <code>1.0</code> is equal to <code>1</code>) but <code>JsonNode</code> (accurately) considers them non equal.</p> <p>So, instead of extending <code>JsonNode</code>, I use this code, which works:</p> <pre><code>public final class JsonNodeEquivalence extends Equivalence&lt;JsonNode&gt; { // snip @Override protected boolean doEquivalent(final JsonNode a, final JsonNode b) { /* * If both are numbers, delegate to appropriate method */ if (a.isNumber() &amp;&amp; b.isNumber()) return numEquals(a, b); final NodeType typeA = NodeType.getNodeType(a); final NodeType typeB = NodeType.getNodeType(b); /* * If they are of different types, no dice */ if (typeA != typeB) return false; /* * For all other primitive types than numbers, trust JsonNode */ if (!a.isContainerNode()) return a.equals(b); /* * OK, so they are containers (either both arrays or objects due to the * test on types above). They are obviously not equals if they do not * have the same number of elements/members. */ if (a.size() != b.size()) return false; /* * Delegate to the appropriate method according to their type. */ return typeA == NodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b); } @Override protected int doHash(final JsonNode t) { /* * If this is a numeric node, we want the same hashcode for the same * mathematical values. Go with double, its range is good enough for * 99+% of use cases. */ if (t.isNumber()) return Double.valueOf(t.doubleValue()).hashCode(); /* * If this is a primitive type (other than numbers, handled above), * delegate to JsonNode. */ if (!t.isContainerNode()) return t.hashCode(); /* * The following hash calculations work, yes, but they are poor at best. * And probably slow, too. * * TODO: try and figure out those hash classes from Guava */ int ret = 0; /* * If the container is empty, just return */ if (t.size() == 0) return ret; /* * Array */ if (t.isArray()) { for (final JsonNode element : t) ret = 31 * ret + doHash(element); return ret; } /* * Not an array? An object. */ final Iterator&lt;Map.Entry&lt;String, JsonNode&gt;&gt; iterator = t.fields(); Map.Entry&lt;String, JsonNode&gt; entry; while (iterator.hasNext()) { entry = iterator.next(); ret = 31 * ret + (entry.getKey().hashCode() ^ doHash(entry.getValue())); } return ret; } private static boolean numEquals(final JsonNode a, final JsonNode b) { /* * If both numbers are integers, delegate to JsonNode. */ if (a.isIntegralNumber() &amp;&amp; b.isIntegralNumber()) return a.equals(b); /* * Otherwise, compare decimal values. */ return a.decimalValue().compareTo(b.decimalValue()) == 0; } private boolean arrayEquals(final JsonNode a, final JsonNode b) { /* * We are guaranteed here that arrays are the same size. */ final int size = a.size(); for (int i = 0; i &lt; size; i++) if (!doEquivalent(a.get(i), b.get(i))) return false; return true; } private boolean objectEquals(final JsonNode a, final JsonNode b) { /* * Grab the key set from the first node */ final Set&lt;String&gt; keys = Sets.newHashSet(a.fieldNames()); /* * Grab the key set from the second node, and see if both sets are the * same. If not, objects are not equal, no need to check for children. */ final Set&lt;String&gt; set = Sets.newHashSet(b.fieldNames()); if (!set.equals(keys)) return false; /* * Test each member individually. */ for (final String key: keys) if (!doEquivalent(a.get(key), b.get(key))) return false; return true; } } </code></pre> <p>However, I am dissatisfied with <code>doHash()</code>'s calculation for JSON arrays and objects. I cannot judge of its distribution quality, but most of all, since this can be called quite often in some situations, I'd like to make it faster.</p> <p>As explained above, the requirement is that all numeric nodes will equal mathematical values have the same hash code.</p> <p>What do you propose?</p> <p><strong>EDIT</strong>: since then I have figured out how to use Guava's hashing functions, so I attempted to use them and compare performance. To use it, you need to create a <code>Funnel</code> for your object class and inject it into a <code>Hasher</code> issued from a <code>HashFunction</code>.</p> <p>So I wrote the funnel and tried and used a <code>.goodFastHash(32)</code> (since the result is ultimately a hash code). But it was three times slower than the already existing code. To do better, I guess I'd have to calculate the hash while parsing the JSON itself, but it kind of defeats the purpose of using an external JSON library to begin with :/</p>
[]
[ { "body": "<p>Working through your code i Have found very few things to criticise....</p>\n\n<ol>\n<li>I like the way you are using <code>final</code>.</li>\n<li>I like the general layout and structure</li>\n<li>using compareTo on the BigDecimals is the right thing to do.</li>\n</ol>\n\n<p>If I have one complaint about your 'style', it is that your comments are too verbose...</p>\n\n<p>As for your question about the hashCode of Collection-like data members....</p>\n\n<p>I have inspected the source code for both <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.jackson/jackson-mapper-asl/1.9.5/org/codehaus/jackson/node/ObjectNode.java#ObjectNode.hashCode%28%29\" rel=\"nofollow\">ObjectNode</a> and <a href=\"http://grepcode.com/file/repo1.maven.org/maven2/org.codehaus.jackson/jackson-mapper-asl/1.9.5/org/codehaus/jackson/node/ArrayNode.java#ArrayNode.hashCode%28%29\" rel=\"nofollow\">ArrayNode</a>.</p>\n\n<p>In each case they implement reasonable hashes given some constraints.</p>\n\n<p>You need to answer three questions:</p>\n\n<ol>\n<li>do you know these are static data members (you are not changing their internal values)?</li>\n<li>The arrays may contain numbers just so long as the result for the array is consistent?</li>\n<li>do you trust the array members to have reasonably-well distributed hash values?</li>\n</ol>\n\n<p>If you feel like you should implement your own hash, then consider the following:</p>\n\n<pre><code> // start the hash off with a value that's unique to the size.\n int ret = t.size();\n\n /*\n * If the container is empty, just return\n */\n if (ret == 0)\n return 1;\n\n /*\n * Array\n */\n if (t.isArray()) {\n // prime-number tricks like *31 are to ensure distributions.\n // we don't really care too much.... but we can shift easily...\n // 13 and 19 are prime numbers that add to 32 -- making a relatively\n // long loop-around time.\n // rotate the hash 19 bits, and XOR with the next element.\n for (final JsonNode element : t)\n ret = ((ret &gt;&gt;&gt; 13) | (ret &lt;&lt; 19)) ^ doHash(element);\n return ret;\n }\n\n /*\n * Not an array? An object.\n */\n final Iterator&lt;Map.Entry&lt;String, JsonNode&gt;&gt; iterator = t.fields();\n\n while (iterator.hasNext()) {\n final Map.Entry&lt;String, JsonNode&gt; entry = iterator.next();\n ret ^= entry.getKey().hashCode();\n ret = ((ret &gt;&gt;&gt; 13) | (ret &lt;&lt; 19)) ^ doHash(entry.getValue()));\n }\n\n return ret;\n</code></pre>\n\n<p>Messing with bitwise functions vs. <code>*31</code> is a JVM-dependant fix. I have had successes and failures with it....</p>\n\n<p>... to clarify what I mean here, I have one specific example in mind:</p>\n\n<p>consider the difference between <code>(ret * 31) ^ hash</code> and <code>((ret &lt;&lt; 5) - ret) ^ hash</code>. I have known the second one to be both significantly faster, and significantly slower.....</p>\n\n<p>Edit: Discussion about prime-number shifts:</p>\n\n<pre><code>public static void main(String[] args) {\n\n // sorted array of 1-bit integer values\n int[] bitsets = new int[32];\n for (int i = 0; i &lt; bitsets.length; i++) {\n bitsets[(i + 1) % 32] = 1 &lt;&lt; i;\n }\n\n int[] cnt = new int[32];\n int val = 1;\n for (int i = 0; i &lt; 1000; i++) {\n val = (val &gt;&gt;&gt; 13) | (val &lt;&lt; 19);\n int pos = Arrays.binarySearch(bitsets, val);\n cnt[pos]++;\n }\n System.out.println(\"Bit Distributions: \" + Arrays.toString(cnt));\n}\n</code></pre>\n\n<p>The above code results in:</p>\n\n<blockquote>\n<pre><code>Bit Distributions: [32, 31, 31, 31, 31, 31, 32, 32, 31, 31, 31, 31, 31, 32, 31, 31, 31, 31, 31, 32, 32, 31, 31, 31, 31, 32, 32, 31, 31, 31, 31, 31]\n</code></pre>\n</blockquote>\n\n<p>What this means, is that by shifting with relatively large primes, it takes a while for the same bit-pattern to repeat, and also, the coverage of the entire bit range is comprehensive. <a href=\"http://en.wikipedia.org/wiki/Periodical_cicadas\" rel=\"nofollow\">This is like the Cicada 17-year cycles and 13-year cycles</a>, etc. making sure that no two species of cicada are (often) emerging in the same years.</p>\n\n<p>It means that the each bit in each input hash is used to affect every other bit in subsequent hash values as much as possible (and it affects itself as little as possible because an XOR with yourself is always 0).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T18:44:05.910", "Id": "70757", "Score": "0", "body": "I don't understand the comment 'making a relative long loop-around time' in your code above?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T20:59:40.157", "Id": "70778", "Score": "0", "body": "@fge it's an attempt to sound like I know hashing functions really well.... ;-) Actually, all it means is that any 1 bit will in any one hash, from any one element, will not affect the same bit's worth of data very often. Added some code to show you...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T23:30:06.013", "Id": "70796", "Score": "0", "body": "Your attempt showed me that you know a great deal more than me ;) I'll try and compare my and your approach using Caliper... In any event, I bow to you for the research and sample code! +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-14T17:10:04.870", "Id": "164595", "Score": "0", "body": "IIUC, `val = (val >>> 13) | (val << 19)` just performs a right cyclic shift of val by 13. The 19 is just there because 19=32-13, and it being prime doesn't make the choice of 13 better - any odd value would be equivalent from a periodicity perspective. The analogy to coprime cicada lifecycles is not accurate." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T05:41:31.027", "Id": "36756", "ParentId": "20970", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T04:10:36.917", "Id": "20970", "Score": "8", "Tags": [ "java" ], "Title": "A better hash function for an Equivalence?" }
20970
<p>This code for the Raspberry Pi board waits for serial input then plays an arrow with a sound and message. I'd like any constructive comments or suggestions.</p> <pre><code>#include &lt;termios.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;fcntl.h&gt; #include &lt;sys/signal.h&gt; #include &lt;sys/types.h&gt; #include &lt;signal.h&gt; #include &lt;bits/siginfo.h&gt; #include &lt;iostream&gt; #include &lt;cv.h&gt; #include &lt;highgui.h&gt; #include &lt;stdlib.h&gt; #include &lt;queue&gt; #define BAUDRATE B9600 #define MODEMDEVICE "/dev/ttyUSB0" #define _POSIX_SOURCE 1 /* POSIX compliant source */ #define FALSE 0 #define TRUE 1 volatile int STOP=FALSE; void signal_handler_IO (int status); /* definition of signal handler */ int wait_flag=TRUE; /* TRUE while no signal received */ int fd,c, res; struct termios oldtio,newtio; struct sigaction saio; /* definition of signal action */ char buf[255]; using namespace cv; using namespace std; #define w 400 //width #define l 400 //length #define mp 3 //multiplier - size of arrow #define ts 4 //time scale - time to show arrow //message void Arrow( Mat img, int i ); int CreateMessage( String tln, int i ); // (Teller number, Arrow 1 left 2 right 3 down) //images int showImages(int a); void loadImages(); int nImages = 8; IplImage *images[0]; typedef queue&lt;char*&gt; CHARQUEUE; //initilaize serial port void iSerial(){ fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd &lt;0) {perror(MODEMDEVICE); exit(-1); } saio.sa_handler = signal_handler_IO; saio.sa_flags=0; saio.sa_restorer = NULL; sigaction(SIGIO,&amp;saio,NULL); fcntl(fd, F_SETOWN, getpid()); fcntl(fd, F_SETFL, FASYNC); tcgetattr(fd,&amp;oldtio); /* save current port settings */ newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR | ICRNL; newtio.c_oflag = 0; newtio.c_lflag = ICANON; newtio.c_cc[VMIN]=1; newtio.c_cc[VTIME]=0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&amp;newtio); tcsetattr(fd,TCSANOW,&amp;oldtio); } int main() { CHARQUEUE q; loadImages(); iSerial(); while(1){ for (int i = 0; i &lt; nImages; ++i){ showImages(i); /* after receiving SIGIO, wait_flag = FALSE, input is available and can be read */ if (wait_flag==FALSE) { res = read(fd,buf,255); buf[res]=0; q.push(buf); printf(":%s:%d\n", buf, res); if (res==1) STOP=TRUE; /* stop loop if only a CR was input */ wait_flag = TRUE; /* wait for new input */ } while (!q.empty()) { CreateMessage( q.front(), 2 ); q.pop(); } } } } void signal_handler_IO (int status) { printf("received SIGIO signal.\n"); wait_flag = FALSE; } void loadImages() { images[0] = cvLoadImage("images/001.jpg"); images[1] = cvLoadImage("images/002.jpg"); images[2] = cvLoadImage("images/003.jpg"); images[3] = cvLoadImage("images/004.jpg"); images[4] = cvLoadImage("images/005.jpg"); images[5] = cvLoadImage("images/006.jpg"); images[6] = cvLoadImage("images/007.jpg"); images[7] = cvLoadImage("images/008.jpg"); images[8] = cvLoadImage("images/009.jpg"); } int showImages(int a){ cvNamedWindow("pic"); cvShowImage("pic",images[a]); cvMoveWindow("pic", 0, 0); cvWaitKey(2000); } int CreateMessage( String tln, int i ) { Mat arrow_image = Mat::zeros( w, l, CV_8UC3 ); putText(arrow_image, "Teller "+tln, cvPoint(100,30), FONT_HERSHEY_COMPLEX_SMALL, 1.8, cvScalar(200,200,250), 1, CV_AA); Arrow( arrow_image, i ); namedWindow("Drawing arrow"); system("aplay a_12.wav&amp;"); /*play sound*/ imshow("Drawing arrow", arrow_image); cvWaitKey(1000*ts); /*this is the delay */ destroyWindow("Drawing arrow"); } void Arrow( Mat img, int i ) { int lineType = 8; Point arrow_points[1][7]; if (i == 1) { //left arrow_points[0][0] = Point( 90*mp, 60*mp ); arrow_points[0][1] = Point( 90*mp, 40*mp ); arrow_points[0][2] = Point( 50*mp, 40*mp ); arrow_points[0][3] = Point( 50*mp, 30*mp ); arrow_points[0][4] = Point( 10*mp, 50*mp ); arrow_points[0][5] = Point( 50*mp, 70*mp ); arrow_points[0][6] = Point( 50*mp, 60*mp ); }; if (i == 2) { //right arrow_points[0][0] = Point( 20*mp, 60*mp ); arrow_points[0][1] = Point( 20*mp, 40*mp ); arrow_points[0][2] = Point( 60*mp, 40*mp ); arrow_points[0][3] = Point( 60*mp, 30*mp ); arrow_points[0][4] = Point( 100*mp, 50*mp ); arrow_points[0][5] = Point( 60*mp, 70*mp ); arrow_points[0][6] = Point( 60*mp, 60*mp ); }; if (i == 3) { //down arrow_points[0][0] = Point( 60*mp, 20*mp ); arrow_points[0][1] = Point( 40*mp, 20*mp ); arrow_points[0][2] = Point( 40*mp, 60*mp ); arrow_points[0][3] = Point( 30*mp, 60*mp ); arrow_points[0][4] = Point( 50*mp, 100*mp ); arrow_points[0][5] = Point( 70*mp, 60*mp ); arrow_points[0][6] = Point( 60*mp, 60*mp ); }; const Point* ppt[1] = { arrow_points[0] }; int npt[] = { 7 }; fillPoly( img, ppt, npt, 1, Scalar( 250, 0, 0 ), lineType ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T17:43:20.097", "Id": "33918", "Score": "1", "body": "You may get better trackaction if you add C as a language. Though you use one C++ class the code for review is basically C no real C++ features used so you may as well ask for comments from C coders." } ]
[ { "body": "<p>Nice. I am working on a similar project. In order to make your code more modular and object oriented, you can write a <code>Message</code> class and a <code>SerialPort</code> class. It makes it much easier to restructure your code when you want to change the behavior. e.g.</p>\n\n<pre><code>SerialPort sp(\"COM8\"); // or \"/dev/ttyUSB0\" for linux\nMessage msg(\"alskadflaskjfd\");\nMessage rx;\n\nsp.write(msg);\nsp.read(rx);\n</code></pre>\n\n<p>You might as well since your using some c++, modularity is always a good thing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:24:04.400", "Id": "21152", "ParentId": "20974", "Score": "1" } } ]
{ "AcceptedAnswerId": "21152", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T09:41:43.017", "Id": "20974", "Score": "4", "Tags": [ "c", "serial-port", "raspberry-pi" ], "Title": "Responding to serial input" }
20974
<p>My objective has been to build a custom dropdown like the one on Amazon's search scope selector. I do this by positioning a styleable element on top of a standard select list. I then use jQuery to keep the styleable element in sync with the select list. My code works fine, but I would love to learn how to do it cleaner. Currently, I do the syncing twice - on page load and on change. Is it possible to refactor my code using on()? (or similar).</p> <p><code>prev()</code> is the styleable element.</p> <pre><code>// Sync is performed on page load var $select = $('select'); $select.each(function(index, value) { var optionText = $(this).find('option:selected').text(); $(this).prev().text(optionText); }); // Sync is performed on change event $('select').change(function() { var optionText = $(this).find('option:selected').text(); $(this).prev().text(optionText); }); </code></pre>
[]
[ { "body": "<p>It's probably a bit too heavyweight for your task, but have you considered using <a href=\"http://knockoutjs.com/\" rel=\"nofollow\">knockoutJS</a> for it? It's a quite powerful MVVM javascript framework that uses the notion of <a href=\"http://knockoutjs.com/documentation/observables.html\" rel=\"nofollow\">Observables</a> to keep UI in sync with underlying data model.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T11:24:18.630", "Id": "20977", "ParentId": "20976", "Score": "0" } }, { "body": "<p>Instead of rewriting the code you can just trigger the change event after you bind it which will cause it to sync on page load</p>\n\n<pre><code>$('select').change(function() {\n var optionText = $(this).find('option:selected').text();\n $(this).prev().text(optionText);\n}).trigger('change'); // &lt;-- trigger change\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T15:09:40.023", "Id": "20989", "ParentId": "20976", "Score": "1" } } ]
{ "AcceptedAnswerId": "20989", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T10:50:11.353", "Id": "20976", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Maintain sync of select list" }
20976
<p>I was wondering if someone could take some time to look over my portfolio script and see let me know if it's secure enough to be uploaded live and connected to my database. My previous mySQL script was VERY insecure...</p> <p><strong>The Database Connection:</strong> <pre><code> public function __construct($server, $databaseName, $username, $password) { $this-&gt;server = $server; $this-&gt;databaseName = $databaseName; $this-&gt;username = $username; $this-&gt;password = $password; $this-&gt;openConnection(); } protected function openConnection() { $this-&gt;databaseLink = new PDO("mysql:host=$this-&gt;server;dbname=$this-&gt;databaseName", $this-&gt;username, $this-&gt;password); } public function getLink() { return $this-&gt;databaseLink; } } $database = new Database("localhost", "XXXXXXX", "XXXXXXX", "XXXXXXX"); $databaseLink = $database-&gt;getLink(); ?&gt; </code></pre> <p><strong>The Client Detail Page</strong> <pre><code>$client = $_GET["client"]; $getClientDataSql = "SELECT * FROM `client` WHERE `client`=:client"; $statement = $databaseLink-&gt;prepare($getClientDataSql); $statement-&gt;bindParam(":client", $client, PDO::PARAM_STR); $statement-&gt;execute(); if(!$statement-&gt;rowCount()) { echo "No Clients Found"; } else { $row = $statement-&gt;fetch(PDO::FETCH_ASSOC); // Title echo "&lt;div id='portfolio_detail'&gt;"; echo "&lt;h3&gt;".$row["title"]."&lt;/h3&gt;"; echo "&lt;div class='portfolio_block'&gt;".$row["description"]."&lt;/div&gt;"; // Tags $tags = explode(",", $row["tags"]); if (count($tags)) { echo "&lt;div class='portfolio_block'&gt;"; foreach ($tags as $tag) { echo "&lt;span class='tag'&gt;".$tag."&lt;/span&gt;"; } echo "&lt;/div&gt;"; } // Colours $colours = explode(",", $row["colours"]); if (count($colours)) { echo "&lt;div class='portfolio_block'&gt;&lt;h3&gt;Colours&lt;/h3&gt;"; foreach ($colours as $colour) { echo "&lt;div class='colour_block' id='".$colour."' alt='".$colour."' title='".$colour."'&gt;&lt;/div&gt;"; } echo "&lt;/div&gt;"; } // Services $services = explode(",", $row["services"]); if (count($services)) { echo "&lt;div class='portfolio_block'&gt;&lt;h3&gt;Services&lt;/h3&gt;&lt;ul&gt;"; foreach ($services as $service) { echo "&lt;li id='".$service."'&gt;".$service."&lt;/li&gt;"; } echo "&lt;/ul&gt;&lt;/div&gt;"; } echo "&lt;div class='portfolio_visit'&gt;&lt;a href='".$row["visit"]."'&gt;Visit Website&lt;/a&gt;&lt;/div&gt;"; echo "&lt;/div&gt;"; echo "&lt;div id='portfolio_detail_img'&gt;&lt;img src='"."/client/".$row["client"].".png"."' alt='".$row["client"]."' title='".$row["client"]."' /&gt;&lt;/div&gt;"; echo "&lt;div id='portfolio_detail_slide' class='rsMinB'&gt;"; echo "&lt;div&gt;&lt;img src='"."/client/".$row["client"]."_1.png"."' /&gt;&lt;/div&gt;"; echo "&lt;div&gt;&lt;img src='"."/client/".$row["client"]."_2.png"."' /&gt;&lt;/div&gt;"; echo "&lt;div&gt;&lt;img src='"."/client/".$row["client"]."_3.png"."' /&gt;&lt;/div&gt;"; echo "&lt;/div&gt;"; } ?&gt; </code></pre> <p><strong>The Client List Page</strong> <pre><code>$getPortofolioDataSql = "SELECT `id`, `title`, `description`, `client` FROM `client`"; $statement = $databaseLink-&gt;prepare($getPortofolioDataSql); $statement-&gt;execute(); if($statement-&gt;rowCount() == 0) { echo "No Portfolio Found"; } else { while($portofolioDetails = $statement-&gt;fetch(PDO::FETCH_ASSOC)) { echo "&lt;li class='portfolio'&gt;"; echo "&lt;a href='portfolio/".$portofolioDetails["client"]."'&gt;&lt;img src='http://www.creativewebgroup.co.uk/client/".$portofolioDetails["client"].".png' /&gt;&lt;/a&gt;"; echo "&lt;/li&gt;"; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T16:32:34.520", "Id": "36541", "Score": "2", "body": "Please do not edit the question in a way which makes existing answers meaningless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T18:01:24.907", "Id": "36544", "Score": "1", "body": "In response to your flag: We don't delete questions just because they're answered and probably not helpful to anyone else (to some degree that applies to most questions here). That would just take away reputation from the answerers for no good reason." } ]
[ { "body": "<ul>\n<li><p>Your database queries are using bound parameters with prepared statements. Good.</p></li>\n<li><p>You need to <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow\">escape your output</a>.</p></li>\n</ul>\n\n<p>Other observations:</p>\n\n<ul>\n<li>Your Database class adds nothing (unless you've abbreviated it here for simplicity?). Consider simply using PDO.</li>\n<li>You have no error handling. Try loading your page with incorrect db credentials and see what I mean.</li>\n<li>Consider using markup with php instead of string-ified markup in php. It is much easier to read and maintain.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T02:29:16.480", "Id": "21012", "ParentId": "20979", "Score": "2" } } ]
{ "AcceptedAnswerId": "21012", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T12:55:39.303", "Id": "20979", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "How secure is this PDO Portfolio Script?" }
20979
<p>I've recently discovered how cool <code>reduce()</code> could be and I want to do this:</p> <pre><code>&gt;&gt;&gt; a = [1, 1] + [0] * 11 &gt;&gt;&gt; count = 1 &gt;&gt;&gt; def fib(x,n): ... global count ... r = x + n ... if count &lt; len(a) - 1: a[count+1] = r ... count += 1 ... return r &gt;&gt;&gt; &gt;&gt;&gt; reduce(fib,a,1) 610 &gt;&gt;&gt; a [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] </code></pre> <p>But this just looks so messy and almost defeats the purpose of the last line:</p> <pre><code>reduce(fib,a,1) </code></pre> <p>What would be a better way to use Python to make a Fibonacci number with <code>reduce()</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:14:07.087", "Id": "33681", "Score": "2", "body": "Why do you want to use reduce?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:18:40.630", "Id": "33682", "Score": "1", "body": "Because it seemed cool. I want to use something like reduce, or map. Because it seems like a challenge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:06:09.840", "Id": "33722", "Score": "0", "body": "@CrisStringfellow It's not really the right tool for the job. A generator would be the best choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:39:31.140", "Id": "33738", "Score": "0", "body": "@Lattyware okay but a generator is just too easy." } ]
[ { "body": "<p>If you set</p>\n\n<pre><code>def fib(x, _):\n x.append(sum(x[-2:]))\n return x\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>&gt;&gt;&gt; reduce(fib, xrange(10), [1, 1])\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]\n</code></pre>\n\n<p>But as long as you're looking for something cool rather than something useful, how about this? In Python 3.3:</p>\n\n<pre><code>from itertools import islice\nfrom operator import add\n\ndef fib():\n yield 1\n yield 1\n yield from map(add, fib(), islice(fib(), 1, None))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:41:53.663", "Id": "33717", "Score": "2", "body": "I guess the second snippet tries to mimic Haskell's `fibs = 0 : 1 : zipWith (+) fibs (tail fibs)`. Unfortunately this is terribly inefficient in Python, you'd need to write it in more verbose manner using corecursion and `itertools.tee` (thus the beauty of the Haskell solution completely vanishes). http://en.wikipedia.org/wiki/Corecursion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:45:50.247", "Id": "33718", "Score": "0", "body": "Yes: that's why I described it as \"cool rather than useful\"!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:41:10.247", "Id": "33739", "Score": "0", "body": "I like that a lot the second snippet." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:53:48.787", "Id": "21004", "ParentId": "20986", "Score": "2" } }, { "body": "<p>A <code>reduce</code> (that's it, a fold) is not exactly the abstraction for the task (what input collection are you going to fold here?). Anyway, you can cheat a little bit and fold the indexes even if you don't really use them within the folding function. This works for Python 2.x:</p>\n\n<pre><code>def next_fib((x, y), n):\n return (y, x + y)\n\nreduce(next_fib, xrange(5), (1, 1))[0]\n#=&gt; 8\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:46:05.433", "Id": "33740", "Score": "0", "body": "That is awesome." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:14:06.177", "Id": "21005", "ParentId": "20986", "Score": "4" } }, { "body": "<p>In your case, the interesting part of <code>reduce</code> is to re-apply a function.\nSo, let's define :</p>\n\n<pre><code>&gt;&gt;&gt; def ncompose(f, a, n): return a if n &lt;= 0 else ncompose(f, f(a), n-1)\n</code></pre>\n\n<p>Then,</p>\n\n<pre><code>&gt;&gt;&gt; def fibo((a,b)): return (b, a+b)\n&gt;&gt;&gt; ncompose(fibo, (1,1), 5)[0]\n8\n</code></pre>\n\n<p>Since you like to play with <code>reduce</code>, let's use it to perform composition :</p>\n\n<pre><code>&gt;&gt;&gt; reduce(lambda a,f: f(a), [fibo]*5, (1,1))\n</code></pre>\n\n<p>Like @tokland's answer, it's quite artificial (building n items only as a way to iterate n times).</p>\n\n<p>A side note : Haskell and Scala should provide you even more fun'. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:49:34.360", "Id": "21038", "ParentId": "20986", "Score": "1" } } ]
{ "AcceptedAnswerId": "21005", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T14:29:54.510", "Id": "20986", "Score": "4", "Tags": [ "python", "fibonacci-sequence" ], "Title": "Making this reduce() Fibonacci generator better" }
20986
<p>I have a list with <code>contentlets</code> and want all languages from every <code>contentlet</code> (I get these with the method <code>languageAPI.getAllValuesByKey(key , contentList)</code>. I get a <code>HashMap</code> and iterate over it. There are 1000 keys available. In the beginning it only takes 2 ms per key. But after a while it increases. And the last one takes 35ms. How can I decrease these times? How can I make it faster/more efficient?</p> <pre><code>JSONArray arrAll = new JSONArray(); JSONObject jsonObject = new JSONObject(); JSONArray arr = new JSONArray(); JSONObject values = new JSONObject(); List&lt;Contentlet&gt; contentlets = languageFactory.getAllContentlets(null); List&lt;Contentlet&gt; keys = languageAPI.getLanguageKeys(null, contentlets); for(Contentlet key : keys) { Long startTime = System.currentTimeMillis(); jsonObject = new JSONObject(); HashMap&lt;Long, String&gt; allValues = languageAPI.getAllValuesByKey(key.getStringProperty("key"), contentlets); Iterator&lt;java.util.Map.Entry&lt;Long, String&gt;&gt; it = allValues.entrySet().iterator(); arr = new JSONArray(); while (it.hasNext()) { values = new JSONObject(); java.util.Map.Entry&lt;Long, String&gt; pairs = it.next(); values.put("l", pairs.getKey()); values.put("v", pairs.getValue()); arr.add(values); it.remove(); // avoids a ConcurrentModificationException } try { jsonObject.put("k", key.getStringProperty("key")); jsonObject.put("t", (Object)arr); jsonObject.put("p", key.isLive()); jsonObject.put("l", key.isLocked()); jsonObject.put("a", key.isArchived()); } catch (DotStateException e) { throw new RuntimeException(e.toString(),e); } catch (DotDataException e) { throw new RuntimeException(e.toString(),e); } catch (DotSecurityException e) { throw new RuntimeException(e.toString(),e); } arrAll.add(jsonObject); Long end = System.currentTimeMillis() - startTime; Logger.info(this, "For key: " + key.getStringProperty("key") + " " + end + "ms"); } </code></pre> <p><strong>Edit:</strong></p> <p>One of the problems is that the for loop in the <code>getStringKey</code> method take some time. Of course in the beginning the value is at the beginning, but after a while, it is at the end of the list. So I think one of the problems might be here (this takes 8ms, in the last records)</p> <pre><code>public HashMap&lt;Long, String&gt; getAllValuesByKey(String key, List&lt;Contentlet&gt; contentlets) { HashMap&lt;Long, String&gt; keys = new HashMap&lt;Long, String&gt;(); for(Language language : APILocator.getLanguageAPI().getLanguages()) { keys.put(language.getId(), getStringKey(language.getId(), key, contentlets)); } return keys; } public String getStringKey(Long languageId, String key, List&lt;Contentlet&gt; contentlets){ String value=null; for(Contentlet keyEntry : contentlets) { if(keyEntry.getStringProperty("key").equals(key) &amp;&amp; languageId == keyEntry.getLanguageId()) { return keyEntry.getStringProperty("value"); } } if(value==null) { value = ""; } return value; } </code></pre> <p><strong>Edit 2:</strong> found the problem, but how to solve it?</p> <p>The code after this phrase takes 20ms in the last records. The only thing what happens here is adding some things to a <code>JSONObject</code>. Why is this taking so long? I even don't know, how to make this faster, because this is the only way to handle it?</p> <pre><code> end = System.currentTimeMillis() - startTime; Logger.info(this, "Before add: " + key.getStringProperty("key") + " " + end + "ms"); try { jsonObject.put("k", key.getStringProperty("key")); jsonObject.put("t", (Object)arr); jsonObject.put("p", key.isLive()); jsonObject.put("l", key.isLocked()); jsonObject.put("a", key.isArchived()); } catch (DotStateException e) { throw new RuntimeException(e.toString(),e); } catch (DotDataException e) { throw new RuntimeException(e.toString(),e); } catch (DotSecurityException e) { throw new RuntimeException(e.toString(),e); } end = System.currentTimeMillis() - startTime; Logger.info(this, "After add: " + key.getStringProperty("key") + " " + end + "ms"); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:36:42.193", "Id": "33673", "Score": "4", "body": "Use a profiler to find out where the time is spent. Then you'll know what to optimize." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:37:40.303", "Id": "33674", "Score": "2", "body": "Is it necessary that you remove the entries?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:39:38.867", "Id": "33675", "Score": "0", "body": "also, what type does arrAll have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:45:18.520", "Id": "33676", "Score": "0", "body": "The 'Map.Entry.remove()' method need some time to find the current Object in the entry. Also you need more time-watch to check the slowest method calling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:53:59.170", "Id": "33677", "Score": "0", "body": "Added the initialization of the method. So the arrAll is a JSONArray. I understand that the methods take some time, but why is it in the beginning 2ms and the last one 36ms? They have al the same contentlets (only with another text in it, but they are all short)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T08:04:04.890", "Id": "33678", "Score": "0", "body": "Have you tried writing the data out as plain text instead of building a large data structure first?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T08:34:44.913", "Id": "33679", "Score": "0", "body": "The problem is indeed the objects. I have changed this now to normal Java Objects and after that I convert it to a JSONArray. But this doesn't decrease the time. I can you plain text, but why would I do that and how can I convert that in to a JSONObject" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T08:38:12.570", "Id": "33680", "Score": "1", "body": "Try to profile this method with JVIsual VM. Thus you can gather more information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T07:20:01.973", "Id": "74684", "Score": "0", "body": "You say key.getStringProperty(\"key\") takes quite long. So why do you call it three times. One time should do, if you save it in a var and use that instead." } ]
[ { "body": "<ol>\n<li><p><code>getStringKey</code> iterates over the <code>contentlets</code> list for every <code>key</code>. It looks O(n^2) which does not scale well.\nYou could create a <code>HashMap&lt;ContentletCacheKey, Contentlet&gt;</code> cache with a proper <code>hashCode</code> and <code>equals</code> for <code>ContentletCacheKey</code> and use this instead of iterating over the list every time.</p></li>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p>\n\n<p>This object creation is unnecessary since you create a new object at the beginning of the for loop:</p>\n\n<pre><code>JSONObject jsonObject = new JSONObject();\n</code></pre>\n\n<p>The same is true for <code>values</code> and <code>arr</code>.</p></li>\n<li><p>Your statistics log could show invalid data because if you change the system date <code>System.currentTimeMillis()</code> will reflect that. I suggest using <code>System.nanoTime()</code> or a stopwatch class (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html\">Guava</a>, <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html\">Apache Commons</a>).</p></li>\n<li><pre><code>public String getStringKey(Long languageId, String key, \n List&lt;Contentlet&gt; contentlets) {\n String value = null;\n\n for (final Contentlet keyEntry: contentlets) {\n if (keyEntry.getStringProperty(\"key\").equals(key) \n &amp;&amp; languageId == keyEntry.getLanguageId()) {\n return keyEntry.getStringProperty(\"value\");\n }\n }\n\n if (value == null) {\n value = \"\";\n }\n return value;\n}\n</code></pre>\n\n<p>This could be more simple:</p>\n\n<pre><code>public String getStringKey(Long languageId, String key, \n List&lt;Contentlet&gt; contentlets) {\n for (final Contentlet keyEntry: contentlets) {\n if (keyEntry.getStringProperty(\"key\").equals(key) \n &amp;&amp; languageId == keyEntry.getLanguageId()) {\n return keyEntry.getStringProperty(\"value\");\n }\n }\n return \"\";\n}\n</code></pre></li>\n<li><pre><code> Iterator&lt;java.util.Map.Entry&lt;Long, String&gt;&gt; it \n = allValues.entrySet().iterator();\n JSONArray arr = new JSONArray();\n while (it.hasNext()) {\n JSONObject values = new JSONObject();\n java.util.Map.Entry&lt;Long, String&gt; pairs = it.next();\n values.put(\"l\", pairs.getKey());\n values.put(\"v\", pairs.getValue());\n arr.add(values);\n it.remove(); // avoids a ConcurrentModificationException\n }\n</code></pre>\n\n<p>If I'm right you can clear the the whole map after loop (instead of <code>remove</code> in every iteration) and could use a foreach loop:</p>\n\n<pre><code>for (final Map.Entry&lt;Long, String&gt; pairs: allValues.entrySet()) {\n final JSONObject values = new JSONObject();\n values.put(\"l\", pairs.getKey());\n values.put(\"v\", pairs.getValue());\n arr.add(values);\n}\nallValues.clear();\n</code></pre>\n\n<p>Actually, the clear() need unnecessary (as well as the <code>it.remove()</code>) since you don't use the allValues map after the <code>while</code> (<code>for</code>) loop. Furthermore, importing <code>java.util.Map.Entry</code> makes the code easier to read.</p></li>\n<li><p><code>HashMap&lt;...&gt;</code> reference types should be simply <code>Map&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T00:26:37.323", "Id": "42712", "ParentId": "20992", "Score": "7" } } ]
{ "AcceptedAnswerId": "42712", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T07:32:49.027", "Id": "20992", "Score": "5", "Tags": [ "java", "performance", "iterator" ], "Title": "How to make an iteration in a for-loop faster?" }
20992
<p>I'm developing an Android app that performs several requests to a server using the <a href="http://loopj.com/android-async-http/" rel="nofollow">AndroidAsynchronousHttpClient</a>. One of these requests (as an example) is responsible to send the username and password. I created a class <code>Sign</code> that has a static method (see below) to which I provide a callback to handle the server's response. Is this considered a bad practice? </p> <p>I'm asking this because I'm having a hard time testing with Mockito.</p> <pre><code>public class Sign { public static void signin(String username, String password, final SigninResponseHandler responseHandler) { RequestParams params = new RequestParams(); params.put("username", username); params.put("password", password); MyAPIClient.getInstance().post(path, params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject responseObject) { String responseAPIStatus = responseObject.getString("status"); if (status.isEquals("success") { responseHandler.callback(true, null); } } @Override public void onFailure(Throwable e, JSONObject errorResponse) { responseHandler.callback(false, new CustomError(e)); } }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:20:32.857", "Id": "33694", "Score": "0", "body": "It's the singleton which indicates problems with the code." } ]
[ { "body": "<p>I see nothing bad with this code. I mean as far as I can see you do not want to store any data, you just want to get the answer from the server, but maybe you want to handle this by an other thread because it can cause delays. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:14:10.420", "Id": "33696", "Score": "0", "body": "The AndroidAsynchronousHttpClient executes the post in another thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:22:07.917", "Id": "33697", "Score": "1", "body": "oh ok dont know much about android development :P" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:10:40.607", "Id": "20995", "ParentId": "20994", "Score": "0" } }, { "body": "<p>Each new call to this method creates a new instance of the interface thus all calls to this method use a resource (JsonHttpResponseHandler) different.\nBut you deveira mark the method as \"synchronized\" for sharing the object \"SigninResponseHandler\"</p>\n\n<p><a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html\" rel=\"nofollow\">Synchronized on oracle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:17:02.460", "Id": "20996", "ParentId": "20994", "Score": "0" } }, { "body": "<p>Overdoing static is a code smell. Basically you have to balance things.</p>\n\n<p>Too much static code typically means not enough code in the objects, or not much object oriented structure. Since objects provide boundaries between the in-object code and the rest of the system, they allow \"leverage points\" for future change (and for testing). You can, for example, subclass an object to provide a variety of implementations of a particular class method.</p>\n\n<p>With static methods, no such polymorphisim is possible. This can lead to switch statements embedded within the static method (to function on key fields, acting somewhat like the <em>state</em> pattern). The primary reason this <em>tends</em> to become a smell is that switch statements put the burden of code maintenance outside of the object. In extreme cases, it begins to feel like the object is not encapsulating it's behavior, but rather the switch statement dictates external behavior depending on the data fields within the object. Such code becomes difficult to maintain over time.</p>\n\n<p>I would avoid <em>static methods</em> as much as reasonably possible; however, in some cases it is a better choice to use them. For example, one would not typically benefit from subclassing the java core types. So if I needed to write a method that operated on String objects, I would probably prefer to put that as a static method on a <code>StringUtils</code> class. On the other hand, if it were a class that I had written, I would probably go out of my way to stay more object-oriented.</p>\n\n<p>In your example...</p>\n\n<pre><code>MyAPIClient.getInstance().post(path, params,\n new JsonHttpResponseHandler()\n {\n @Override\n public void onSuccess(JSONObject responseObject)\n {\n String responseAPIStatus = responseObject.getString(\"status\");\n if (status.isEquals(\"success\")\n {\n responseHandler.callback(true, null);\n }\n\n }\n\n @Override\n public void onFailure(Throwable e, JSONObject errorResponse)\n {\n responseHandler.callback(false, new CustomError(e));\n }\n });\n</code></pre>\n\n<p>is going to be very hard to test. If only you had made an interface on the <code>MyAPIClient</code>, you could do something like.</p>\n\n<pre><code>public SignIn(String username, String password,\n final SigninResponseHandler responseHandler,\n final MyAPIClient) {\n ...\n}\n</code></pre>\n\n<p>which would make SignIn easily be unit testable, like so</p>\n\n<pre><code>SignIn signIn = new SignIn(\"bob\", \"supersecret\", new JsonHttpResponseHandler() {...},\n new MockAPI() {... });\nsignIn.perform();\n</code></pre>\n\n<p>while the mainline code would look like</p>\n\n<pre><code>SignIn signIn = new SignIn(\"bob\", \"supersecret\", new JsonHttpResponseHandler() {...},\n MyAPIClient.getInstance());\nsignIn.perform();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T18:28:21.260", "Id": "33699", "Score": "0", "body": "Thank you so much Edwin for your answer but now I'm concerned about one Class file for each request type I have in my application. Two if you consider the response handles interface. Isn't that strange? For example, I have two requests: product/list and product/buy. They shouldn't be in the same file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:28:09.367", "Id": "33707", "Score": "1", "body": "@RaphaelOliveira It is normal to have concerns, and eventually we all settle for the best choice we can afford out of a number of progressively more expensive solutions. Your second question would be better served as a second question. The commentary sections at the end of a question are not large enough to really address a second follow up question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T17:14:45.440", "Id": "171142", "Score": "0", "body": "As a proponent of functional programming, I disagree with the essence of your argument. Polymorphism and storing data in objects (mutable state!) aren't necessarily good things; in fact I would argue that they are more often than not bad. Source 1) https://en.wikipedia.org/wiki/Composition_over_inheritance 2) http://c2.com/cgi/wiki?KillMutableState" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T18:25:35.443", "Id": "171163", "Score": "0", "body": "@Sridhar-Sarnobat If you don't want objects (code and data together) and you don't want polymorphisim, then __as a proponent of functional programming__ why use Java? Scheme or CommonLisp work just fine, and aren't encumbered with an entire library that's designed (more or less) to have these features you don't want to use. From those of us who came into Java from the C / Iterative side of programming, these features make it possible to write a lot of code (tens of millions of lines) in a maintainable way, something not easy to do from the functional side (I know, I've lived in both worlds)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T19:43:53.357", "Id": "171180", "Score": "0", "body": "In practice, the programming paradigm is only one aspect to consider when choosing a language. I've worked at some large companies (who I guess I am not allowed to mention) that are big on functional programming but are tied to java. They're not ready to make that leap to Scala etc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:27:57.570", "Id": "20997", "ParentId": "20994", "Score": "3" } }, { "body": "<p>Yes, it's a smell: <a href=\"http://xunitpatterns.com/Hard%20to%20Test%20Code.html\" rel=\"nofollow\">Hard-to-Test Code</a></p>\n\n<p>I'd start with the following:</p>\n\n<ol>\n<li>Create an interface for <code>MyApiClient</code> (usually it's easier to mock interfaces than classes),</li>\n<li>Remove the static modifier of <code>signin</code>,</li>\n<li>Create a constructor in <code>Sign</code> which get a <code>MyApiClient</code> instance and store it in a field,</li>\n<li>Modify the <code>signin</code> method to use the instance above.</li>\n</ol>\n\n\n\n<pre><code>public class Sign {\n\n private final MyApiClient client;\n\n public Sign(final MyApiClient client) {\n this.client = client;\n }\n\n public void signin(final String username, final String password, \n final SigninResponseHandler responseHandler) {\n ...\n client.post(path, params, ...\n</code></pre>\n\n<p>Here you can create a <code>Sign</code> object with a mocked <code>MyApiClient</code> which is easier to test.</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p><code>Sign</code> does not seem a good class name. From <em>Clean Code</em>, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote></li>\n<li><p><code>MyApiClient</code> also should be renamed something meaningful.</p></li>\n</ol>\n\n<p>Some useful readings:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx\" rel=\"nofollow\">Eliminating static helper classes</a></li>\n<li><a href=\"http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html\" rel=\"nofollow\">TotT: Using Dependency Injection to Avoid Singletons</a></li>\n<li><em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:23:10.450", "Id": "33704", "Score": "0", "body": "Thanks for your answer palacsint. One doubt, why MyApiClient should be an interface? At the moment it is a singleton and extends AsyncHttpClient to do custom url behavior. The guys recommend to use static methods http://loopj.com/android-async-http/." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T01:02:29.873", "Id": "33728", "Score": "0", "body": "@RaphaelOliveira: I think they suggest static because \"to make it easy to communicate with Twitter’s API\". On the other hand it makes testing harder. (I've updated the answer too.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T18:52:01.393", "Id": "21000", "ParentId": "20994", "Score": "3" } }, { "body": "<p>I disagree completely with all the others in this thread, probably because I find Functional programs so much easier to reason about than Imperative Object-Oriented code. Making a method static is the first step to making java code functional-style.</p>\n\n<p>When you make methods static, you make dependencies between inputs and outputs explicit without having to read the body of the method. It's a similar argument to why dependency injection is helpful.</p>\n\n<p>I agree that inability to mock can be inconvenient for testing existing code, but the need to mock in the first place is a sign that your code has rigid dependencies.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T17:23:09.447", "Id": "94002", "ParentId": "20994", "Score": "0" } } ]
{ "AcceptedAnswerId": "20997", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:59:32.290", "Id": "20994", "Score": "4", "Tags": [ "java", "android", "static" ], "Title": "Android app for sending username and password requests" }
20994
<p>I am new to jQuery, and after spending weeks to convert my pages using jQuery, I am now reading about jQuery optimization. In that effort, I'm rewriting one of my functions. Please comment whether it is right (both are working).</p> <p><strong>Previous</strong></p> <pre><code>$("#mydiv").empty(); var i = 2; $("#axisa option").each(function() { $("#mydiv").append("&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;"); updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val()); i++ }); $("#axisb option").each(function() { $("#mydiv").append("&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;"); updateCharts($("#wd").slider("value"), $("#ht").slider("value"),$(this).val()); i++ }); $("#hiddendiv").show("slow"); </code></pre> <p><strong>Optimized</strong></p> <pre><code>var mydiv = $("#mydiv"); var mywid = $("#wd").slider("value"); var myhet = $("#ht").slider("value"); var total = $("#axisa option").length + $("#axisb option").length+2; mydiv.empty(); var design = ""; for(var i=2;i&lt;total;i++){ design += "&lt;div id='tempdiv"+i+"'&gt;&lt;/div&gt;"; } mydiv.append(design); i = 2; $("#axisa option").each(function() { updateCharts(mywid, myhet, $(this).val()); i++ }); $("#axisb option").each(function() { updateCharts(mywid, myhet, $(this).val()); i++ }); $("#hiddenDiv").show("slow"); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:36:07.640", "Id": "33708", "Score": "0", "body": "you define `mydiv` as a variable, but then you still use `$('#mydiv')`. Could you throw this up into a jsFiddle with some target HTML? I'm not quite clear on what you are trying to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T19:51:12.157", "Id": "33710", "Score": "0", "body": "frankly, I still am not totally clear how to optimize jquery ... I read somewhere that I should not call same selector again and again to avoid creating too many jquery objects... but not sure how exactly to do that. \nhttp://stackoverflow.com/questions/3230727/jquery-optimization-best-practices" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:30:33.287", "Id": "33713", "Score": "2", "body": "that makes sense, and I see you doing it, but then you use `$(\"#mydiv\").append(design)` when you could have used `mydiv.append(design)`. Larger picture though -- I don't know what your code is trying to _accomplish_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T04:37:21.643", "Id": "33734", "Score": "0", "body": "o yaa, that was a mistake..i missed that ... corrected ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T19:37:21.807", "Id": "34255", "Score": "0", "body": "Caching selectors with a variable is a good optimisation. A handy naming convention that a lot of people use is to prefix $ on your variable name. var $mydiv = $('#mydiv'). That way you will remember that what you have is a jQuery selector (JavaScript doesn't treat the $ as anything special, its just a visual reminder)" } ]
[ { "body": "<p>Here are some general optimizations that I usually do.</p>\n\n<p>When you have multiple var declarations you can separate with \",\" making it a bit easier to read and less of a hassle to write:</p>\n\n<pre><code>var mydiv = $(\"#mydiv\").empty(),\n mywid = $(\"#wd\").slider(\"value\"),\n myhet = $(\"#ht\").slider(\"value\"),\n etc = etc.....\n</code></pre>\n\n<p>Also when I name my variables, ids, classes, etc. it's good to put names that reference what's inside the element, or the role it plays. It will help you remeber what does what when you get into big projects with lots of these declarations.</p>\n\n<p>As a rule of thumb, if you have to call on an element more than once, you should cache its value. This way jQuery doesn't have to jump into the DOM and look for that element each time you call it. You should also try to limit the scope of elements jQuery has to look through to find the one you want. You can use the type of element previous to the id/class. For example:</p>\n\n<pre><code>$(\"#mydiv\").doSomething();\n$(\"#mydiv\").doSomethingElse();\n</code></pre>\n\n<p>Instead do:</p>\n\n<pre><code>var mydiv = $(\"div #mydiv\");\n\n$(mydiv).doSomething();\n$(mydiv).doSomethingElse();\n</code></pre>\n\n<p>Like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called <a href=\"https://tutsplus.com/course/30-days-to-learn-jquery/\" rel=\"nofollow\">30 Days to Learn jQuery</a>. He does a really good job of explain some basic principals as well as some more complex concepts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:15:16.340", "Id": "21343", "ParentId": "20998", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T17:39:31.483", "Id": "20998", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Optimized jQuery code check" }
20998
<p>I have PostgreSQL 9.1.1 running in a shared hosting environment and I'm running this query:</p> <pre><code>SELECT a.id, CASE WHEN a.idpai IS NULL THEN a.nome ELSE concat(a.nome, ' (', b.nome, ')') END AS nome, a.idpai FROM localidade a LEFT OUTER JOIN localidade b ON a.idpai = b.id WHERE a.idcidade = :idcidade AND normalizar( CASE WHEN a.idpai IS NULL THEN a.nome ELSE concat(a.nome, ' (', b.nome, ')') END ) LIKE normalizar(:nome) ORDER BY CASE WHEN normalizar( CASE WHEN a.idpai IS NULL THEN a.nome ELSE concat(a.nome, ' (', b.nome, ')') END ) LIKE substring(normalizar(:nome) from 2) THEN 1 ELSE 2 END, a.nome, b.nome LIMIT 15 </code></pre> <p>The performance is pretty good, the query returns in less than 50ms. Though, I'm repeating this part 3 times inside the query:</p> <pre><code>CASE WHEN a.idpai IS NULL THEN a.nome ELSE concat(a.nome, ' (', b.nome, ')') END </code></pre> <p>I believe this reduces the maintainability of the query and is not DRY at all. What is the recommended way to handle that? Should I create a function in my schema solely for this query? Or just store it in a variable and concatenate into the query in my back end before sending it over to the db server? Or is there any better way around?</p> <p>I believe what this query does isn't the main point here, but just to give some background:</p> <p>The <code>localidade</code> table may or may not have a relation with itself through the <code>idpai</code> which references a "parent" register. Assuming this table format:</p> <pre><code>id | nome | idpai 1 | foo | 2 | bar | 1 </code></pre> <p>So if the query placeholder <code>:nome</code> contains <code>%foo%</code>, it will return:</p> <pre><code>id | nome | idpai 1 | foo | 2 | bar (foo) | 1 </code></pre> <p>The <code>ORDER BY</code> clause is just to display results which the query parameter matches the beginning of the returned row's <code>name</code> before those who don't - <code>SUBSTRING('%foo%' FROM 2)</code> returns <code>foo%</code> -, and then the matching and not matching groups are ordered by <code>a.nome</code> and <code>b.nome</code> ASC as the SQL shows.</p> <p><code>normalizar</code> is a <code>STABLE</code> function that takes a string as parameter and calls <code>LOWER()</code> and removes accentuation returning the new string, so I can perform case-insensitive and accent-insensitive string comparison. Similar to <a href="http://www.postgresql.org/docs/9.1/static/unaccent.html" rel="nofollow"><code>unaccent</code></a> which I couldn't properly apply on my use case due to some encoding problems (page is UTF8 and DB is latin1, if I convert the UTF8 to latin1 solely on the back end I'll have broken UTF8 pages; well this has been solved with the function above and is off-topic).</p> <p><code>idcidade</code> is just a foreign key which I use to reduce the result set to less than 0.1% of the table. Hence performance isn't really an issue in this specific case.</p> <p>My real question is, does calling <code>CASE</code> multiple times passing the exact same parameters have an impact on performance? I assume the result from <code>CASE</code> should be <code>STABLE</code> and the query will be optimized automatically then. If that's the case, I can store part of the query into a variable on my back end and build the query string using that. Otherwise, if calling <code>CASE</code> multiple times in the same query with the same arguments affects performance, should I create a <code>STABLE</code> function for it then or what's the correct approach to this? Any pointers are appreciated.</p>
[]
[ { "body": "<p>I think this part:</p>\n\n<pre><code>CASE WHEN a.idpai IS NULL THEN a.nome\nELSE concat(a.nome, ' (', b.nome, ')')\nEND AS nome\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>CONCAT(a.nome, ' (' || b.nome || ')') AS nome\n</code></pre>\n\n<p>If b.nome is NULL, then \"' (' || b.nome || ')'\" will also be NULL (concatenating strings using '||' with NULL values will result in NULL. CONCAT() ignore null values, so will return only a.none in this case</p>\n\n<p>In other words: if b.nome is present, it will output \"a.nome (b.nome)\", otherwise \"a.nome\"</p>\n\n<p>You can test it yourself, here's my sqlfiddle:</p>\n\n<p><a href=\"http://sqlfiddle.com/#!1/d41d8/744/0\" rel=\"nofollow\">http://sqlfiddle.com/#!1/d41d8/744/0</a></p>\n\n<p>Also, you can try to use a subselect to prevent having to repeat this CONCAT;</p>\n\n<p><a href=\"http://sqlfiddle.com/#!1/a9571/7/0\" rel=\"nofollow\">http://sqlfiddle.com/#!1/a9571/7/0</a></p>\n\n<p>I haven checked if this improves performance, but it reduces the amount of repeated code and may be better maintainable</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:11:30.863", "Id": "33936", "Score": "0", "body": "Awesome! Thanks. I've read about the side effect of `||`ing with `NULL` before but never thought of taking advantage of it. Brilliant solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:13:48.893", "Id": "33937", "Score": "0", "body": "@FabrícioMatté Glad I could help!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T23:33:59.863", "Id": "21144", "ParentId": "20999", "Score": "3" } }, { "body": "<p>A few additional simplifications:</p>\n\n<pre><code>SELECT a.id\n ,concat(a.nome, ' (' || b.nome || ')') AS nome\n ,a.idpai\nFROM localidade a\nLEFT JOIN localidade b ON a.idpai = b.id\nWHERE a.idcidade = :idcidade\nAND normalizar(concat(a.nome, ' (' || b.nome || ')'))\n LIKE ('%' || normalizar(:nome) || '%')\nORDER BY (normalizar(concat(a.nome, ' (' || b.nome || ')'))\n LIKE (normalizar(:nome)) || '%') DESC NULLS LAST\n ,2\nLIMIT 15;\n</code></pre>\n\n<ul>\n<li><p><a href=\"http://www.postgresql.org/docs/current/interactive/functions-string.html#FUNCTIONS-STRING-OTHER\" rel=\"nofollow noreferrer\"><code>right(x, -1)</code></a> would be a little simpler and faster than <code>substring(x from 2)</code>. But if you follow my advice below you don't need either.</p></li>\n<li><p>If you use this query in a prepared statement of function, and you know the search term is never anchored (always <code>%</code> around the term - <code>%foo%</code>), then it will be faster to use explicit placeholder. Let the planner know, the pattern <em>always</em> starts with <code>%</code>, so the query plan can be optimized.</p></li>\n<li><p>You can just <code>ORDER BY</code> the boolean result of an expression. No need for a case statement. <code>FALSE</code> (0) sorts before <code>TRUE</code> (1) sorts before <code>NULL</code>.<br>\nI added <code>NULLS LAST</code> to get 100% identical behaviour like your original with descending order. Consider this <a href=\"http://sqlfiddle.com/#!12/d41d8/564\" rel=\"nofollow noreferrer\"><strong>SQLfiddle</strong> demonstrating the effect</a>.</p></li>\n<li><p>I also <code>ORDER BY</code> the <em>positional parameter</em> <code>2</code> to simplify the syntax. Won't make the query faster, just shorter.</p></li>\n<li><p>One thing to consider: If <code>a.idpai IS NOT NULL</code> that doesn't necessarily mean <code>b.nome IS NOT NULL</code>, so the original and the simplified <code>concat()</code> version are not identical if <code>b.nome</code> can be <code>NULL</code>.</p></li>\n<li><p>I would make the function <code>normalizar</code> <code>IMMUTABLE</code>, since the result is always the same for the same input. Probably won't make a difference for this query, though. Both <code>STABLE</code> and <code>IMMUTABLE</code> function can be optimized by the query planner.</p></li>\n<li><p>Some other minor syntax simplifications <em>just to demonstrate possibilities</em>. Like .. <code>~~</code> is a Postgres operator for the SQL standard <code>LIKE</code>. (Niether is faster, <code>~~</code> is just shorter but non-standard. Note the slight difference in operator precedence. You may have to change parenthesis since <code>~~</code> (or <code>~~*</code>, <code>!~~</code>, <code>!~~*</code>) binds stronger than <code>LIKE</code> (or <code>ILIKE</code>, <code>NOT LIKE</code>, <code>NOT ILIKE</code>).</p></li>\n</ul>\n\n<p>If your tables are big and you really want fast - like <strong>several orders of magnitude faster</strong> than what you have - then create a <strong>materialized view</strong> (read <a href=\"https://dba.stackexchange.com/questions/34326/aggregating-statistics-from-child-rows/34458#34458\">here</a> and <a href=\"https://stackoverflow.com/questions/10283979/postgresql-script-execution-every-night/10285480#10285480\">here</a>) with a <strong>trigram GIN or GiST index</strong> to support non-anchored <code>LIKE</code> searches. Read <a href=\"https://dba.stackexchange.com/questions/10694/pattern-matching-with-like-similar-to-or-regular-expressions-in-postgresql/10696#10696\">here</a> and <a href=\"https://dba.stackexchange.com/questions/2195/how-is-like-implemented/10856#10856\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:23:30.103", "Id": "36552", "Score": "0", "body": "Thanks for your throughout answer. Many of your answers in SO helped me in the past as well and I'm grateful for that. On topic now, there is no advantage in using `~~` instead of `LIKE` besides the reduced characters, right? In that case the more verbose form `LIKE` is technically more maintainable when members of your team do not have as much PGSQL experience. I forgot to mention that `b.nome` cannot be `null`, my bad. Some things I'm not 100% sure: does `NULLS LAST` make a difference? It seems to be the default. Also does positional parameter 2 correspond to the 2nd column in the SELECT?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:26:53.187", "Id": "36553", "Score": "0", "body": "And 2 more serious issues: running `~~` in the `WHERE` results in an \"ERROR: argument of WHERE must be type boolean, not type text\", which doesn't happen using LIKE ([simplified sqlfiddle](http://sqlfiddle.com/#!1/5c75e/7)), and one last thing, your `concat(a.nome, ' (', b.nome, ')')` will display `a.nome's value ()` when `b.nome` is `null` - not showing empty brackets when `b.nome` is `null` was the main point of the question. Thanks for the time to provide your answer and insights though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:34:31.787", "Id": "36554", "Score": "0", "body": "Sorry for the number of questions, but I can only find documentation on positional parameters when it is inside of a SQL function. Weird thing is, the documentation says that double tildes are equivalent to LIKE ([link](http://www.postgresql.org/docs/8.3/static/functions-matching.html)) but it fails in the fiddle's `WHERE`. Weird." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:38:56.990", "Id": "36555", "Score": "0", "body": "Oh the issue with ~~ was probably due to operator precedence, `~~ ('%' || normalizar(:nome) || '%')` works. At least this shows that these are not 100% equivalent apparently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:43:28.620", "Id": "36556", "Score": "0", "body": "Apart from the issue with empty brackets when `b.nome` is `null`, your answer does not account for ordering by matches starting with the queried string first. http://sqlfiddle.com/#!1/3872a/1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:38:26.650", "Id": "36561", "Score": "0", "body": "@FabrícioMatté: **`LIKE`**: ~~ was `just to demonstrate possibilities`. Neither is faster. As you found out yourself: the only difference is in [operator precedence](http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-PRECEDENCE), you may need parens with `~~`. I should have mentioned that. `~~` is just shorter for ad-hoc queries. I wouldn't use it in stored code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:51:44.750", "Id": "36563", "Score": "0", "body": "Alright, I'll keep these possibilities in mind. +1 for these. Can't give an accept as your query unfortunately breaks the two main goals of my original query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T00:08:11.593", "Id": "36565", "Score": "0", "body": "@FabrícioMatté: **concat()**: I fixed that. Transformed the expression to avoid empty `()` and added the missing `|| '%'` in the `ORDER BY`. Now it should do what you were looking for. Also added clarification for `LIKE` and put it back in the query as that is the better option, generally. And I added an SQLfiddle demo to better explain `ORDER BY <bool> DESC NULLS LAST`. Also consider your [updated SQLfiddle](http://sqlfiddle.com/#!1/3872a/3) demonstrating the now working `ORDER BY`. Sorry for the mistakes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T00:16:45.490", "Id": "36566", "Score": "0", "body": "No problem. `=]` I've never had a too deep involvement with PostgreSQL but my logic thinking never failed me - with your explanation and fiddle the `DESC NULLS LAST` is crystal clear! Thanks again." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:12:24.283", "Id": "23669", "ParentId": "20999", "Score": "1" } } ]
{ "AcceptedAnswerId": "23669", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T18:30:15.517", "Id": "20999", "Score": "4", "Tags": [ "sql", "postgresql" ], "Title": "PostgreSQL simple query with repeated function calls" }
20999
<p>I'm pulling data from a list of images and passing it into an information container after click. After looking at my logic I assume there is a better way to do this. Any ideas would be helpful.</p> <pre><code>var getData = function() { $('.guest-image').html('&lt;img src="' + $($this).data("image") + '" /&gt;'); if ($($this).data("known1") != undefined) { $('.guest-data .known-for li').eq(0).html('&lt;img src="' + $($this).data("known1") + '" data-title="' + $($this).data("known1title") + '" /&gt;'); } if ($($this).data("known2") != undefined) { $('.guest-data .known-for li').eq(1).html('&lt;img src="' + $($this).data("known2") + '" data-title="' + $($this).data("known2title") + '" /&gt;'); } if ($($this).data("known3") != undefined) { $('.guest-data .known-for li').eq(2).html('&lt;img src="' + $($this).data("known3") + '" data-title="' + $($this).data("known3title") + '" /&gt;'); } $('.guest-data .title').text($($this).data("name")); $('.guest-data .desc').text($($this).data("desc")); $('.guest-data .link').text($($this).data("link")); $('.guest-data .link').attr('href', $($this).data("link")); } </code></pre>
[]
[ { "body": "<p>squished and optimized, the code looks like this:</p>\n\n<pre><code>function getData() {\n var guestData = $('.guest-data'),\n knownFors = $('.known-for li', guestData),\n data = $($this).data();\n $('.guest-image').html('&lt;img src=\"' + data.image + '\"/&gt;');\n $.each(data.knowns, function (i, entry) {\n knownFors.eq(i).html('&lt;img src=\"' + entry.known + '\" data-title=\"' + entry.title + '\"/&gt;')\n });\n $('.title', guestData).text(data.name);\n $('.desc', guestData).text(data.desc);\n $('.link', guestData).text(data.link).attr('href', data.link)\n}\n</code></pre>\n\n<p>and here's the explanation</p>\n\n<pre><code>//named functions are better in debugging\nfunction getData() {\n\n //cache frequently used elements\n var guestData = $('.guest-data'),\n\n //providing a query context limits jQuery to locate a selector only under the context\n //so in this code, we find .known-for li only under guestData which we already cached\n //instead of traversing the DOM again for each find\n knownFors = $('.known-for li', guestData),\n\n //jQuery data can be fetched as a JS object by a parameter-less .data()\n data = $($this).data();\n\n //by informal convention, variables prefixed by $ usually means it\n //references a jQuery object. You may not need wrap it again with\n //a $() call if you are sure it's already a jQuery object\n\n //there are two ways to build elements in jQuery\n\n //for performance, string assembly would be faster\n $('.guest-image').html('&lt;img src=\"'+data.image+'\"/&gt;');\n\n //for readability, but slow, the jQuery element builder method\n $('.guest-image').html($('&lt;img/&gt;', {\n 'src': data.image\n }));\n\n //I also have to note as to why .guest-image was not cached\n //it's simply because it is only used once in the function\n\n //for your \"knowns\", I suggest placing them in an array and in order\n //so that you can easily iterate through and attach to your html\n\n //example of the structure\n /*\n data.knowns = [\n {\n known : 'known here',\n title : 'title here'\n },{\n known : 'known here',\n title : 'title here'\n }\n ];\n */\n\n //looping through the structure\n $.each(data.knowns, function (i, entry) {\n\n //string assembly method\n knownFors.eq(i).html('&lt;img src=\"'+entry.known+'\" data-title=\"'+entry.title+'\"/&gt;')\n\n //builder method\n knownFors.eq(i).html($('&lt;img/&gt;', {\n 'src': entry.known,\n 'data-title': entry.title\n }));\n\n });\n\n $('.title', guestData).text(data.name);\n $('.desc', guestData).text(data.desc);\n\n //lastly, some jQuery functions return the element they operated on\n //this makes chaining possible.\n $('.link', guestData).text(data.link).attr('href', data.link);\n}\n</code></pre>\n\n<p><s>Here's a <a href=\"http://jsperf.com/so-perftest\" rel=\"nofollow\">JS perf performance test</a>. Compared to your code, the builder method is more readable, verbose but 23% slower. The string assembly method is 7% faster than your code.</s> </p>\n\n<p>Seems like it was faster only on my Firefox 18 and Firefox 21 Android (Nightly) and was too eager to conclude.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T15:11:53.300", "Id": "33761", "Score": "0", "body": "How many time did you run your JS perf, I've been running them a few times in FF, Chrome & IE and the original code seams faster?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:08:38.367", "Id": "33821", "Score": "0", "body": "@soderslatt well, i ran it several times and im on linux so no safari or IE to use. However, optimization isnt necessarily just abot speed. It's also about DRY and minimal code as well as readability and maintainability. Though the original code is faster, the code is all over the place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:35:13.230", "Id": "33825", "Score": "1", "body": "Of course DRY is preferred and your structure is much better than the original! Just wanted to point out that the performance figures shouldn't be taken as a fact." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:09:36.467", "Id": "21017", "ParentId": "21006", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T22:47:39.913", "Id": "21006", "Score": "4", "Tags": [ "javascript", "jquery", "html" ], "Title": "Improving logic for pulling and passing data();" }
21006
<p>My task is:</p> <p>Write a program that reads integers until 0 is entered. After input terminates, the program should report the total number of even integers (excluding the 0) entered, the average value of the even integers, the total number of odd integers entered, and the average value of the odd integers.</p> <p>But I had to use switch for this...</p> <p>My code is:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int oddIndex = 0, evenIndex = 0, evenTotal = 0, evenSum, oddTotal = 0, oddSum; int userInput; int oddArray[oddIndex], evenArray[evenIndex]; printf("please enter some numbers: \n"); while (((scanf("%d", &amp;userInput)) == 1) &amp;&amp; (userInput != 0)) { switch (userInput%2) { case 0: evenArray[evenIndex] = userInput; evenIndex++; evenTotal++; evenSum += userInput; break; default: oddArray[oddIndex] = userInput; oddIndex++; oddTotal++; oddSum += userInput; break; }; } if (evenTotal &gt; 0) printf("even total: %d, even average: %d\n", evenTotal, evenSum/evenTotal); else printf("there is no even numbers!\n"); if (oddTotal &gt; 0) printf("odd total: %d, odd average: %d", oddTotal, oddSum/oddTotal); else printf("there is no odd numbers!"); } </code></pre> <p>Is this code ok? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:48:45.827", "Id": "33724", "Score": "0", "body": "It's a little weird that you're using a `switch` for a 2-case scenario; an `if-else` would be more appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:49:17.757", "Id": "33725", "Score": "0", "body": "You *have to*? Is this an homework?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:50:04.197", "Id": "33726", "Score": "0", "body": "yes i know, its kind of stupid. but in the task, first he said to do this with if else, but couple of exercises latter he asked to redo this exercise using switch..@seand" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:50:57.473", "Id": "33727", "Score": "0", "body": "yes, i have to use switch for this task. its not homework, im reading the C primer plus book @akappa" } ]
[ { "body": "<ol>\n<li><p>It does not work well on my machine (gcc version 4.4.5):</p>\n\n<pre><code>please enter some numbers: \n1\n2\n3\n0\neven total: 1, even average: 134519058\nodd total: 2, odd average: 67257214\n</code></pre></li>\n<li><p>The size of <code>oddArray</code> and <code>evenArray</code> is zero. (<code>oddArray[oddIndex]</code>, where <code>oddIndex</code> is zero) (See also: <a href=\"https://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c\">How to initialize an array in C</a></p></li>\n<li><p>Actually, you could remove these arrays <code>oddIndex</code>, and <code>evenIndex</code>, they are only written, never read.</p></li>\n<li><p>There are missing <code>\\n</code>s in the last two <code>printf</code>s.</p></li>\n<li><p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...] \n It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote></li>\n<li><p>The names <code>evenTotal</code> and <code>oddTotal</code> are confusing since you have <code>evenSum</code> and <code>oddSum</code> too. I'd call them <code>evenCount</code> and <code>oddCount</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T01:52:08.220", "Id": "33729", "Score": "0", "body": "Hi, i initialized the odd/even numbers array to zero before entering the loop to 0, so it will store the first number in place0, and then I increment this index by one so the next time i will store a number it will go to the next place in the array...how should i'v done it? im reading \"C primer plus\" and i saw this method over there, but maybe I got it wrong..thanks! @palacsint" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T11:37:11.410", "Id": "33747", "Score": "0", "body": "@user1959174: I'm not too familiar with C, but I think you should use `malloc` here. Anyway, those arrays are unnecessary here, so I would simply remove them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T00:08:37.360", "Id": "21008", "ParentId": "21007", "Score": "3" } }, { "body": "<p>I haven't been a C guy for years, but a few observations:</p>\n\n<p>You have <code>int oddArray[oddIndex], evenArray[evenIndex];</code> declared, but the only time you use it is to add the entered number, and even that will fail because you have basically declared them as size[0], so oddArray[1] will throw an exception.</p>\n\n<p>I think <code>[even|odd]Index and [even|odd]Total</code> can be combined into one variable.</p>\n\n<p>I'm not sure what the standard is for C, but I really don't like the multiple declarations on one line. There should be a single declaration per line. Its less confusing that way.</p>\n\n<p>You could also put some error handling around the input. What happens if somebody enters \"A\"? Your program would crash. I also think your instruction should be a little more clear. What does \"please enter some numbers.\" really mean?</p>\n\n<p>Minor thing, you forgot to indent the line after the if's at the bottom.</p>\n\n<p>I would also move the reporting to a different function and reduce duplication.</p>\n\n<p>Your code could turn out like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid DisplayResults(char numberType[], int total, int sum);\n\nint main(void) \n{\n int oddCount= 0;\n int evenCount= 0;\n int evenSum = 0;\n int oddSum = 0;\n int userInput;\n\n printf(\"Please enter a number followed by &lt;enter&gt;. Enter \\\"0\\\" to exit: \\n\");\n\n while (((scanf(\"%d\", &amp;userInput)) == 1) &amp;&amp; (userInput != 0))\n {\n\n switch (userInput%2)\n {\n case 0:\n evenCount++;\n evenSum += userInput;\n break;\n\n default:\n oddCount++;\n oddSum += userInput;\n break;\n };\n }\n\n DisplayResults(\"Even\", evenCount, evenSum);\n DisplayResults(\"Odd\", oddCount, oddSum);\n return 0;\n}\n\nvoid DisplayResults(char numberType[], int count, int sum)\n{\n if (total &gt; 0)\n {\n printf(\"%s total: %d, %s average: %d\\n\", numberType, count, numberType, sum/count);\n }\n else\n {\n printf(\"There are no %s numbers!\\n\", numberType);\n }\n}\n</code></pre>\n\n<p>Please excuse me if I have the syntax wrong, I haven't used C in about 20 years.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T00:09:52.150", "Id": "21009", "ParentId": "21007", "Score": "4" } } ]
{ "AcceptedAnswerId": "21009", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:33:53.673", "Id": "21007", "Score": "4", "Tags": [ "c" ], "Title": "Testing numbers using 'switch'" }
21007
<blockquote> <p>Write a program that reads input up to # and reports the number of times that the sequence ei occurs.</p> </blockquote> <p>Is this a decent code?</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int index = 0, combinationTimes = 0, total = 0; char userInput; char wordChar[index]; printf("please enter your input:\n"); while ((userInput = getchar()) != '#') { if (userInput == '\n') continue; wordChar[index] = userInput; index++; total++; } for (index = 1; index &lt; total; index++) { if (wordChar[index] == 'i') { if (wordChar[--index] == 'e') { combinationTimes++; ++index; } } } printf("number of combination is: %d", combinationTimes); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T02:21:29.600", "Id": "33730", "Score": "0", "body": "Posted my original comment as answer because spaces in comments are stupid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T02:40:51.283", "Id": "33731", "Score": "0", "body": "can you say why it dosen't work with this input? i tried it and i see that i have an problem there @BlackSheep" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T03:31:15.947", "Id": "33733", "Score": "0", "body": "Edited original answer to reflect suggested changes. What I suggest there is a good start, but you can definitely improve on the provided code as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:24:14.033", "Id": "33751", "Score": "0", "body": "If you are using the code at the bottom of the answer for anything, I have revised it to fix an edge case I missed last night because it was late." } ]
[ { "body": "<p>Here are some inputs on command line which break your code:</p>\n\n<pre><code>dan@albatross $ gcc -Wall f.c -o f\ndan@albatross $ ./f\nplease enter your input:\nbfiqwb23b r9pu3h2ru23r\n9aisdbfuiasdf\nadsf#asdf\n#\n#\n#\n adsfadsfasdf\n34324!\n^C\n</code></pre>\n\n<p>I assume your program is supposed to terminate at the first <code>#</code>, but notice here that it does not. I have to kill the program to stop it. The shows there is a problem with one of your loops. By seeing the manipulation of the index variable in the second loop, I think it's the problem.</p>\n\n<p><strong>Code Review</strong></p>\n\n<p>First: you do not need to have the line <code>index++</code> inside the loop. Use the single variable total instead. This is a minor thing.</p>\n\n<p>Instead of having a nested if-statement, use an and conditional. And stop decreasing the index variable - that's what causing all those problems. Try this:</p>\n\n<pre><code>for (index = 1; index &lt; total; index++)\n { \n if (wordChar[index] == 'i' &amp;&amp; wordChar[index - 1] == 'e')\n combinationTimes++;\n } \n</code></pre>\n\n<p>However, that is still inefficient code, because you should be processing the input as it is given, not processing it after the last hash. Notice that you are doing <code>length_of_input</code> work at the end, when you could be doing <code>constant</code> work at each step, which is computationally less noticeable to a user. In addition, the array has <code>length_of_input</code> memory overhead, which seems unnecessary here. Consider writing something like this instead:</p>\n\n<pre><code>#define FALSE 0\n#define TRUE 1\n\nint main(void)\n{\n int combinationTimes = 0;\n char userInput;\n short int last_e = FALSE;\n\n printf(\"please enter your input:\\n\");\n\n while ((userInput = getchar()) != '#')\n { \n if (userInput == 'e')\n { \n last_e = TRUE;\n } \n else if (userInput == 'i' &amp;&amp; last_e) \n {\n combinationTimes++;\n last_e = FALSE;\n }\n else\n {\n //this is important, otherwise combinations like 'ite' are counted\n last_e = FALSE;\n }\n } \n\n printf(\"Number of combos: %d\\n\", combinationTimes);\n return 0;\n}\n</code></pre>\n\n<p>Here are some key features:</p>\n\n<ul>\n<li><p>I removed your array, so I have no significant memory overhead. Each char is processed and discarded, one at a time</p></li>\n<li><p>I remove your variables total and index</p></li>\n<li><p>I process the event you care about inside the first for loop, as you read the character</p></li>\n<li><p>I create boolean variables with compiler flags</p></li>\n</ul>\n\n<p>This code also has a lot of room for improvement, but that's left as an exercise...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:19:58.637", "Id": "33750", "Score": "0", "body": "Sorry, it's my first answer. I edited the original answer to make it less... mean... :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:30:01.923", "Id": "33752", "Score": "0", "body": "hah, good thing you did so. C is the first language im learning and im only learning it for 2 weeks, so you could guess positive feedbacks are more appreciate around here ;) @BlackSheep" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T02:23:14.793", "Id": "21011", "ParentId": "21010", "Score": "4" } } ]
{ "AcceptedAnswerId": "21011", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T01:12:22.937", "Id": "21010", "Score": "4", "Tags": [ "c", "io" ], "Title": "Detecting a combination of characters from input" }
21010
<p>Here is a program which keeps track of the longest path in a graph. I think it can be written much better.</p> <pre><code>from Tkinter import * ''' This program tries to compute the longest path (largest number of consecutive edges) currently in the graph at any point. The edges will be labelled as roads, connecting 2 nodes. These edges are undirected. The nodes will not be constrained here, so any start- or end-point of an edge will be called a node. Some nodes will occassionally be called settlements, but it doesn't mean anything special here. ''' class A(): '''The main class, groups all functions.''' def create_roads(self): '''Create the roads that will later be added.''' # first settlement s0 = (100, 100) # second settlement s1 = (100, 300) self._road_index = 0 self._roads = [ # G1 # one way from s0 (s0, (150, 100)), # other way from s0 (s0, (50, 100)), # extend from 150 #((150, 100), (200, 100)), # branch at 150 ((150, 100), (200, 150)), # extend branch #((200, 150), (250, 150)), # extend other side ((50, 100), (100, 150)), # discontinuous site (G2) #(s1, (150, 250)), # extend G2 ((150, 250), (100, 200)), ((100, 200), (50, 150)), # branch off G2 ((150, 250), (200, 250)), ((200, 250), (250, 200)), # join G2 to G1 at endpoints ((50, 150), (100, 150)), # join G2 to G1 at middle ((250, 200), (200, 150)), # another branch off G2 ((200, 250), (250, 250)) ] def draw_paths(self, canvas): '''Draw all the paths as a series of roads. Each path is represented by a different color.''' i = 0 c = ["red", "orange", "purple", "cyan", "green", "grey", "lightgreen", "yellow", "blue"] spacing = 3 for path in self._paths: i += 1 for road_i in range(len(path) - 1): startpt = (path[road_i][0], path[road_i][1] + i * spacing) endpt = (path[road_i + 1][0], path[road_i + 1][1] + i * spacing) self.draw_road(startpt, endpt, canvas, c[i % len(c)]) print "**** Drawing ****" for p in self._paths: print p print "**** End drawing ****" def draw_road(self, v1, v2, canvas, c="red"): '''Draw a road between v1 and v2.''' t = "road" if c == "red" else "path" canvas.create_line(v1[0], v1[1], v2[0], v2[1], fill=c, width=1.5, tags=t) def draw_node(self, v, canvas): '''Draw a node at v.''' r = 10 canvas.create_oval(v[0] + r, v[1] + r, v[0] - r, v[1] - r, fill="black") def draw(self, canvas): '''Draw the path-node system - i.e. the graph.''' for v1, v2 in self._roads: self.draw_road(v1, v2, canvas) self.draw_node(v1, canvas) self.draw_node(v2, canvas) self.draw_paths(canvas) def add_next_path(self, canvas): '''Show the addition of another path.''' if self._road_index == len(self._roads): print "No" else: for item in canvas.find_withtag("path"): canvas.delete(item) self.add_road(*self._roads[self._road_index]) self.draw(canvas) self._road_index += 1 def add_path_buttons(self, canvas): '''Add a button to control addition of new paths.''' f = lambda : self.add_next_path(canvas) self._path_button = Button( self._root, text="Add path", command=f ) # more or less arbitrary placement canvas.create_window(100, 500, window=self._path_button, anchor=S) def print_debug(self, msg): '''If the debug flag is on, print the message.''' if self._debug: print msg def __init__(self, root, debug=True): '''Create a new app.''' # save variables self._root = root self._debug = debug self._path_end = {} # maps endpoints (second coordinate) to path self._path_start = {} # maps startpoints (first coordinate) to path self._paths = [] # list of all paths self._cycles = [] # the list of all paths that are cycles ; currently not used self.create_roads() # everything will be drawn on the canvas c = Canvas(self._root, width=600, height=600) c.pack() self.add_path_buttons(c) # buttons are hooked to the canvas self.draw(c) # draw everything except the buttons def branch(self, branchpt, new_node, path): '''New road is added - road = (branchpt, new_node) path - the existing path, intersecting with road branchpt - the intersection of road and path new_node - the other node in road ''' if path.count(branchpt) == 0: #TODO this should never happen return elif path.count(branchpt) == 2: # means cycle, so gets extra tricky ; not sure what to do here pass i = path.index(branchpt) if i == 0: # insert road at beginning if path[0] in self._path_start and len(self._path_start[path[0]]) &gt; 0: self._path_start[path[0]].remove(path) # remove old starting point if len(self._path_start[path[0]]) == 0: del(self._path_start[path[0]]) else: # should never be the case, because self._path_start should always be synced pass path.insert(0, new_node) # alter the road # add new starting point if new_node not in self._path_start: self._path_start[new_node] = [] self._path_start[new_node].append(path) elif i == len(path) - 1: # means road added at the end self._path_end[path[-1]].remove(path) # remove old ending point # update if len(self._path_end[path[-1]]) == 0: del(self._path_end[path[-1]]) path.append(new_node) # update existing list # update end point if new_node not in self._path_end: self._path_end[new_node] = [] self._path_end[new_node].append(path) else: # somewhere in the middle # first path goes from new_node through branchpt to path[-1] p1 = [new_node] + path[i : ] # second path goes from path[0] through branchpt to new_node p2 = path[: i + 1] + [new_node] # in this case, the original path stays if path[0] == path[-1]: # in the case of a cycle self._new_paths.append(p1 + p2[1:-1]) else: # simple branching self._new_paths.append(p1) self._new_paths.append(p2) def update(self): '''Update the memory with self._new_paths added.''' while len(self._new_paths) &gt; 0: path = self._new_paths.pop() print "Adding path {}".format(path) startpt = path[0] endpt = path[-1] if startpt not in self._path_start: self._path_start[startpt] = [] if endpt not in self._path_end: self._path_end[endpt] = [] self._path_start[startpt].append(path) self._path_end[endpt].append(path) self._paths.append(path) if path[0] == path[-1]: # if I created a new cycle, update cycle list. self._cycles.append(path) def add_road(self, a, b): '''Add a road (a, b) a and b are arbitrarily arranged endpoints representing nodes. Only branch on one node per path so can consistently merge at the end.''' self.print_debug('#' * 50) # dilineate between subsequent iterations self._new_paths = [] added_a = added_b = False for path in self._paths: if a in path and not added_b: # console output self.print_debug("==&gt; {}".format((a, b))) self.print_debug("hit on {}".format(path)) # branch there, signal modified self.branch(a, b, path) added_a = True elif b in path and not added_a: # console output print "==&gt; {}".format((a, b)) print "hit on {}".format(path) # branch there, signal modified self.branch(b, a, path) added_b = True if not added_a and not added_b: self.print_debug("new disjoint: {}".format([a, b])) # helpful console message self._new_paths.append([a, b]) # added it as a disjoint part to the graph if len(self._new_paths) &gt; 0: self.update() if added_a: self.merge(b) # because a is the point connected elif added_b: self.merge(a) # because b is the point connected def can_merge(self, path_1, path_2, mergept): '''Checks if 2 paths can merge with each other. Very basic check.''' try: i_1 = path_1.index(mergept) i_2 = path_2.index(mergept) except ValueError: # mergept not found in one of the lists return False if i_1 == len(path_1) - 1: path_1 = list(reversed(path_1)) if i_2 == len(path_2) - 1: path_2 = list(reversed(path_2)) return path_1[0] == path_2[0] and path_1[1] != path_2[1] def merge(self, mergept): '''mergept is the point of the merge. All roads with an endpoint here are subjects. - we can combine any 2 roads that start from / end at b ''' if mergept not in self._path_end: self._path_end[mergept] = [] if mergept not in self._path_start: self._path_start[mergept] = [] # every road that starts and ends at mergept merge_list = self._path_end[mergept] + self._path_start[mergept] merged = set([]) if len(merge_list) &lt; 2: return # cannot merge a single path else: self.print_debug("**** Starting merger ****") for pi1, path_1 in enumerate(merge_list): for pi2, path_2 in enumerate(merge_list): # join these 2 paths under the right conditions if self.can_merge(path_1, path_2, mergept) and (pi2, pi1) not in merged: merged.add((pi1, pi2)) self.print_debug("Merging {} and {}".format(path_1, path_2)) i_1 = path_1.index(mergept) i_2 = path_2.index(mergept) if i_1 == 0: path_1 = list(reversed(path_1)) if i_2 == len(path_2) - 1: path_2 = list(reversed(path_2)) p = path_1 + path_2[1:] self.print_debug("Added newly merged path {}".format(p)) self._new_paths.append(p) if len(merged) &gt; 0: # delete every path in merge_list for p in merge_list: self._path_start[p[0]].remove(p) self._path_end[p[-1]].remove(p) self._paths.remove(p) self.update() self.print_debug("**** End Merger ****") # do this at the end as cleanup if mergept in self._path_end and len(self._path_end[mergept]) == 0: del(self._path_end[mergept]) if mergept in self._path_start and len(self._path_start[mergept]) == 0: del(self._path_start[mergept]) if __name__ == "__main__": root = Tk() a = A(root) root.mainloop() </code></pre>
[]
[ { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>I didn't understand everything that the code was trying to do. What's the difference between a <em>road</em> and a <em>path</em>? What's going on with all that merging and branching? Is it important, or is it just part of your longest-path-finding algorithm, and could be removed or replaced if you got a better algorithm?</p></li>\n<li><p>Putting all your functions in the same class is usually a sign that the class is doing too many things. Another sign of this is that you haven't managed to find a good name for the class. An easy way to refactor this program would be to have separate classes for the graph and the display.</p></li>\n<li><p>There are <a href=\"http://en.wikipedia.org/wiki/Graph_%28abstract_data_type%29#Representations\" rel=\"nofollow\">several standard ways to represent a graph</a>, and in all of them, the nodes appear as elements in the data structure. But in your representation, nodes only appear in the form of the coordinates of endpoints of edges. This means, for example, that you end up drawing each node multiple times (once for each edge that it is incident to). This representation also makes it hard for you to find connections in the graph.</p>\n\n<p>Switching to a better representation, for example the <a href=\"http://en.wikipedia.org/wiki/Adjacency_list\" rel=\"nofollow\">adjacency list representation</a>, would be a good idea.</p></li>\n<li><p>It's a good idea for your classes to inherit from <code>object</code> so that they are portable between Python 2 and Python 3.</p></li>\n<li><p>Why not make <code>canvas</code> an instance member so that you don't have to pass it around?</p></li>\n<li><p>Code like</p>\n\n<pre><code>c = [\"red\", \"orange\", \"purple\", \"cyan\", \"green\", \"grey\", \"lightgreen\", \"yellow\", \"blue\"]\n</code></pre>\n\n<p>which is the same every time a method is called, could be moved out of the method into the class. Perhaps like this:</p>\n\n<pre><code>_colors = \"red orange purple cyan green grey lightgreen yellow blue\".split()\n</code></pre></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>The code below has separate classes for representing the graph and displaying it. (Since I didn't understand what all that merging and branching code was for, I didn't try to improve it. If it was important, you'll have to figure out how to restore it and make it use the revised data structures.)</p>\n\n<p>The longest path is computed with a simple depth-first search over all paths in the graph. This takes time that's exponential in the size of the graph, but since the <a href=\"http://en.wikipedia.org/wiki/Longest_path_problem\" rel=\"nofollow\">longest path problem</a> is <a href=\"http://en.wikipedia.org/wiki/NP-hard\" rel=\"nofollow\">NP-hard</a>, that's unfortunately the performance you have to live with. (If you were willing to accept a reasonably long path, but not necessarily the longest, then there would be ways to speed this up.)</p>\n\n<pre><code>from collections import defaultdict\nfrom itertools import permutations\nfrom Tkinter import *\n\nclass Graph(object):\n \"\"\"An undirected graph.\"\"\"\n\n def __init__(self):\n # Map from node to set of neighbours.\n self.g = defaultdict(set)\n\n def add_node(self, v):\n \"\"\"Add a node `v`.\"\"\"\n self.g[v].update()\n\n def add_edge(self, v, w):\n \"\"\"Add an undirected edge between `v` and `w`.\"\"\"\n self.g[v].add(w)\n self.g[w].add(v)\n\n def iter_nodes(self):\n \"\"\"Return an iterator over the nodes of the graph.\"\"\"\n return iter(self.g)\n\n def iter_edges(self):\n \"\"\"Return an iterator over the edges of the graph.\"\"\"\n for v in self.g:\n for w in self.g[v]:\n if v &lt; w:\n yield v, w\n\n def longest_path(self):\n \"\"\"Return the longest path in the graph.\"\"\"\n longest = []\n visited = set()\n path = []\n def search(v):\n visited.add(v)\n path.append(v)\n if len(path) &gt; len(longest):\n longest[:] = path[:]\n for w in self.g[v]:\n if w not in visited:\n search(w)\n path.pop()\n visited.remove(v)\n for v in self.g:\n search(v)\n return longest\n\nclass GraphDisplay(object):\n def __init__(self, root, graph, debug=True):\n self._root = root\n self._debug = debug\n self._graph = graph\n self._longest_path = graph.longest_path()\n self._canvas = Canvas(self._root, width=600, height=600)\n self._canvas.pack()\n self.draw()\n\n def draw_edge(self, v, w, fill='red'):\n self._canvas.create_line(v[0], v[1], w[0], w[1], fill=fill, width=1.5)\n\n def draw_node(self, v, r = 10, fill='black'):\n self._canvas.create_oval(v[0] + r, v[1] + r, v[0] - r, v[1] - r,\n fill=fill)\n\n def draw(self):\n for v, w in self._graph.iter_edges():\n self.draw_edge(v, w)\n for v, w in zip(self._longest_path, self._longest_path[1:]):\n self.draw_edge(v, w, fill='green')\n for v in self._graph.iter_nodes():\n self.draw_node(v)\n\ndef example_graph():\n edges = [\n ((100, 100), (150, 100)),\n ((100, 100), ( 50, 100)),\n ((150, 100), (200, 150)),\n (( 50, 100), (100, 150)),\n ((150, 250), (100, 200)),\n ((100, 200), ( 50, 150)),\n ((150, 250), (200, 250)),\n ((200, 250), (250, 200)),\n (( 50, 150), (100, 150)),\n ((250, 200), (200, 150)),\n ((200, 250), (250, 250)),\n ]\n g = Graph()\n for v, w in edges:\n g.add_edge(v, w)\n return g\n\nif __name__ == \"__main__\":\n root = Tk()\n GraphDisplay(root, example_graph())\n root.mainloop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:14:36.797", "Id": "33749", "Score": "0", "body": "A path is a sequence of nodes, not necessarily 2. Thus it differs from an edge by being \"longer\". I agree with your other criticisms. I think an adjacency list is a good idea, as is moving the drawing portion to a different class, and storing the nodes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:01:47.653", "Id": "21022", "ParentId": "21014", "Score": "3" } } ]
{ "AcceptedAnswerId": "21022", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T03:10:12.670", "Id": "21014", "Score": "3", "Tags": [ "python", "graph", "tk" ], "Title": "Evaluating longest path" }
21014
<p>I'm using the following technologies: Google App Engine, GAE Datastore, Struts2. <code>Common lang</code> java library were also used.</p> <p>Because of the limitation on aggregation for datastore, I'm using <a href="http://jagg.sourceforge.net" rel="nofollow">jagg</a> for aggregation on List of <code>Profile</code> for some sort of report.</p> <p><code>Profile</code> object have basic properties like email, name, gender, country, dateCreated, etc.</p> <p>For <code>Chart Report</code> I have this:</p> <pre><code>public class ChartReport { private Date date = null; private String country = null; private Map&lt;String, Integer&gt; count = null; //by gender public ChartReport() { Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;(); map.put("m", 0); map.put("f", 0); map.put(null, 0); count = map; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Map&lt;String, Integer&gt; getCount() { return count; } public void setCount(Map&lt;String, Integer&gt; count) { this.count = count; } } </code></pre> <p>I used <code>map</code> for count so that report will have different count for <code>male</code>, <code>female</code> and <code>null</code>.</p> <p>For my Struts2 action, I have this:</p> <pre><code> if ( dateFrom != null &amp;&amp; dateTo != null ) list = access.getNewProfiles(dateFrom, dateTo); //remove timestamp if ( type.equals("Daily")){ for(Profile p: list) p.setDateCreated( DateUtils.truncate(p.getDateCreated(), Calendar.DATE) ); }else{ for(Profile p: list) p.setDateCreated( DateUtils.truncate(p.getDateCreated(), Calendar.MONTH) ); } List&lt;String&gt; properties = new ArrayList&lt;String&gt;(); properties.add("dateCreated"); properties.add("gender"); List&lt;Aggregator&gt; aggregators = new ArrayList&lt;Aggregator&gt;(); aggregators.add(new CountAggregator("*")); List&lt;AggregateValue&lt;Profile&gt;&gt; aggValues = Aggregations.groupBy( list, properties, aggregators); Profile profile = null; ChartReport report = null; reportList = new ArrayList&lt;ChartReport&gt;(); Date date = null; for (AggregateValue&lt;Profile&gt; aggValue : aggValues ){ profile = aggValue.getObject(); Aggregator aggregator = aggregators.get(0); //only one aggregator if ( date == null || ! date.equals( profile.getDateCreated() ) ){ report = new ChartReport(); report.setDate( profile.getDateCreated() ); report.getCount().put(profile.getGender(), Integer.parseInt(String.valueOf(aggValue.getAggregateValue(aggregator)))); reportList.add(report); }else{ report.getCount().put(profile.getGender(), Integer.parseInt(String.valueOf(aggValue.getAggregateValue(aggregator)))); date = profile.getDateCreated(); continue; } date = profile.getDateCreated(); } </code></pre> <p>The condition <code>( date == null || ! date.equals( profile.getDateCreated() ) )</code> was used for grouping purposes. The same <code>dateCreated</code> value will be in one group.</p> <p>Everything works perfectly, but I need suggestions, comments, and feedback for my code. Can I improve its performance in terms of speed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:42:24.197", "Id": "33794", "Score": "0", "body": "You may want to look into [JodaTime](http://joda-time.sourceforge.net/), which is considered a superior implementation than the standard Java handling of date/time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T19:52:08.810", "Id": "33855", "Score": "0", "body": "... It just occurred to me to ask - where is this information being stored? If you have a backend db, that will almost certainly be the fastest way to do this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:50:03.270", "Id": "33861", "Score": "0", "body": "it's stored in AppEngine datastore w/c don't allow aggregation query like count, avg, sum, etc." } ]
[ { "body": "<blockquote>\n <p>Can I improve it's performance in terms of speed?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>As there is no specific value in my one word answer, the same does apply to your question for me. Are there any requirements for speed? If no, then just do not take care about it and save your time. If yes, have your profiled it against the requirements?</p>\n\n<p>Some small things:</p>\n\n<pre><code>private Map&lt;String, Integer&gt; count = null; //by gender\n</code></pre>\n\n<p>Well, instead of the comment, you could write:</p>\n\n<pre><code>private Map&lt;String, Integer&gt; mapGenderToCount = null;\n</code></pre>\n\n<p>and save the comment, prevent everyone from reading it all the time and save it from updates (which noone will take care of)</p>\n\n<hr>\n\n<pre><code>map.put(null, 0);\n</code></pre>\n\n<p>This was unexpected. What kind of biological or theoretical gender is null?</p>\n\n<hr>\n\n<pre><code>Map&lt;String, Integer&gt; map = new HashMap&lt;String, Integer&gt;();\nmap.put(\"m\", 0);\nmap.put(\"f\", 0);\nmap.put(null, 0);\ncount = map;\n</code></pre>\n\n<p>You could directly write:</p>\n\n<pre><code>Map&lt;String, Integer&gt; count = new HashMap&lt;String, Integer&gt;();\ncount.put(\"m\", 0);\ncount.put(\"f\", 0);\ncount.put(null, 0);\n</code></pre>\n\n<p>There is no difference in your case.</p>\n\n<hr>\n\n<pre><code>public void setCount(Map&lt;String, Integer&gt; count) {\n this.count = count;\n}\n</code></pre>\n\n<p>Is there a specific need for this method? Otherwise I would remove it. I would not provide methods to change my internal data structure. I would avoid the <code>getCount</code>, too.<br>\nInstead of</p>\n\n<pre><code>public Map&lt;String, Integer&gt; getCount() {\n return count;\n}\n</code></pre>\n\n<p>You could provide a method</p>\n\n<pre><code>public boolean increaseCount(String gender, int count) {\n ...;\n return if successful (only if needed, otherwise void)\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public boolean increaseFemale(int count) {\n ...;\n return if successful (only if needed, otherwise void)\n}\n+male\n</code></pre>\n\n<hr>\n\n<p>You could replace the String-Key for the <code>HasMap</code> by enum <code>Gender</code>:</p>\n\n<pre><code>public enum Gender {\n MALE, FEMALE, UNKNOWN;\n}\n\nMap&lt;Gender, Integer&gt; mapGenderToCount\n</code></pre>\n\n<hr>\n\n<pre><code>if ( type.equals(\"Daily\")){\n</code></pre>\n\n<p>Looks like an use case for enum, too.Then you could remove the if/else and write something like:</p>\n\n<pre><code>for(Profile p: list)\n p.setDateCreated( DateUtils.truncate(p.getDateCreated(), date.getUnit()) );\n</code></pre>\n\n<hr>\n\n<p>More a personal preference. Instead of:</p>\n\n<pre><code> final List&lt;String&gt; properties = new ArrayList&lt;&gt;();\n properties.add(\"dateCreated\");\n properties.add(\"gender\");\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code> final List&lt;String&gt; properties = Arrays.asList(\"dateCreated\", \"gender\");\n //or if you need mutability\n final List&lt;String&gt; properties = new ArrayList&lt;&gt;(Arrays.asList(\"dateCreated\", \"gender\"));\n</code></pre>\n\n<hr>\n\n<pre><code>Profile profile = null;\n</code></pre>\n\n<p>If you do not need variables outside a loop, do not declare them outside of your loop. Some people will argue with a speed argument to declare them outside, but as I said, just prefer readability over premature optimization.</p>\n\n<hr>\n\n<pre><code>Aggregator aggregator = aggregators.get(0); //only one aggregator\n</code></pre>\n\n<p>Then remove the list?</p>\n\n<hr>\n\n<p>This:</p>\n\n<pre><code> if ( date == null || ! date.equals( profile.getDateCreated() ) ){\n report = new ChartReport();\n report.setDate( profile.getDateCreated() );\n report.getCount().put(profile.getGender(), Integer.parseInt(String.valueOf(aggValue.getAggregateValue(aggregator))));\n reportList.add(report);\n }else{\n report.getCount().put(profile.getGender(), Integer.parseInt(String.valueOf(aggValue.getAggregateValue(aggregator))));\n date = profile.getDateCreated();\n continue;\n }\n\n date = profile.getDateCreated();\n</code></pre>\n\n<p>could be simplified to:</p>\n\n<pre><code> if ( date == null || ! date.equals( profile.getDateCreated() ) ){\n report = new ChartReport();\n report.setDate( profile.getDateCreated() );\n reportList.add(report);\n }\n report.getCount().put(profile.getGender(), Integer.parseInt(String.valueOf(aggValue.getAggregateValue(aggregator))));\n date = profile.getDateCreated();\n</code></pre>\n\n<hr>\n\n<p>In the end, you could come up with something like this:</p>\n\n<pre><code>if ( dateFrom != null &amp;&amp; dateTo != null )\n list = access.getNewProfiles(dateFrom, dateTo);\n\n//remove timestamp\np.setDateCreated( DateUtils.truncate(p.getDateCreated(), type.getUnit()) );\n\nAggregator countAggregator = new CountAggregator(\"*\");\nList&lt;AggregateValue&lt;Profile&gt;&gt; listAggregateValues = Aggregations.groupBy(\n list,\n Arrays.asList(\"dateCreated\", \"gender\"),\n Arrays.asList(countAggregator)\n );\n\nreportList = new ArrayList&lt;ChartReport&gt;();\nDate date = null;\nChartReport report = null;\n\nfor (AggregateValue&lt;Profile&gt; listAggregateValuesItem : listAggregateValues){ // perhaps extract loop to own method with good name\n Profile profile = listAggregateValuesItem.getObject();\n\n if ( date == null || ! date.equals( profile.getDateCreated() ) ){\n report = new ChartReport();\n report.setDate( profile.getDateCreated() );\n reportList.add(report);\n }\n\n report.increaseCount(profile.getGender(), Integer.parseInt(listAggregateValuesItem.getAggregateValue(countAggregator).toString()));\n date = profile.getDateCreated();\n}\n</code></pre>\n\n<hr>\n\n<p>Other than that, I do not like to use too much external libraries. In particular fancy ones. They make code hard to read for other people and you need some trust in what is happening. But this is a strongly personal and subject meaning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T19:50:57.643", "Id": "33854", "Score": "0", "body": "I'm assuming a `null` gender is 'unspecified' - ie it's part of a web form, and some users just won't give that information." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:26:52.583", "Id": "21030", "ParentId": "21015", "Score": "3" } }, { "body": "<p>The rules of optimization may be helpful here:</p>\n\n<ol>\n<li>Don't do it.</li>\n<li>Don't do it, <em>yet</em>.</li>\n<li>Profile before optimizing.</li>\n</ol>\n\n<blockquote>\n <p>We should forget about small efficiencies, say about 97% of the time:\n premature optimization is the root of all evil.\n - Donald Knuth (who attributed the observation to C.A.R Hoare)</p>\n</blockquote>\n\n<p>Above from <a href=\"http://c2.com/cgi/wiki?RulesOfOptimization\" rel=\"nofollow\">http://c2.com/cgi/wiki?RulesOfOptimization</a> (the original wiki).</p>\n\n<p>Also, I always wrap the contents of all conditionals and loops in {}'s. This increases readability and reduces the chance of adding another line and mistaking that it is being executed inside of a loop or conditional.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:30:38.943", "Id": "21044", "ParentId": "21015", "Score": "2" } } ]
{ "AcceptedAnswerId": "21030", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T04:46:26.477", "Id": "21015", "Score": "1", "Tags": [ "java", "google-app-engine", "struts2" ], "Title": "Aggregation on List" }
21015
<p>I am attempting to refactor my app using the MVC paradigm.</p> <p>My site displays charts. The URLs are of the form</p> <ul> <li><code>app.com/category1/chart1</code></li> <li><code>app.com/category1/chart2</code></li> <li><code>app.com/category2/chart1</code></li> <li><code>app.com/category2/chart2</code></li> </ul> <p>I am using Apache Rewrite to route all requests to <code>index.php</code>, and so am doing my URL parsing in PHP.</p> <p>I am working on the enduring task of adding an <code>active</code> class to my navigation links when a certain page is selected. Specifically, I have both category-level navigation, and chart-level sub-navigation. My question is, what is the best way to do this while staying in the spirit of MVC?</p> <p>Before my refactoring, since the nav was getting relatively complicated, I decided to put it into an array:</p> <pre><code>$nav = array( '25th_monitoring' =&gt; array( 'title' =&gt; '25th Monitoring', 'charts' =&gt; array( 'month_over_month' =&gt; array( 'default' =&gt; 'month_over_month?who=total&amp;deal=loan&amp;prev='.date('MY', strtotime('-1 month')).'&amp;cur='.date('MY'), 'title' =&gt; 'Month over Month'), 'cdu_tracker' =&gt; array( 'default' =&gt; 'cdu_tracker', 'title' =&gt; 'CDU Tracker') ) ), 'internet_connectivity' =&gt; array( 'title' =&gt; 'Internet Connectivity', 'default' =&gt; 'calc_end_to_end', 'charts' =&gt; array( 'calc_end_to_end' =&gt; array( 'default' =&gt; 'calc_end_to_end', 'title' =&gt; 'calc End to End'), 'quickcontent_requests' =&gt; array( 'default' =&gt; 'quickcontent_requests', 'title' =&gt; 'Quickcontent Requests') ) ) ); </code></pre> <p>Again, I need to know both the current category and current chart being accessed. My main nav was</p> <pre><code>&lt;nav&gt; &lt;ul&gt; &lt;?php foreach ($nav as $category =&gt; $category_details): ?&gt; &lt;li class='&lt;?php $current_category == $category ? null : 'active'; ?&gt;'&gt; &lt;a href="&lt;?php echo 'http://' . $_SERVER['SERVER_NAME'] . '/' . $category . '/' . reset(reset($category_details['monitors'])); ?&gt;"&gt;&lt;?php echo $category_details['title']; ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre> <p>and the sub-nav was something similar, checking for current_chart instead of current_category.</p> <p>Before, during parsing, I was exploding <code>$_SERVER['REQUEST_URI']</code> by <code>/</code>, and breaking the pieces up into <code>$current_category</code> and <code>$current_monitor</code>. I was doing this in index.php. Now, I feel this is not in the spirit of the font controller. From references like <a href="http://symfony.com/doc/current/book/from_flat_php_to_symfony2.html#creating-the-front-controller" rel="nofollow">Symfony 2's docs</a>, it seems like each route should have a controller. But then, I find myself having to define the current category &amp; monitor multiple times, and either within the template files themselves (which doesn't seem to be in the spirit of MVC), or in an arbitrary function in the model.</p> <p>What is the best practice here?</p> <p>Update: Here's what my front controller looks like:</p> <pre><code>// index.php &lt;?php // Load libraries require_once 'model.php'; require_once 'controllers.php'; // Route the request $uri = str_replace('?'.$_SERVER['QUERY_STRING'], '', $_SERVER['REQUEST_URI']); if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; (!empty($_GET)) &amp;&amp; $_GET['action'] == 'get_data') { $function = $_GET['chart'] . "_data"; $dataJSON = call_user_func($function); header('Content-type: application/json'); echo $dataJSON; } elseif ( $uri == '/' ) { index_action(); } elseif ( $uri == '/25th_monitoring/month_over_month' ) { month_over_month_action(); } elseif ( $uri == '/25th_monitoring/cdu_tracker' ) { cdu_tracker_action(); } elseif ( $uri == '/internet_connectivity/intexcalc_end_to_end' ) { intexcalc_end_to_end_action(); } elseif ( $uri == '/internet_connectivity/quickcontent_requests' ) { quickcontent_requests_action(); } else { header('Status: 404 Not Found'); echo '&lt;html&gt;&lt;body&gt;&lt;h1&gt;Page Not Found&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;'; } ?&gt; </code></pre> <p>It seems like when <code>month_over_month_action()</code> is called, for instance, since the controller knows the <code>current_chart</code> is <code>month_over_month</code>, it should just pass that along. This is where I'm getting tripped up.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:41:43.807", "Id": "33826", "Score": "0", "body": "it is ideal situation when you need 1-to-1 route-to-controller. Real life case can be more complicated and I would use one controller to handle this identical operations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T23:17:24.423", "Id": "33871", "Score": "0", "body": "You reference Symfony2 documentation. Are you using Symfony2?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T03:05:56.287", "Id": "33883", "Score": "0", "body": "I started, but then decided I should step back and really understand OOP first. I'm trying to figure out the routing stuff first, since I'm going back and refactoring my projects, and that seems like me to be the first step." } ]
[ { "body": "<p>You could try urls like this:</p>\n\n<pre><code>/category/1/chart/1\n/category/1/chart/2\n/category/2/chart/1\n</code></pre>\n\n<p>Where your application controller structure looks like this:</p>\n\n<pre><code>+-Application/\n +-Category/\n +-Controller/\n +-ChartController.php\n</code></pre>\n\n<p>You could think of \"Category\" as a module (or in Symfony, a bundle).</p>\n\n<p>The route pattern would be: <code>/category/{category}/chart/{chart}</code>\nand ChartController might look like this:</p>\n\n<pre><code>class ChartController\n{\n showAction($category, $chart)\n {\n //look up the category and chart to display\n }\n}\n</code></pre>\n\n<p>Have a look at the <a href=\"http://symfony.com/doc/current/book/routing.html\" rel=\"nofollow\">symfony2 routing documentation</a>. Also, symfony2's routing is a <a href=\"https://github.com/symfony/Routing\" rel=\"nofollow\">stand alone routing component</a> that you could use in your index.php/front controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T18:07:58.133", "Id": "33919", "Score": "0", "body": "I have built something else that looks like this, but I'd like to have some more flexibility in my urls. Ultimately, I just want to know the right way to do it, in a way that is robust." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T03:47:52.600", "Id": "21093", "ParentId": "21016", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T06:58:38.633", "Id": "21016", "Score": "2", "Tags": [ "php", "mvc", "url-routing" ], "Title": "Routing, Navigation and State in MVC" }
21016
<p>I want to perform standard additive carry on a vector. The base is a power of 2, so we can swap modulus for bitwise AND.</p> <pre><code>def carry(z,direction='left',word_size=8): v = z[:] mod = (1&lt;&lt;word_size) - 1 if direction == 'left': v = v[::-1] accum = 0 for i in xrange(len(v)): v[i] += accum accum = v[i] &gt;&gt; word_size v[i] = v[i] &amp; mod print accum,v if direction == 'left': v = v[::-1] return accum,v </code></pre> <p>Is there any way to make this function even tinier? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:30:16.583", "Id": "33753", "Score": "0", "body": "It would be very handy if you include some `assert`s (3 ó 4) so people can test their refactors easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:53:27.187", "Id": "33755", "Score": "0", "body": "Good point. I will." } ]
[ { "body": "<p>I got it:</p>\n\n<pre><code>def carry2(z,direction='left',word_size=8):\n x = z[:]\n v = []\n mod = (1&lt;&lt;word_size) - 1\n if direction == 'left': x.reverse()\n def cu(a,n):\n v.append((a+n)&amp;mod)\n return (a+n) &gt;&gt; word_size\n accum = reduce(cu,x,0)\n if direction == 'left': v.reverse()\n return accum,v\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:34:28.187", "Id": "33754", "Score": "1", "body": "You are clearly stuck in the imperative paradigm, that's why the code is so verbose (and hard to understand). Check http://docs.python.org/2/howto/functional.html and google for \"python functional programming\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T08:56:05.947", "Id": "33803", "Score": "0", "body": "Thanks! I'm getting started. My latest code has a lot more generators, lambdas and functional style...but I am just getting started." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T10:13:25.350", "Id": "21020", "ParentId": "21019", "Score": "0" } }, { "body": "<ol>\n<li><p>Your code has a lot of copying in it. In the default case (where <code>direction</code> is <code>left</code>) you copy the array three times. This seems like a lot. There are various minor improvements you can make, for example instead of</p>\n\n<pre><code>v = v[::-1]\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>v.reverse()\n</code></pre>\n\n<p>which at least re-uses the space in <code>v</code>.</p>\n\n<p>But I think that it would be much better to reorganize the whole program so that you store your bignums the other way round (with the least significant word at the start of the list), so that you can always process them in the convenient direction.</p></li>\n<li><p>The parameters <code>direction</code> and <code>word_size</code> are part of the description of the data in <code>z</code>. So it would make sense to implement this code as a class to keep these values together. And then you could ensure that the digits always go in the convenient direction for your canonicalization algorithm.</p>\n\n<pre><code>class Bignum(object):\n def __init__(self, word_size):\n self._word_size = word_size\n self._mod = 2 ** word_size\n self._digits = []\n\n def canonicalize(self, carry = 0):\n \"\"\"\n Add `carry` and canonicalize the array of digits so that each\n is less than the modulus.\n \"\"\"\n assert(carry &gt;= 0)\n for i, d in enumerate(self._digits):\n carry, self._digits[i] = divmod(d + carry, self._mod)\n while carry:\n carry, d = divmod(carry, self._mod)\n self._digits.append(d)\n</code></pre></li>\n<li><p>Python already has built-in support for bignums, anyway, so what exactly are you trying to do here that can't be done in vanilla Python?</p>\n\n<p>Edited to add: I see from your comment that I misunderstood the context in which this function would be used (so always give us the context!). It's still the case that you could implement what you want using Python's built-in bignums, for example if you represented your key as an integer then you could write something like:</p>\n\n<pre><code>def fold(key, k, word_size):\n mod = 2 ** (k * word_size)\n accum = 0\n while key:\n key, rem = divmod(key, mod)\n accum += rem\n return accum % mod\n</code></pre>\n\n<p>but if you prefer to represent the key as a list of words, then you could still implement the key-folding operation directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import izip_longest\n\nclass WordArray(object):\n def __init__(self, data = [], word_size = 8):\n self._word_size = word_size\n self._mod = 1 &lt;&lt; word_size\n self._data = data\n\n def fold(self, k):\n \"\"\"\n Fold array into parts of length k, add them with carry, and return a\n new WordArray. Discard the final carry, if any.\n \"\"\"\n def folded():\n parts = [xrange(i * k, min((i + 1) * k, len(self._data))) \n for i in xrange((len(self._data) + 1) // k)]\n carry = 0\n for ii in izip_longest(*parts, fillvalue = 0):\n carry, z = divmod(sum(self._data[i] for i in ii) + carry, self._mod)\n yield z\n return WordArray(list(folded()), self._word_size)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:04:28.820", "Id": "33756", "Score": "0", "body": "Thanks a lot. I will make my way through it. Just quickly the objective is not bignum. I fold an array into parts of length k and add these together, but I preserve the length k, so I discard any carry that falls off one end. It's a mixing step in a key scheduling part of a crypto." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:32:41.510", "Id": "33758", "Score": "0", "body": "Your approach reminded me of this: http://pyvideo.org/video/880/stop-writing-classes 'the signature of *this shouldn't be a class* is that it has two methods, one of which is `__init__`, anytime you see this you should think \"hey, maybe I only need that one method!\"'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:35:26.843", "Id": "33759", "Score": "1", "body": "@Jaime: it should be clear, I hope, that my classes aren't intended to be complete. I believe that the OP has more operations that he hasn't told us about, that in a complete implementation would become methods on these classes. (Do you think I need to explain this point?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T08:59:44.737", "Id": "33804", "Score": "0", "body": "Had a closer, look @GarethRees -- that's awesome. I really like that. Very concise on the loops in the BigNum class. Looking at the next part now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:04:06.150", "Id": "33805", "Score": "0", "body": "You understood me perfectly on the second part. I am pretty shocked since I gave just a tiny description. That is really clever, too. You are amazing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:38:32.257", "Id": "33812", "Score": "0", "body": "Thanks for the edit. I generally write `//` for integer (floor) division so that code is portable between Python 2 and Python 3." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:01:20.173", "Id": "21029", "ParentId": "21019", "Score": "2" } }, { "body": "<p>Preliminary remarks :</p>\n\n<ul>\n<li>Functional idioms and imperative mutations doesn't play well (except when they do. Cf Scala). Here, both FP and Python lovers will likely be lost !</li>\n<li>Since there is exactly 2 possible directions, use a Boolean. It will prevent typo (trying to pass 'Left' for instance).</li>\n<li>Extract the main computation to a dedicated function. First benefice : you won't have to test for direction twice, which is error prone.</li>\n<li>(1st version) : instead of copying + updating via index (awkward), generate a brand new sequence.</li>\n</ul>\n\n<p>That's an interesting question, since it requires both folding (to propagate the carry) and mapping from updated values (to apply <code>mod</code>, ie get the less significant bits). \nSince it's not that common, I suggest to stick with a standard Python approach. Don't force an idiom if it obfuscates.</p>\n\n<pre><code>def carry_from_left(z, word_size):\n mod = (1&lt;&lt;word_size) - 1\n res = []\n acc = 0\n for a in z :\n tot = a + acc\n res.append(tot &amp; mod)\n acc = tot &gt;&gt; word_size\n return (acc, res)\n\ndef carry(z, left_to_right = False, word_size=8):\n if left_to_right :\n return carry_from_left(z, word_size)\n else:\n acc, res = carry_from_left(reversed(z), word_size)\n res.reverse() #inplace. Nevermind, since it's a brand new list.\n return (acc, res)\n</code></pre>\n\n<p>Now, if this \"map+fold\" pattern occurs frequently, you can abstract it.</p>\n\n<pre><code>def fold_n_map (f, l, acc):\n \"\"\" Apply a function (x, acc) -&gt; (y, acc') cumulatively.\n Return a tuple consisting of folded (reduced) acc and list of ys.\n TODO : handle empty sequence, optional initial value, etc,\n in order to mimic 'reduce' interface\"\"\"\n res = []\n for x in l :\n y, acc = f(x, acc)\n res.append(y)\n return acc, res\n\ndef carry_fold_left(z, word_size):\n mod = (1&lt;&lt;word_size) - 1\n #Nearly a one-liner ! Replace lambda by named function for your Python fellows.\n return fold_n_map(lambda x, acc: ((x+acc) &amp; mod, (x+acc) &gt;&gt; word_size), z, 0)\n\ndef carry(z, left_to_right = False, word_size=8):\n #idem\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T02:21:37.147", "Id": "33880", "Score": "0", "body": "Cool, I like that. *Especially* the abstraction of the pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T20:51:17.997", "Id": "21076", "ParentId": "21019", "Score": "1" } } ]
{ "AcceptedAnswerId": "21029", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T09:46:03.803", "Id": "21019", "Score": "2", "Tags": [ "python", "converting" ], "Title": "Convert carry-add loop to a map or reduce to one-liner" }
21019
<p>My task is:</p> <blockquote> <p>Write a program that requests the hours worked in a week and then prints the gross pay, the taxes, and the net pay. Assume the following:</p> <ol> <li>Basic pay rate = $10.00/hr</li> <li>Overtime (in excess of 40 hours) = time and a half</li> <li>Tax rate: 15% of the first $300 <ul> <li>20% of the next $150</li> <li>25% of the rest</li> </ul></li> </ol> </blockquote> <p>Is my code way too long and complicated for that?</p> <pre><code>#include &lt;stdio.h&gt; #define PAYRATE 10 //basic pay rate per hour #define OVERTIME 15 //in excess of 40 hours a week int NetPay(int hours); int main() { int userWeeklyHours; printf("Please enter your total weekly working hours: \n"); scanf("%d", &amp;userWeeklyHours);// get the user weekly hours NetPay(userWeeklyHours); return 0; } int NetPay(int hours)// implementing the function to calculate total pay, total taxes, and net pay { int firstRate, secondRate, restOfRate, secondAmount, rest, payAfterTax, payedBeforeTax, overHours; if (hours &gt; 40) { overHours = hours - 40; payedBeforeTax = (40 * PAYRATE) + (overHours * OVERTIME); } else payedBeforeTax = hours * PAYRATE;//defining the user first paycheck before taxes if (payedBeforeTax &lt;= 300)//paying only first rate case { firstRate = payedBeforeTax*0.15; payAfterTax =payedBeforeTax - firstRate; printf("your total gross is %d, your taxes to pay are %d, your net pay is %d", payedBeforeTax, firstRate, payAfterTax); } else if (payedBeforeTax &gt; 300 &amp;&amp; payedBeforeTax &lt;= 450)//paying first and second rate { secondAmount = payedBeforeTax - 300; firstRate = (payedBeforeTax - secondAmount) * 0.15; secondRate = secondAmount * 0.20; payAfterTax = payedBeforeTax - (firstRate + secondRate); printf("your total gross is %d, your taxes to pay are %d, your net pay is %d", payedBeforeTax, firstRate + secondRate, payAfterTax); } else if (payedBeforeTax &gt; 450)// paying all rates { rest = payedBeforeTax - 450; secondAmount = (payedBeforeTax - 300) - rest; firstRate = (payedBeforeTax - (rest + secondAmount)) * 0.15; secondRate = secondAmount * 0.20; restOfRate = rest * 0.25; payAfterTax = payedBeforeTax - (firstRate + secondRate + restOfRate); printf("your total gross is %d, your taxes to pay are %d, your net pay is %d", payedBeforeTax, firstRate + secondRate + restOfRate, payAfterTax); } return payAfterTax; } </code></pre>
[]
[ { "body": "<p>I'd start extracting some more functions.</p>\n\n<p>What about decomposing</p>\n\n<pre><code>int NetPay(int hours){\n int payedBeforeTaxes = payedBeforeTaxes(hours);\n return applyTaxes(payedBeforeTaxes);\n}\n\nint payedBeforeTaxes(hours){\n return regularPay(hours) + overtimePay(hours);\n}\n\nint applyTaxes(int amountBeforeTaxes){\n int firstRateTaxes = applyFirstRate(amountBeforeTaxes);\n int secondRateTaxes = applySecondRate(amountBeforeTaxes);\n int thirdRateTaxes = applyThirdRate(amountBeforeTaxes);\n return amountBeforeTaxes - firstRateTaxes -\n secondRateTaxes - thirdRateTaxes;\n}\n</code></pre>\n\n<p>At this point you just need to implement the functions with the appropriate code.\nYou'll notice that with this structure each function only does one thing and it will be much simpler and clearer.</p>\n\n<p>Alternatively you can replace your apply taxes introducing an array of `(rate, threshold).\nYou will have to loop through the array, and at each step compute the amount you have to apply that tax rate and the associated tax amount.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:08:03.253", "Id": "33770", "Score": "1", "body": "+1 for separating regular/overtime pay and separating the rates. It's always better to wrap the solution around the problem than the other way around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T14:01:56.050", "Id": "359704", "Score": "0", "body": "(My favourite names probably included `grossPay()` and `taxes()`.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:37:34.907", "Id": "21028", "ParentId": "21027", "Score": "3" } }, { "body": "<p>Your code is not that complicated but a bit long.\nI'm going through the same exercises right now and I came up with a more compact solution. In my opinion, extra functions are redundant.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define BASIC 10.0 // basic payrate\n#define OVERTIME 15.0 // overtime payrate in excess of 40 hours\n#define RATE1 0.15 // taxrate of the first $300\n#define RATE2 0.2 // taxrate of the next $150\n#define RATE3 0.25 // taxrate of the rest\n\nint main(void)\n{\n float gross, taxes, net;\n int hour;\n\nwhile(scanf(\"%d\", &amp;hour) == 1) //quits if no int or more than 1 int entered\n{\n // if gross is &lt;= 400\n if ((gross = hour * BASIC) &lt;= 400)\n {\n if (gross &lt;= 300.0)\n taxes = gross * RATE1;\n else\n taxes = (300 * RATE1) + ((gross - 300) * RATE2);\n }\n\n // if gross is &lt;= 450\n else if ((gross = ((40 * BASIC) + ((hour - 40) * OVERTIME)) &lt;= 450))\n taxes = (300 * RATE1) + ((gross - 300) * RATE2);\n\n // if gross is &gt; 450\n else\n taxes = (300 * RATE1) + (150 * RATE2) + ((gross - 450) * RATE3);\n\n net = gross - taxes;\n printf(\"GROSS: %0.2f\\nTAXES: %0.2f\\nNET: %0.2f\\n\", gross, taxes, net);\n}\nprintf(\"DONE\\n\");\nreturn 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T09:47:41.720", "Id": "359685", "Score": "0", "body": "(Welcome to CR!) `extra functions are redundant` please refer explicitly to part of the question. `going through the same exercises right now` might better be a comment to your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T10:38:26.190", "Id": "359687", "Score": "0", "body": "I explicitly referred to part of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T11:36:01.403", "Id": "359690", "Score": "0", "body": "*Which `extra functions`* are you referring to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T13:48:48.017", "Id": "359702", "Score": "0", "body": "I referred to the only extra function the OP used, namely the NetPay function. The excercise is simple and creating extra functions is an overkill imo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T13:59:55.897", "Id": "359703", "Score": "0", "body": "`referred to the only extra function the OP used, namely the NetPay function` well, *without naming* `NetPay()`, `extra` is not the same in everyone's eyes: see [mariosangiorgio's procedural decomposition](https://codereview.stackexchange.com/a/21028/93149), the comment below it and the votes for each answer. (`extra functions` *might* even have meant *features not in the requirement specification*.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T14:03:07.770", "Id": "359705", "Score": "0", "body": "well, it's logical that I was answering the OPs question, isn't it?\nIf I was to comment about others, I would mention them.\nBut thanks anyways:)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T08:40:41.307", "Id": "188314", "ParentId": "21027", "Score": "1" } } ]
{ "AcceptedAnswerId": "21028", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:16:20.383", "Id": "21027", "Score": "2", "Tags": [ "c", "finance" ], "Title": "Calculate weekly net pay" }
21027
<p>I am working on a webforms project using c#/aspx/jquery. I'm not sure where to handle my <code>Onclick</code>. Both options (doing it in C# or jquery) seem feasible. Which would be better practice?</p> <p>Here is the scenario:</p> <p>I want to build a <code>checkbox</code> which will toggle a <code>textbox's textmode</code>, altering it between Password and SingleLine.</p> <p>Currently, I have this following code for my markup since I am currently handling it in C#:</p> <pre><code>&lt;asp:Checkbox ID="CheckBox1" OnCheckedChanged="CheckBox1_OnCheckedChanged"/&gt; </code></pre> <p>The code:</p> <pre><code>protected virtual void OnCheckedChange(EventArgs e) { If (CheckBox1.TextMode == TextMode.Password) CheckBox1.TextMode = TextMode.SingleLine; else CheckBox1.TextMode = TextMode.Password; } </code></pre> <p>The use case of this is: A user is entering his password. On the same page, he may choose to keep the password hidden or not by checking the checkbox.</p>
[]
[ { "body": "<p>You cannot change the type of the input field on client side in some or all browsers. I would create a custom hiding method in Javascript and leave the input type in text mode (SingleLine), but maybe this has some drawbacks in security.</p>\n\n<p>Other solution is to remove the original input and create a new one on the fly with Javascipt but i think not all browser will let you to read out the value of a password type input.</p>\n\n<p>Third version is to send the field to the server side and get back the new HTML fields but in this way you may send multiple times the password to the server which can be a security hole. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:16:01.183", "Id": "21034", "ParentId": "21031", "Score": "1" } } ]
{ "AcceptedAnswerId": "21034", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T15:29:25.757", "Id": "21031", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Handle OnClick in Jquery or C#" }
21031
<p>I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. <a href="http://anandology.com/python-practice-book/functional-programming.html">One tutorial</a> in particular gives this as an exercise:</p> <blockquote> <p>Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.</p> </blockquote> <p>So I decided to give it a try. Here is what I have and it works fine:</p> <pre><code>def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.iteritems(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result </code></pre> <p>I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call. </p>
[]
[ { "body": "<p>Your solution really isn't at all functional. You should return a flattened dict and then merge that into your current dictionary. You should also not modify the dictionary, instead create it with all the values it should have. Here is my approach:</p>\n\n<pre><code>def flatten_dict(d):\n def items():\n for key, value in d.items():\n if isinstance(value, dict):\n for subkey, subvalue in flatten_dict(value).items():\n yield key + \".\" + subkey, subvalue\n else:\n yield key, value\n\n return dict(items())\n</code></pre>\n\n<p>Alternative which avoids yield</p>\n\n<pre><code>def flatten_dict(d):\n def expand(key, value):\n if isinstance(value, dict):\n return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]\n else:\n return [ (key, value) ]\n\n items = [ item for k, v in d.items() for item in expand(k, v) ]\n\n return dict(items)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:39:53.393", "Id": "33764", "Score": "0", "body": "Thanks. I was trying to iterate through the result during each recursive step but it returns an error stating the size of the dictionary changed. I'm new to python and I barely understand yield. Is it because yield creates the value on the fly without storing them that the code is not blocked anymore?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:45:27.547", "Id": "33765", "Score": "0", "body": "One thing though. I did return a flattened dict and merged it into a current dictionary, which is the flattened result of the original dictionary. I'd like to know why it was not functional at all..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:05:55.500", "Id": "33767", "Score": "0", "body": "@LimH., if you got that error you were modifying the dictionary you were iterating over. If you are trying to be functional, you shouldn't be modifying dictionaries at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:07:34.050", "Id": "33769", "Score": "0", "body": "No, you did not return a flattened dict and merge it. You ignore the return value of your recursive function call. Your function modifies what is passed to it which is exactly that which you aren't supposed to do in functional style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:08:37.700", "Id": "33771", "Score": "0", "body": "yield does create values on the fly, but that has nothing to do with why this works. It works because it creates new objects and never attempts to modify the existing ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:09:11.227", "Id": "33772", "Score": "0", "body": "I see my mistakes now. Thank you very much :) I thought I was passing copies of result to the function. In fact, I think the author of the tutorial I'm following makes the same mistake, at least with the flatten_list function: http://anandology.com/python-practice-book/functional-programming.html#example-flatten-a-list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:49:06.400", "Id": "33785", "Score": "0", "body": "Unfortunately, both versions are bugged for 3+ levels of recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:36:07.440", "Id": "33793", "Score": "2", "body": "@JohnOptionalSmith, I see the problem in the second version, but the first seems to work for me... test case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:17:53.050", "Id": "33807", "Score": "0", "body": "@WinstonEwert Try it with `a = { 'a' : 1, 'b' : { 'leprous' : 'bilateral' }, 'c' : { 'sigh' : 'somniphobia'} }` (actually triggers the bug with 2-level recursion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:33:31.610", "Id": "33810", "Score": "0", "body": "My bad ! CopyPaste error ! Your first version is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:01:49.873", "Id": "272490", "Score": "0", "body": "Thanks for this nice code snippet @WinstonEwert! Could you explain why you defined a function in a function here? Is there a benefit to doing this instead of defining the same functions outside of one another?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:20:31.280", "Id": "272493", "Score": "2", "body": "@zelusp, the benefit is organizational, the function inside the function is part of of the implementation of the outer function, and putting the function inside makes it clear and prevents other functions from using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:33:43.197", "Id": "272496", "Score": "0", "body": "[This link](https://realpython.com/blog/python/inner-functions-what-are-they-good-for/) helped me understand better" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:20:49.623", "Id": "21035", "ParentId": "21033", "Score": "19" } }, { "body": "<p>Beside avoiding mutations, functional mindset demands to split into elementary functions, along two axes:</p>\n\n<ol>\n<li>Decouple responsibilities.</li>\n<li>By case analysis (eg pattern matching). Here scalar vs dict. </li>\n</ol>\n\n<p>Regarding 1, nested dict traversal has nothing to do with the requirement to create dot separated keys. We've better return a list a keys, and concatenate them afterward. Thus, if you change your mind (using another separator, making abbreviations...), you don't have to dive in the iterator code -and worse, modify it.</p>\n\n<pre><code>def iteritems_nested(d):\n def fetch (suffixes, v0) :\n if isinstance(v0, dict):\n for k, v in v0.items() :\n for i in fetch(suffixes + [k], v): # \"yield from\" in python3.3\n yield i\n else:\n yield (suffixes, v0)\n\n return fetch([], d)\n\ndef flatten_dict(d) :\n return dict( ('.'.join(ks), v) for ks, v in iteritems_nested(d))\n #return { '.'.join(ks) : v for ks,v in iteritems_nested(d) }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:27:12.087", "Id": "33806", "Score": "0", "body": "Thank you for your response. Let me see if I get this right. Basically there are two strategies here. One is to recursively construct the dictionary result and one is to construct the suffixes. I used the second approach but my mistake was that I passed a reference of the result down the recursive chains but the key part is correct. Is that right? Winston Etwert used the first approach right? What's wrong with his code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:25:24.513", "Id": "33808", "Score": "0", "body": "The point is to (a) collect keys until deepest level and (b) concatenate them. You indeed did separate the two (although packed in the same function). Winston concatenate on the fly without modifying (mutating) anything, but an issue lies in recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:34:48.367", "Id": "33811", "Score": "0", "body": "My bad : Winston's implementation with yield is ok !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:38:34.250", "Id": "33818", "Score": "0", "body": "Is packing multiple objectives in the same function bad? I.e., is it bad style or is it conceptually incorrect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:01:43.017", "Id": "33859", "Score": "0", "body": "@LimH. [Both !](http://www.cs.utexas.edu/~shmat/courses/cs345/whyfp.pdf). It can be necessary for performance reason, since Python won't neither inline nor defer computation (lazy programming). To alleviate this point, you can follow the opposite approach : provide to the iterator the way to collect keys -via a folding function- (strategy pattern, kind of)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:47:57.963", "Id": "21045", "ParentId": "21033", "Score": "9" } } ]
{ "AcceptedAnswerId": "21035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:08:41.920", "Id": "21033", "Score": "14", "Tags": [ "python", "functional-programming" ], "Title": "Flatten dictionary in Python (functional style)" }
21033
<p>This is a working mergesort implementation I wrote as I'm trying to get back into C.</p> <p>I am not so much interested in feedback on the optimality of the algorithm (as I could read up countless articles I'm sure), but deep criticism of my style would be greatly appreciated.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; void mergesort_recurse(int* in_array, int i, int j); void merge(int* array, int left, int centre, int right); void mergesort(int* in_array, int len) { mergesort_recurse(in_array, 0, len); } void mergesort_recurse(int* in_array, int left, int right) { int length = right-left; /*Base case: There are only two elements - Compare them and swap if necessary.*/ if(length == 2) { if(in_array[left] &gt; in_array[right-1]) { int temp = in_array[right-1]; in_array[right-1] = in_array[left]; in_array[left] = temp; } } /*Leaves of lenth 1 can be ignored as they are already "sorted"*/ else if(length &gt; 1){ /*Split into two and sort recursively.*/ int centre = left + length / 2; mergesort_recurse(in_array, left, centre); mergesort_recurse(in_array, centre, right); merge(in_array, left, centre, right); } } void merge(int* array, int left, int centre, int right) { /*Establish the initial indexes of the left and right sides of the two "halves" to be merged.*/ int l = left; int r = centre; int length = right-left; /*A temporary array to hold the merged data - this implementation is not in-place*/ int* tmp = malloc(length * sizeof(int)); /*Iterate over the length of the merge.*/ int i; for(i = 0; i &lt; length; i++) { if(r==right){ /*If the right index has reached the right hand end of the data, the remaining elements can be dumped in from the LHS.*/ memcpy(tmp+i, array+l, (length-i)*sizeof(int)); break; } else if (l==centre) { /*Conversely if the left index has reached the LHS end, the remaining elements can be dumped in from the RHS.*/ memcpy(tmp+i, array+r, (length-i)*sizeof(int)); break; } else if(array[l] &lt; array[r]) { /*Otherwise add from the left or right by comparison.*/ tmp[i] = array[l]; l++; } else { tmp[i] = array[r]; r++; } } /*Finally memcpy the temp array into the target.*/ memcpy(array+left, tmp, length*sizeof(int)); free(tmp); } </code></pre>
[]
[ { "body": "<p>I can't fault too much here, it's generally looking pretty reasonable. I think the first point below is the most important, depending on how much experience you have with C, the second may or may not make much sense.</p>\n\n<h2>Information Hiding</h2>\n\n<p>Firstly, you should split this up into separate <code>.h</code> and <code>.c</code> files; perhaps you've already done this but just pasted them together for this post. Either way, if you want to reuse this, you'll need to put your function prototypes into a header file to <code>#include</code>.</p>\n\n<p>When you do this, you should give internal only functions (that is, functions you don't want your users to call directly) internal linkage. Hence your two functions:</p>\n\n<pre><code>void mergesort_recurse(int* in_array, int i, int j);\nvoid merge(int* array, int left, int centre, int right);\n</code></pre>\n\n<p>should be prefaced with <code>static</code>:</p>\n\n<pre><code>static void mergesort_recurse(int* in_array, int i, int j);\nstatic void merge(int* array, int left, int centre, int right);\n</code></pre>\n\n<p>So your header will look something like:</p>\n\n<pre><code>#ifndef MERGESORT_H_\n#define MERGESORT_H_\n\nvoid mergesort(int *in_array, int len);\n\n#endif //MERGESORT_H_\n</code></pre>\n\n<p>And the static function prototypes go in the <code>.c</code> file:</p>\n\n<pre><code>static void mergesort_recurse(int* in_array, int i, int j);\nstatic void merge(int* array, int left, int centre, int right);\n</code></pre>\n\n<p>This prevents anyone but the implementer from calling <code>merge</code> or <code>mergesort_recurse</code>. This allows you to safely modify any <code>static</code> functions and know that they won't be utilized in any user code - their interfaces can freely change and it won't break things - they're effectively <code>private</code> functions, in object-oriented terms.</p>\n\n<h2>Generic Sorting</h2>\n\n<p>You say you're trying to get back into C, and I'm not sure how well you knew the language before, but generally things like sorting routines will be generic. This can be somewhat complex, but I'll run through what you'd need to change if you wanted to allow sorting any type.</p>\n\n<p>Firstly, all our <code>int *</code> become <code>void *</code>. We'll also need to add a parameter specifying the size of the type we're actually passing in.</p>\n\n<pre><code>void mergesort(void *in_array, int len, size_t el_size);\n</code></pre>\n\n<p>Next step is to abstract away how comparison is done: instead of simply using <code>&lt;</code> or <code>&gt;</code>, we'll pass in a function pointer which we can use as a comparison function: this has the signature:</p>\n\n<pre><code>int (*compare)(const void*, const void*);\n</code></pre>\n\n<p>That's pretty ugly though, so let's make a <code>typedef</code> for it:</p>\n\n<pre><code>typedef int (*cmp_t)(const void*, const void*);\n</code></pre>\n\n<p>We'll also do the same thing for swapping two values: this will be used to replace </p>\n\n<pre><code>int temp = in_array[right-1];\nin_array[right-1] = in_array[left];\nin_array[left] = temp;\n</code></pre>\n\n<p>Again, with a <code>typedef</code>:</p>\n\n<pre><code>typedef void (*swap_t)(void *, void *);\n</code></pre>\n\n<p>Our header now looks like:</p>\n\n<pre><code>#ifndef MERGESORT_H_\n#define MERGESORT_H_\n\ntypedef int (*cmp_t)(const void*, const void*);\ntypedef void (*swap_t)(void *, void*);\n\nvoid mergesort(void *in_array, int len, size_t el_size, cmp_t, swap_t);\n\n#endif //MERGESORT_H_\n</code></pre>\n\n<p>And our in <code>.c</code>:</p>\n\n<pre><code>static void mergesort_recurse\n(void* in_array, int i, int j, size_t el_size, cmp_t, swap_t);\n\nstatic void merge(void *array, int left, int centre, int right, size_t el_size, cmp_t);\n</code></pre>\n\n<p>The implementation can is still fairly similar, but working with <code>void*</code> makes things a bit messier. Instead of <code>if(in_array[left] &gt; in_array[right-1])</code> we'll need to call our comparison function, and do a bunch of mucking around with casts:</p>\n\n<pre><code>compare(((char *)in_array + (left * el_size)), ((char *)in_array + (right - 1)*el_size)) &gt; 0)\n</code></pre>\n\n<p>Hrm, yuck, that's pretty ugly. Let's make a function that can do all of this casting and index calculating for us:</p>\n\n<p>In our <code>.c</code> file:</p>\n\n<pre><code>static void* get_pos(void *array, int index, size_t el_size)\n{\n return ((char *)array + (index * el_size));\n}\n</code></pre>\n\n<p>The only other thing that needs to be changed in this function is passing through function pointers to the other functions:</p>\n\n<pre><code>mergesort_recurse(in_array, left, centre, el_size, compare, swap);\nmergesort_recurse(in_array, centre, right, el_size, compare, swap);\nmerge(in_array, left, centre, right, el_size, compare);\n</code></pre>\n\n<p>In <code>merge</code>, all the calls to <code>memcpy</code> will have to change a little bit, for example:</p>\n\n<pre><code>memcpy(get_pos(tmp, i, el_size), get_pos(array, r, el_size), (length-i) * el_size);\n</code></pre>\n\n<p>Doing all of this allows the user to sort whatever they want - integers, doubles, structs, whatever - as long as they provide their own comparison and swap functions:</p>\n\n<pre><code>int compare_i(const void *a, const void *b)\n{\n int x = *((int *)a); \n int y = *((int *)b);\n if(x == y) return 0;\n if(x &lt; y) return -1;\n return 1;\n}\n\nvoid swap_i(void *a, void *b)\n{\n int temp = *(int *)a;\n *((int *)a) = *((int *)b);\n *((int *)b) = temp;\n}\n</code></pre>\n\n<p>So our <code>mergesort</code> call would look something like:</p>\n\n<pre><code>int x[] = {5, 8, 2, 3, 1, 7, 10};\nmergesort(x, 7, sizeof(int), compare_i, swap_i);\n</code></pre>\n\n<p>If the above is all very confusing, I apologise, but hopefully it'll give you something to look back on when you get into the hairier parts of C. The standard library <code>qsort</code> uses these techniques to be generic sorting routine as well, so understanding this will help with understanding parts of the standard library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T06:13:14.800", "Id": "33799", "Score": "1", "body": "+1, but one tiny nitpick: Why declare the static functions in the header? That completely breaks the idea of encapsulating them from the calling code. Also, if some consuming code wanted to have a function called `merge` with the same signature, it now can't without it being forced to be static (the chances of that happening are tiny, but the theory should apply)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T06:24:47.700", "Id": "33800", "Score": "0", "body": "@Corbin You're completely right, I had a brainfart there. I've updated my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:19:38.640", "Id": "33817", "Score": "0", "body": "That's great, thanks very much! I just had one question: Why would I need to genericise the swapping? Is there a situation where it would be something other than swapping their places in the array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T13:50:50.420", "Id": "33827", "Score": "0", "body": "You don't have to genericise the swap, you could do the same thing with a few calls to `memcpy`. I just added it in there because I think it's slightly cleaner. It's certainly not an essential part, however." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T17:36:01.200", "Id": "33917", "Score": "0", "body": "+1 for allowing the user to pass in a comparison function. But if you do this, you should also allow the user to supply an environment `void *env` which gets passed as a third argument to the comparison function each time it is called. (This works around C's lack of closures.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T01:47:05.997", "Id": "33939", "Score": "0", "body": "@GarethRees Well, I suppose, if it needs to access or modify anything outside of its scope, which it may. Honestly, at that point, I start longing for C++ and functors (and also templates). But that's a whole other can of worms..." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T05:37:16.920", "Id": "21051", "ParentId": "21036", "Score": "9" } }, { "body": "<p>I can't compete with the answer you got from @Yuushi but I have some nit-picking and pedantry to add.</p>\n\n<ul>\n<li>C functions usually start with the opening { in column 0.</li>\n<li>functions are best ordered so that local prototypes are unnecessary -\ni.e. in reverse order of use.</li>\n<li>I prefer keywords (<code>if</code>, <code>for</code>, <code>while</code> etc) to be followed by a space.</li>\n<li>I prefer <code>int *var;</code> to <code>int* var;</code>. Consider <code>int* var1, var2;</code> - <code>var2</code> is\nnot a pointer.</li>\n<li>there is some extra vertical spacing that, to me, is undesirable</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T04:34:18.403", "Id": "33884", "Score": "0", "body": "Thanks for the feedback! Tbh I thought I was following Kernighan and Ritchie, placing the `{` at the end of the definition, but having bothered to pull the book off the shelf I see that they don't do that for functions. Your tip on keywords is also in line with K&R. I also accept your reasoning on pointer declarations. However I am not decided (either way) on the issue of vertical spacing. Sometimes I philosophise that the empty space is the most important factor contributing to readablity (like in Chinese art and calligraphy). One day I'll be convinced one way or the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T06:53:47.513", "Id": "33885", "Score": "0", "body": "The `int *var` vs `int* var` only really helps the argument to not put more than 1 declaration per line. I don't think it matters too much either way - actually, when I write `C` I'll use `int *var`, when writing `C++`, `int* var`. The argument is that the type is `int*` so the `*` should go with the type, but that's also not terribly convincing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T01:01:07.413", "Id": "21089", "ParentId": "21036", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:37:45.273", "Id": "21036", "Score": "5", "Tags": [ "c", "mergesort" ], "Title": "ANSI C Mergesort" }
21036
<p>My task is ask this from the user:</p> <pre><code>Enter the number corresponding to the desired pay rate or action: 1) $8.75/hr 2) $9.33/hr 3) $10.00/hr 4) $11.20/hr 5) quit </code></pre> <p>If choices 1 through 4 are selected, the program should request the hours worked. The program should recycle until 5 is entered. If something other than choices 1 through 5 is entered, the program should remind the user what the proper choices are and then recycle. And i have to use <code>switch</code></p> <p>My code:</p> <pre><code>#include &lt;stdio.h&gt; #define RATE1 8.75 #define RATE2 9.33 #define RATE3 10.00 #define RATE4 11.20 int main() { int rateSelected; int weeklyHours; double totalPayed, rateToCalculate; printf("Enter the number corresponding to the desired pay rate or action:\n"); printf("1) %.2lf$/hr 2) %.2lf$/hr\n", RATE1, RATE2); printf("3) %.2lf$/hr 4) %.2lf$/hr\n", RATE3, RATE4); printf("5) Quit\n"); while ((scanf("%d", &amp;rateSelected)) != EOF &amp;&amp; rateSelected != 5) { if (rateSelected &gt; 4) { printf("please enter a valid number:\n"); continue; } switch (rateSelected) { case 1: rateToCalculate = RATE1; break; case 2: rateToCalculate = RATE2; break; case 3: rateToCalculate = RATE3; break; case 4: rateToCalculate = RATE4; break; }; printf("please enter you weekly hours:\n"); scanf("%d", &amp;weeklyHours); totalPayed = weeklyHours * rateToCalculate; printf("your paychack for this week is: %.2lf\n\n",totalPayed); printf("Enter the number corresponding to the desired pay rate or action:\n"); printf("1) %.2lf$/hr 2) %.2lf$/hr\n", RATE1, RATE2); printf("3) %.2lf$/hr 4) %.2lf$/hr\n", RATE3, RATE4); printf("5) Quit\n"); } return 0; } </code></pre> <p>How bad is it? And one thing didn't work for me is if a user put a letter its not cycling..(any suggestion for that too?)</p> <p>Thank you,</p>
[]
[ { "body": "<ol>\n<li>Create better names for the rate levels, maybe you could use positions or titles (e.g. entry level rate, mid level rate, etc.). </li>\n<li>Consistent use of whitespace would help readability </li>\n<li>Pull the switch statement out into a different method </li>\n</ol>\n\n<p>like below: </p>\n\n<pre><code>int getRate(RateEnum selection)\n{\n switch (selection)\n {\n case 1:\n return EntryLevelRate;\n break;\n case 2:\n return MidLevelRate;\n break;\n case 3:\n return SeniorLevelRate;\n break;\n case 4:\n return ManagerLevelRate;\n break;\n };\n}\n</code></pre>\n\n<p>Then call it like this: <code>rateToCalculate = getRate(rateSelected);</code></p>\n\n<p>If you are trying to prompt the user again, you should make use of a <a href=\"http://www.cprogramming.com/tutorial/c/lesson3.html\" rel=\"nofollow\">while</a> loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T18:03:54.163", "Id": "21040", "ParentId": "21037", "Score": "1" } }, { "body": "<p>It's not bad. A couple of issues regarding validating input, which you know about, but a few 'style' things, some of which you may not know about yet. </p>\n\n<p>In addition to Ryan's answer, a couple more suggestions:</p>\n\n<ul>\n<li><p>Only declare one variable per line. Otherwise it becomes harder to see where it comes from.</p>\n\n<pre><code>double totalPayed;\ndouble rateToCalculate;\n</code></pre></li>\n<li><p>In general, try to declare variables in the inner-most block in which they're used. In this case, all but <code>rateSelected</code> should be declared inside the while loop. It doesn't matter for this, but in more complex programs restricting where the variables can be used will become more important.</p></li>\n<li><p>Don't have 'magic numbers', in this case the options themselves. I would suggest setting up an enum (if you know about them?, or a series of <code>#define</code>s), something like:</p>\n\n<pre><code>enum { OPTION_BEGIN = 1, OPTION_RATE_ENTRY = OPTION_BEGIN, OPTION_RATE_MID, OPTION_RATE_SENIOR, OPTION_RATE_MANAGER, OPTION_QUIT, OPTION_END };\n</code></pre>\n\n<p>Use these in <code>getRate</code> instead of the appropriate numbers.</p></li>\n<li><p>Separate out the question into a separate function, it's an identifiable single task. And it becomes easier to change if it's one place. I've added another function here for readability:</p>\n\n<pre><code>int is_valid_option( int option )\n{\n return ( option &gt;= OPTION_BEGIN ) &amp;&amp; ( option &lt; OPTION_END );\n}\n\nint ask_for_pay_rate( void )\n{\n int option = OPTION_END;\n while ( option == OPTION_END ) \n {\n int answer;\n\n printf(\"Enter the number corresponding to the desired pay rate or action:\\n\");\n printf(\"1) %.2lf$/hr 2) %.2lf$/hr\\n\", RATE1, RATE2);\n printf(\"3) %.2lf$/hr 4) %.2lf$/hr\\n\", RATE3, RATE4);\n printf(\"5) Quit\\n\");\n\n /* scanf returns the number of successful inputs, ie 1 number.\n Test for this, rather than eof */\n if ( ( scanf( \"%d\", &amp;answer ) == 1 ) &amp;&amp; is_valid_option( answer ) )\n {\n option = answer;\n }\n else\n {\n printf(\"please enter a valid number:\\n\");\n }\n }\n return option;\n}\n</code></pre>\n\n<p>Note by the way, that I've set up a condition at the start of the while loop which forces it to execute at least once. Doing it the way you did means that you have to duplicate code, allowing the possibility that it'll be subtly different.</p></li>\n<li><p>You may want to validate the value for <code>weeklyHours</code>, should be a number >= 0</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:00:50.610", "Id": "33814", "Score": "1", "body": "thank allot for that detailed comment! it helped allot :) @Glenn Rogers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:05:29.077", "Id": "21054", "ParentId": "21037", "Score": "2" } } ]
{ "AcceptedAnswerId": "21054", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:48:33.373", "Id": "21037", "Score": "4", "Tags": [ "c" ], "Title": "Using 'switch to choose different rates to calculate net pay" }
21037
<p>I was interested in feedback on this architecture.</p> <p>Objective: serialize / deserialize a network application protocol stream.</p> <p>Approach: Create a class for each layer/object which exposes attributes as well as encapsulating the stream reader/writer.</p> <p>If instantiated for serialization the object is instantiated with the appropriate attributes, then a serialize method can be invoked with a BinaryWriter argument that results in the object, and sub-objects, serializing themselves to the stream.</p> <p>Conversely, when instantiated for deserialization the root object is instantiated with a BinaryReader in the constructor. The root object deserializes the stream by reading its attributes from the stream and instantiating instances of any child layer/object(s).</p> <p>Below is a working simple example of a single layer. It does not currently have the BinaryWriter method implemented, only the reader.</p> <p>Good idea? Typical? Bad idea? Are there other common architectures or better design patterns?... that of course is before we even get to code quality.</p> <pre><code>namespace Sony.Protocol.Hdcp { public class HdcpGammaData { private byte _fill1 = 0x00; private byte _fill2 = 0x00; private Table _table; private Color _color; private byte _fill3 = 0x00; private byte _offset; private byte _numberOfPoints = 0x10; private List&lt;HdcpGammaPoint&gt; HdcpGammaPoints; public HdcpGammaData(Table table, Color color, byte offset, List&lt;HdcpGammaPoint&gt; hdcpGammaPoints) { Table = table; Color = color; Offset = offset; if (hdcpGammaPoints.Count != _numberOfPoints) { throw new System.ArgumentException("hdcpGammaPoints must contain 0x10 points"); } HdcpGammaPoints = hdcpGammaPoints; } public HdcpGammaData(BinaryReader reader) { HdcpGammaPoints = new List&lt;HdcpGammaPoint&gt;(); fill1 = reader.ReadByte(); fill2 = reader.ReadByte(); Table = (Table)reader.ReadByte(); Color = (Color)reader.ReadByte(); fill3 = reader.ReadByte(); Offset = reader.ReadByte(); NumberOfPoints = reader.ReadByte(); for (int i = 0; i &lt; _numberOfPoints; i++) HdcpGammaPoints.Add(new HdcpGammaPoint(reader)); } public Table Table { get { return _table; } private set { if (!Enum.IsDefined(typeof(Table), value)) { throw new System.ArgumentOutOfRangeException("Table", value, "Table must be between 1 and 3"); } _table = value; } } public byte fill1 { get { return _fill1; } private set { _fill1 = value; } } public Color Color { get { return _color; } private set { if (!Enum.IsDefined(typeof(Color), value)) { throw new System.ArgumentOutOfRangeException("Color", value, "Color must be between 0 and 2"); } _color = value; } } public byte fill2 { get { return _fill2; } private set { _fill2 = value; } } public byte fill3 { get { return _fill3; } private set { _fill3 = value; } } public byte Offset { get { return _offset; } private set { if (_offset != 0x00 &amp;&amp; _offset != 0x10) { throw new System.ArgumentOutOfRangeException("Offset", value, "Offset must be 0x00 or 0x10"); } _offset = value; } } public byte NumberOfPoints { get { return _numberOfPoints; } private set { if (_numberOfPoints != 0x10) { throw new System.ArgumentOutOfRangeException("NumberOfPoints", value, "NumberOfPoints must be 0x10"); } _numberOfPoints = value; } } } public enum Color : byte { Red = 0, Green, Blue } public enum Table : byte { Gamma1 = 0x01, Gamma2, Gamma3 } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:01:07.650", "Id": "33786", "Score": "2", "body": "Is there a reason why are you doing this all by yourself, instead of using a library like [Protocol Buffers](http://code.google.com/p/protobuf-net/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:22:45.753", "Id": "33792", "Score": "0", "body": "@svick If tlum is like me it could be that we have never heard of Protocol Buffers :) Thanks for the link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:06:39.343", "Id": "33946", "Score": "0", "body": "@svick never having heard of it is one major reason, and to be enlightened to it is another. Thanks for the link." } ]
[ { "body": "<p>I' not sure about having two constructors that would be used in different contexts i.e. one for serialization and one for serialization. It seems like to much of a constraint on the object before you even begin to use it.</p>\n\n<p>I think I would prefer to having a HdcpGammaDataReader and a HdcpGammaDataWriter (or something along these lines). These could perhaps both implement respectively a IDataReader and IDataWriter class. These classes would then do the serialization as you wish. </p>\n\n<p>Something like this perhaps:</p>\n\n<pre><code>interface IDataSerializer&lt;T&gt;\n{\n void Seralize(T obj);\n}\n\ninterface IDataDeserializer&lt;T&gt;\n{\n T DeSeralize();\n}\n\npublic partial class HdcpGammaDataSerializer&lt;HdcpGammaData&gt; : IDataDeserializer\n{\n public HdcpGammaData DeSeralize()\n {\n // Build my HdcpGameData object in here either\n }\n}\n\npublic partial class HdcpGammaDataDeSerializer&lt;HdcpGammaData&gt; : IDataDeserializer\n{\n public HdcpGammaData DeSeralize()\n {\n // deserialize here\n }\n}\n</code></pre>\n\n<p>If you wanted to make the Gamma class immutable pass in all the arguments in the constructor. If you wanted to added an extra layer (packet header, CRC etc) around the data object then your serialize could inherit from a base class that first read the surrounding packet data and offloaded the actual payload serialization/serialization as required.</p>\n\n<p>As for the code itself. Just a few minor things</p>\n\n<ol>\n<li><p>I personally try not to make property names the same as their type names although this is just a personal preference. In your case as suggested by svick it is good to leave as is. Here's a good read on this conundrum I just found after a quick google if intereste. <a href=\"https://stackoverflow.com/questions/2542963/how-to-avoid-using-the-same-identifier-for-class-names-and-property-names\">How to avoid using the same identifier for Class Names and Property Names?</a> </p></li>\n<li><p>A couple of inconsistencies in your public property camel casing. I noticed you had a <strong>fill1</strong>. It should be <strong>Fill1</strong> to be consistent.</p></li>\n<li><p>In line with 2. I'm not sure of your application domain but I tend to find properties like fill1, fill2 a bit obscure and don't tend to suggest what that property is. Perhaps a more meaningful name here to get away from the 1, 2 naming syntax would be appropiate.</p></li>\n<li><p>If you are going to have public properties with backing fields unless you need the private field just use auto-properties.</p></li>\n</ol>\n\n<p>i.e. </p>\n\n<pre><code>public byte Fill3 { get; private set; }\n</code></pre>\n\n<p>Alternatively you could do away with the private set altogether and make your field read-only and only expose a public method</p>\n\n<p>i.e. </p>\n\n<pre><code>private readonly byte _fill3; // initialise in constructor\npublic byte fill3 { get { return _fill3; } }\n</code></pre>\n\n<p>As you seem to be mixing and matching your assignment in your constructor being fields and properties I would probably just go with the auto-property concept.</p>\n\n<p>Just my 2cents...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:05:24.167", "Id": "33787", "Score": "0", "body": "I think using `object` in your interfaces is a bad idea, I don't see any reason why they shouldn't be generic. And property with the same name as its type is fine, it's certainly not a reason to rename the *type*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:08:43.873", "Id": "33788", "Score": "0", "body": "Sure, could make the interface generic. Probably a good idea although I vaguely remember a problem I had done that track a while back. As for property names same as type. I personally think they should be different. If not the type name then rename the property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:12:50.490", "Id": "33789", "Score": "0", "body": "Could you explain *why* do you think they should be different? If I have a type that represents a color, I think `Color` is a good name for that. Similarly, if I have a property of something that represents its color, `Color` is a good name for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:14:51.953", "Id": "33790", "Score": "0", "body": "Also, your code would be really confusing if I didn't know what you meant to write. (Generic class that doesn't use its parameter, `Serializer` class that implements `Deserializer` interface, etc.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:18:38.437", "Id": "33791", "Score": "0", "body": "Well I always thought to help with readability where possible to give a different name. No exact reason other than thought it was better practice. However I note that although it might be recommended at times it's not necessarill best practice so will remove from answer. Cheers for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:28:52.260", "Id": "33951", "Score": "0", "body": "I was being sloppy with the property names, they have since become more concise and expressive and the casing is more consistent.fillx was a placeholder since the protocol is very poorly documented... once has since become Ack for example, I don't like that either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:34:51.720", "Id": "33953", "Score": "0", "body": "The reason for the private set on properties was to allow for a single point of validation where there were more than one constructors accepting the property, so that the validation didn't get repeated in each constructor, and the constructors were accessing the property rather than the field directly, which led me to write them all that way just for consistency's sake, and then most of them went unused." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T19:46:58.653", "Id": "21043", "ParentId": "21042", "Score": "2" } } ]
{ "AcceptedAnswerId": "21043", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T18:57:01.920", "Id": "21042", "Score": "3", "Tags": [ "c#" ], "Title": "Layered network protocol serialize / deserialize" }
21042
<p>I've got server running to make serial data available on a TCP/IP port. My goal is to collect data coming from a realtime device connected to the serial port and deliver it to web clients connected to an express server using socket.io as the data is collected from a backend socket. I want the backend socket to reconnect if for some reason data stops or the backend socket disconnects. I also want to be able to expose the ability to change the back end data host and port. I've managed to put something together that does all of this, and it works reasonably well.</p> <p>I am not really sure how this will hold up to a production environment. There is a problem already with any client being about to change the backend data source, which is behavior that I will need to avoid.</p> <p>Short of that, would anyone care to comment on my code with regards to making this more bullet-proof or maybe point out some shortcomings? This is my first time using socket.io in a production environment.</p> <pre><code>var express = require('express'), app = module.exports = express.createServer(), io = require('socket.io').listen(app, { log: true }), routes = require('./routes'), delimiter ="\n", bufferSendCommand = "$X", net = require('net'), serverPort = 3000, dataServerTimeOut = 2000, host = "somehost.com", dataSourcePort = 5000, buffer = [], events = require('events'), line = "", gotAChunck = new events.EventEmitter(), dataConnection = new events.EventEmitter(), connectionMonitor, reconnect = 0, reconnectAttemptTime = 10000, dataMonitorThresholdTime = 5000, dataStream = net.createConnection(dataSourcePort, host); function startReconnect(doReconnect){ dataConnection.emit('status',false); io.sockets.emit('error',{message:"Lost Data Source - Attempting to Reconnect"}); } dataStream.on('error', function(error){ io.sockets.emit('error',{message:"Source error on host:"+ host + " port:"+dataSourcePort}); }); dataStream.on('connect', function(){ dataConnection.emit('status',true); io.sockets.emit('connected',{message:"Data Source Found"}); }); dataStream.on('close', function(){ io.sockets.emit('error',{message:"Data Source Closed"}); }); dataStream.on('end',function(){ io.sockets.emit('error',{message:"Source ended on host:"+ host + " port:"+dataSourcePort}); }); dataStream.on('data', function(data) { dataConnection.emit('status',true); clearTimeout(connectionMonitor); connectionMonitor = setTimeout(function(){startReconnect(true);}, dataMonitorThresholdTime); // Collect a line from the host line += data.toString(); // Split collected data by delimiter line.split(delimiter).forEach(function (part, i, array) { if (i !== array.length-1) { // Fully delimited line. //push on to buffer and emit when bufferSendCommand is present buffer.push(part.trim()); if (part.substring(0, bufferSendCommand.length) == bufferSendCommand){ gotAChunck.emit('new', buffer); buffer=[]; } } else { // Last split part might be partial. We can't announce it just yet. line = part; } }); }); dataConnection.on('status', function(connected){ if(!connected){ reconnect = setInterval(function(){dataStream.connect(dataSourcePort, host);}, reconnectAttemptTime); } else{ clearInterval(reconnect); } }); gotAChunck.on('new', function(buffer){ io.sockets.emit('feed', {feedLines: buffer}); }); io.sockets.on('connection', function(socket){ dataConnection.emit('status',false); // Handle Client request to change data source socket.on('message',function(data) { var clientMessage = JSON.parse(data); if('connectString' in clientMessage &amp;&amp; clientMessage.connectString.dataHost !== '' &amp;&amp; clientMessage.connectString.dataPort !== '') { dataStream.destroy(); dataSourcePort = clientMessage.connectString.dataPort; host = clientMessage.connectString.dataHost; dataStream = net.createConnection(dataSourcePort, host); } }); }); app.configure(function(){ app.set('views', __dirname + '/views'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); app.get('/', routes.index.html); app.listen(serverPort); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T14:21:33.167", "Id": "77347", "Score": "0", "body": "You are defining a lot of constants at the beginning of the file. I would suggest that you use ONLY_CAPS_FOR_CONSTANTS like proposed here http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Constants#Constants. This way it's clear that's not meant to change later in the application. Ex: `DATA_SERVER_TIMEOUT`" } ]
[ { "body": "<p>A fun piece of code, </p>\n\n<ul>\n<li><p>You clearly took the single comma separated <code>var</code> statement all the way, I would still group the related variables ( requires, module, server info, timeouts etc.):</p>\n\n<pre><code>var express = require('express'),\n routes = require('./routes'),\n net = require('net'),\n events = require('events'), \n app = module.exports = express.createServer(),\n io = require('socket.io').listen(app, { log: true }),\n serverPort = 3000, \n host = \"somehost.com\", \n delimiter =\"\\n\", \n bufferSendCommand = \"$X\",\n gotAChunck = new events.EventEmitter(),\n dataConnection = new events.EventEmitter(),\n dataServerTimeOut = 2000,\n dataSourcePort = 5000,\n reconnectAttemptTime = 10000,\n dataMonitorThresholdTime = 5000,\n dataStream = net.createConnection(dataSourcePort, host),\n buffer = [],\n line = \"\",\n reconnect = 0,\n connectionMonitor;\n</code></pre></li>\n<li><p>I am not a big fan of your handling the last bit of info, I would counter-propose this:</p>\n\n<pre><code>// Collect data from the host\nvar lines ( line += data.toString() ).split(delimiter);\n// Last split part might be partial. We can't announce it just yet.\nline = lines.pop();\n// Split collected data by delimiter\nlines.forEach(function (part) {\n //push on to buffer and emit when bufferSendCommand is present\n buffer.push(part.trim());\n if (part.substring(0, bufferSendCommand.length) == bufferSendCommand){\n gotAChunck.emit('new', buffer);\n buffer=[];\n }\n});\n</code></pre>\n\n<p>The first line might be too Golfic for you, feel free to split it out.</p></li>\n</ul>\n\n<p>All in all, I think the code is well written and should be easy to understand/maintain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T19:07:20.580", "Id": "42889", "ParentId": "21047", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T22:44:01.967", "Id": "21047", "Score": "3", "Tags": [ "javascript", "node.js", "express.js", "client", "socket.io" ], "Title": "Delivering realtime data from backend socket" }
21047
<p>This is my first code in C++. Since I'm new to the language, I'm just looking for pointers on what can be made better. I tried to cut out unnecessary stuff, but there are some comments in there. I know Java, so if you're trying to explain anything in Java, I can understand it.</p> <p>Feel free to mention anything, whether it be code style (which I'm completely unsure what the conventions are in C++), performance, etc.</p> <p>The goal of the program is to take an equation, such as <code>5x^2+48204x=7</code>, and parse the <code>5</code> and <code>48204</code> into strings. </p> <pre><code>using namespace std; void printHelp(); class Equation { public: string equation1; string equation2; int matrix [3][2]; Equation(string one, string two) { one.erase(remove_if(one.begin(), one.end(), isspace), one.end()); two.erase(remove_if(two.begin(), two.end(), isspace), two.end()); equation1 = one; equation2 = two; cout &lt;&lt; equation1 &lt;&lt; endl; init(); } void init() { size_t firstx = equation1.find_first_of("x"); size_t secondx = equation1.find_first_of("x", firstx + 1); if (secondx == string::npos) { cout &lt;&lt; "Secondx == 0" &lt;&lt; endl; } //cout &lt;&lt; firstx &lt;&lt; endl; //cout &lt;&lt; secondx &lt;&lt; endl; int startloc = firstx - 1; while (true) { //cout &lt;&lt; "starting with startloc = " &lt;&lt; startloc &lt;&lt; endl; if (startloc == -1) { break; } char c = equation1.at(startloc); if (c == ' ' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/') { //cout &lt;&lt; "Found something" &lt;&lt; endl; break; } startloc--; } string s; unsigned int i = startloc + 1; //cout &lt;&lt; i &lt;&lt; endl; //cout &lt;&lt; firstx &lt;&lt; endl; while (i &lt; firstx) { //cout &lt;&lt; "Character at " &lt;&lt; i &lt;&lt; endl; //cout &lt;&lt; equation1[i] &lt;&lt; endl; stringstream ss; string temp; ss &lt;&lt; equation1[i]; ss &gt;&gt; temp; s.append(temp); i++; } cout &lt;&lt; s &lt;&lt; endl; startloc = secondx - 1; while (true) { //cout &lt;&lt; "starting with startloc = " &lt;&lt; startloc &lt;&lt; endl; if (startloc == 0) { cout &lt;&lt; "Problem" &lt;&lt; endl; } char c = equation1.at(startloc); if (c == ' ' || c == '=' || c == '+' || c == '-' || c == '*' || c == '/') { //cout &lt;&lt; "Found something" &lt;&lt; endl; break; } startloc--; } s = ""; i = startloc + 1; while (i &lt; secondx) { stringstream ss; string temp; ss &lt;&lt; equation1[i]; ss &gt;&gt; s; s.append(temp); i++; } cout &lt;&lt; s &lt;&lt; endl; } }; int main(int argc, char *argv[]) { Equation equation(argv[1], "blank"); //printHelp(); string s; cin &gt;&gt; s; return 0; } void printHelp() { cout &lt;&lt; "Welcome!" &lt;&lt; endl; cout &lt;&lt; "Stuff about commands" &lt;&lt; endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:46:25.607", "Id": "33838", "Score": "3", "body": "The main issue in this program is the program design. Most importantly, you need to use the most fundamental concept in object-oriented design: private encapsulation. C++ is no different from Java in this. Since you are a beginner programmer, you should learn object-oriented design as early as possible, this is far more important than learning all the dirty details of a particular language. I'd actually go back to Java and study OO design with that language as foundation, since Java is far cleaner (though less powerful) than C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T17:19:23.687", "Id": "33843", "Score": "1", "body": "Comment your code. What's the purpose of the code? What's the main algorithm? What are the important lines of code and *why* do they exist?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:23:45.457", "Id": "33847", "Score": "0", "body": "Thanks guys. I dont think i need to go back and relearn OOP because im sure i understand it, althought this code doesnt show it. I wrote this in about 15 minutes so i didnt clean it at all. Im going to repost it once i clean it in 2ish hours. (Also, i dont understand pointers, if anyone has advice) hopefully it will look alot nicer when cleaned" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:24:31.030", "Id": "33860", "Score": "0", "body": "Updated the code, attempted to clean it up and use some of the changes that were suggested" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T01:01:01.047", "Id": "33906", "Score": "0", "body": "My code has been cleaned up greatly, thank you guys." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T21:26:06.623", "Id": "70686", "Score": "0", "body": "In addition to cleaning up the post, I've reverted the changes made to the original code. Please do not do this as it invalidates answers. You may post the updated code below the original instead." } ]
[ { "body": "<p>Without changing things too much...</p>\n\n<ul>\n<li><p>You need some <code>#include</code>s.</p></li>\n<li><p>Don't use <code>using namespace</code>. One of the issues is knowing where a function comes from (which one is being used) - this hides it. Using a short <code>std::</code> gains you a lot in understandability. You can do <code>using std::string</code> which is better, but imo even that isn't worth it.</p></li>\n<li><p>You might as well put <code>printHelp</code> before <code>main</code> rather than after, that way you don't have to declare it. And it's not used currently anyway. </p></li>\n<li><p>Matrix also isn't used.</p></li>\n<li><p>Having an <code>Equation</code> class doesn't make sense for what you're (currently) using it for. You might as well just have a naked function.</p></li>\n<li><p>You don't allow for the possibility that <code>firstx</code> may be invalid, ie there are no <code>x</code> in the equation. This may be a given, of course. And for that matter, that the x^2 term will be first!</p></li>\n<li><p>If <code>secondx</code> is invalid, skip over processing it.</p></li>\n<li><p>Multiple breaks in while loops should be avoided, for readability. This (first) loop probably should be split off into another function since it's used twice, together with the following section.</p></li>\n<li><p>I'm a little nervous of <code>int startloc = firstx - 1;</code>, since <code>firstx</code> is unsigned and <code>startloc</code> isn't. I'd cast <code>firstx</code> to an <code>int</code> first if I were using it like this.</p></li>\n<li><p>Consider using std::string::find_last_of and std::string::substr. They'll simplify the code somewhat.</p></li>\n<li><p>Check that you don't lose a negative coefficient.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:52:59.920", "Id": "33819", "Score": "0", "body": "Thanks, lots of little things i didnt think of. As for printhelp() ill be using it when i start expanding the program. Matrix[][] is unused but i will be using it later. The reason i have the equation class is because ill be expanding it to do multiple things later. I just wrote some (messy) code to try to get the splitting. Your saying instead of #include <string> use std::string? O.o" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:57:38.470", "Id": "33820", "Score": "0", "body": "I understand putting that loop in a function since its used multiple times. My last question: is that char -> string conversion correct? I couldnt find any way to do it faster" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:14:29.863", "Id": "33822", "Score": "1", "body": "You need `#include <string>` anyway. But use `std::string` rather than `using std` and `string`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:20:59.087", "Id": "33823", "Score": "0", "body": "re the conversion, I don't want to even look at it!! For your loops, the first loop is doing `find_last_of`, and the second is doing `substr`. Use these instead of making your own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:04:32.380", "Id": "33834", "Score": "0", "body": "I get how you can use substring and wish i remembered earlier, oops! But how would you use find_last_of? I dont really get how i would use it to replace the first loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:41:30.200", "Id": "33837", "Score": "0", "body": "`startloc = equation1.find_last_of( \"+-*/=\", firstx );`, returns the position of the operator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:25:16.857", "Id": "33848", "Score": "0", "body": "Wow, i cant believe i missed that, thanks. Ill reupload the code shortley" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:25:20.227", "Id": "33849", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7324/discussion-between-tips48-and-glenn-rogers)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:46:02.237", "Id": "21057", "ParentId": "21048", "Score": "10" } } ]
{ "AcceptedAnswerId": "21057", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T03:10:07.243", "Id": "21048", "Score": "12", "Tags": [ "c++", "beginner", "parsing", "mathematics" ], "Title": "Parsing numbers from equations into strings" }
21048
<p>I have some entities in use in my project, and to make things easier, I would like to have the type of the key for that entity defined via a generic. E.g.:</p> <pre><code>public abstract class Entity&lt;T&gt; { public virtual T Id { get; set; } } </code></pre> <p>This way, I can pull the Id field into the base entity and not have to define it every time (There's a few other fields on Entity in the real system, so there is other utility to doing this)</p> <p>Then, since I'm using Fluent NHibernate, I make a generic mapping class to go along with this generic entity:</p> <pre><code>internal abstract class EntityMapping&lt;T,TK&gt; : ClassMap&lt;T&gt; where T : Entity&lt;TK&gt; { protected EntityMapping() { Id(m =&gt; m.Id); } } </code></pre> <p>And starting here is when I wonder if there's a better way of handling this. C# doesn't seem to infer the <code>TK</code> type parameter from the <code>Entity</code> definition, and having to add to all of my mapping classes the key parameter for the entity they map seems redundant, all the more so since it also extends to some of the higher generic data access classes, e.g.:</p> <pre><code>public abstract class EntityRepository&lt;T,TK&gt; where T : Entity&lt;TK&gt; { } </code></pre> <p>Is there a tidier way of handling this, or is this what I have to do if I want to have the key type of my entities passed in?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:28:45.967", "Id": "33809", "Score": "3", "body": "I think there is no tidier way, as long as you want to keep everything generic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T17:53:23.237", "Id": "33844", "Score": "0", "body": "That's what I was thinking was probably the case. Worth asking though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:19:10.210", "Id": "34617", "Score": "0", "body": "I would suggest that you use marker interfaces for generic type constraints (ex. IEntity, IEntity<TId> : IEntity, IRepository, IRepository<T> : IRepository where T: class, IEntity, new()) . A base entity class as shown below should work fine as well, but use marker interfaces instead for constraints to allow using your base class or a custom class." } ]
[ { "body": "<p>There is no way to simplify generic parameters if you want to keep Entity class generic, as noted by @svick. </p>\n\n<p>The only thing I can suggest as alternative here is to remove generic parameter from <code>Entity</code>. I don't think you need 10 different types for <code>Id</code> field, most likely you'll have <code>int Id</code> or <code>Guid Id</code>, so you can create</p>\n\n<pre><code>public interface IEntity&lt;T&gt;\n{\n T Id { get; set; }\n}\n\npublic abstract class IntEntity: IEntity&lt;int&gt;\n{\n public virtual int Id { get; set; }\n}\n\npublic abstract class GuidEntity: IEntity&lt;Guid&gt;\n{\n public virtual Guid Id { get; set; }\n}\n</code></pre>\n\n<p>Not sure if you need <code>IEntity&lt;T&gt;</code> interface, added it so that you don't loose the possibility to reference both types of entities in generic manner.</p>\n\n<p>Yes, you'll have to declare separate IntEntityRepository and GuidEntityRepository, but I don't think it's that hard given that you can extract common code to base class, and it's a one-time job.</p>\n\n<p>As to mappings - I don't use class hierarchy for them (declaring all the fields on the actual entity mapper), but you can do the same trick as with repositories.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-28T20:30:27.623", "Id": "398271", "Score": "0", "body": "What about a composite key ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-30T12:13:42.067", "Id": "398482", "Score": "0", "body": "I don't think it's reasonable to create generic base classes for entities with composite keys. In case of a single key, it's ok to assume (or define a convention) that key's name would be \"Id\". I don't think you would have such a convention for generic composite keys..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T09:36:30.237", "Id": "21103", "ParentId": "21052", "Score": "3" } }, { "body": "<p>This is quite similar to something I'm doing. If I may give a tiny bit of advice for your <code>Entity</code> class, it would be to override/define some of the standard <code>object</code> operations as such:</p>\n\n<pre><code>public abstract class Entity&lt;T&gt;\n{\n public virtual T Id { get; set; }\n\n public static bool operator ==(Entity entity1, Entity entity2)\n {\n return ReferenceEquals(entity1, entity2) || (((object)entity1 != null) &amp;&amp; entity1.Equals(entity2));\n }\n\n public static bool operator !=(Entity entity1, Entity entity2)\n {\n return !(entity1 == entity2);\n }\n\n public override bool Equals(object obj)\n {\n var entity = obj as Entity;\n\n return (entity != null) &amp;&amp; (entity.GetType() == this.GetType()) &amp;&amp; (entity.Id == this.Id);\n }\n\n public override int GetHashCode()\n {\n return this.Id.GetHashCode();\n }\n\n public override string ToString()\n {\n return this.Id.ToString(CultureInfo.InvariantCulture);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:47:33.853", "Id": "34008", "Score": "1", "body": "I had `Equals` and `GetHashCode` overridden on the actual class (I just pulled out the relevant properties for this question), so `IComparer`/`IEquatable` would work. The operator overloading is a good idea though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:52:41.970", "Id": "34009", "Score": "0", "body": "@MattSieker rock on, sir!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-25T16:07:45.350", "Id": "199810", "Score": "1", "body": "@JesseC.Slicer code does not work... missing Entity Base class or must be of type Entity<T>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-25T16:17:43.853", "Id": "199812", "Score": "0", "body": "@Beachwalker it worked 2 1/2 years ago." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:58:44.310", "Id": "21181", "ParentId": "21052", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T05:40:43.140", "Id": "21052", "Score": "3", "Tags": [ "c#", "generics" ], "Title": "Is there a better way of defining generic entity classes?" }
21052
<p>My task was:</p> <p>Write a program that accepts an integer as input and then displays all the prime numbers smaller than or equal to that number.</p> <p>And my code is:</p> <pre><code>#include &lt;stdio.h&gt; void FindPrime(int number); int main() { int userInput, counter; printf("Please enter a limit number to test all the prime numbers it contains:\n"); scanf("%d", &amp;userInput); printf("The prime numbers %d contains are:\n", userInput); for (counter = 2; counter &lt; userInput; counter++) { FindPrime(counter); } return 0; } void FindPrime(int number) { int numberTest, nextNumber = 1; for (numberTest = 2; numberTest &lt; number; numberTest++) { if (number%numberTest == 0 &amp;&amp; numberTest &lt; number) continue; else nextNumber++; } if (nextNumber == (number - 1)) printf("%d ", number); } </code></pre> <p>Can this code be improved?</p>
[]
[ { "body": "<p>To see if a number is prime, you only need to check that the <code>number</code> is divisible by any number between 2 and Square root of <code>number</code>. Cause if the <code>number</code> is divisible by any number between 2 and <code>sqrt(number)</code> then it will also have the corresponding factor between between <code>number+1/2</code> and <code>sqrt(number)</code>.</p>\n\n<p>Consider a number, say 32.</p>\n\n<p>(32+1)/2=16</p>\n\n<p>To check that it is prime or not you only need to check if it is divisible by any number between 2 and 16 (inclusive). </p>\n\n<p>So you need to change this line in your <code>FindPrime(int number)</code> function.</p>\n\n<pre><code>for (numberTest = 2; numberTest &lt; number; numberTest++)\n</code></pre>\n\n<p>To</p>\n\n<pre><code>for (numberTest = 2; numberTest &lt; sqrt(number) + 1; numberTest++)\n</code></pre>\n\n<p>Secondly, you should the <code>main</code> function to call a function which checks whether the number is prime or not, if it is, then use <code>main</code> to print that number. It'll make your code clean since only <code>main</code> will print out and not the <code>FindPrime</code> function. </p>\n\n<p>Here is my code : </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;math.h&gt;\n\nint is_prime(int n);\n\nint main(void) {\n int i, input;\n\n scanf(\"%d\", &amp;input);\n printf(\"The prime numbers %d contains are:\\n\", input);\n for(i = 2; i &lt;= input; ++i) {\n if(is_prime(i)) {\n printf(\"%d\\n\", i);\n }\n }\n return 0;\n}\n\nint is_prime(int n) {\n int i;\n for(i=2; i &lt;= sqrt(n) + 1; ++i) {\n if(!(n % i)) {\n return 1;\n }\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:50:35.677", "Id": "33839", "Score": "2", "body": "Spoiler: there is no need to ever test if even numbers are prime, all even numbers are divisible by 2. Also, why did you suddenly change to void main()? There is nothing in the original post indicating that the code is intended for embedded systems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T19:48:09.417", "Id": "33852", "Score": "2", "body": "To see if n is prime, it is enough to look for factors up to the square root of n. Actually, it is enough to test all primes up to the square root of n because every composite number has a prime factorization." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:11:17.597", "Id": "21059", "ParentId": "21056", "Score": "1" } }, { "body": "<ul>\n<li><p>Personally, I would put <code>FindPrime</code> above <code>main</code>, to avoid having to declare it.</p></li>\n<li><p>Only have one variable declaration per line. With more than one, it becomes harder to see where a variable comes from. It doesn't really matter with a short program, but will for more complex ones.</p></li>\n<li><p>Your print statements contain text which contradict what the task says (<em>contains</em> rather than <em>less than</em>)</p></li>\n<li><p><code>userInput</code> needs to be validated - Make sure that the user has entered a number, and it's greater than 0.</p></li>\n<li><p>As mentioned, it's better that a function does one thing, rather than multiple. So your <code>FindPrime</code> function should be responsible for finding one, and the caller should be responsible for printing it.</p></li>\n<li><p>In <code>FindPrime</code>, the <code>if</code> statement contains a condition that's already been tested for in the <code>for</code> loop, so you can simplify the <code>if</code> condition by removing it.</p></li>\n<li><p>Always use <code>{}</code> for <code>if</code> (and <code>while</code>, <code>for</code> etc) statements, even if they're single line. Sooner or later, you'll add another line and break things, causing a very subtle error. And in this example, I'd reverse the condition, since the normal case doesn't do anything.</p>\n\n<pre><code>if (number%numberTest != 0 )\n{\n nextNumber++;\n}\n</code></pre></li>\n</ul>\n\n<p>With regards to the algorithm, it can certainly be improved, but that may be out of your reach at the moment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:53:50.333", "Id": "33840", "Score": "0", "body": "\"Personally, I would put FindPrime above main, to avoid having to declare it.\" That remark is rather pointless, since proper program design wouldn't place these functions together with main() at all, they would be in a separate module prime.h + prime.c. Apart from that, I completely agree with everything stated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T13:13:39.493", "Id": "21062", "ParentId": "21056", "Score": "2" } } ]
{ "AcceptedAnswerId": "21062", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:09:15.880", "Id": "21056", "Score": "4", "Tags": [ "c", "primes" ], "Title": "Get a limit number to test all the prime numbers it contains in C" }
21056
<p>I think understanding basic data compression and pattern finding / entropy reduction primitives is really important. Mostly the basic algorithms (before the many tweaks and optimizations are made) are really elegant and inspiring. What's even more impressive is how widespread they are, but perhaps also how little they are really understood except outside of people working in compression directly. So I want to understand.</p> <p>I understand and have implemented the naive implementations of <a href="http://en.wikipedia.org/wiki/LZ77_and_LZ78" rel="nofollow">LZ77</a> (just find the maximal prefix that existed before the current factor) and <a href="http://en.wikipedia.org/wiki/LZ77_and_LZ78" rel="nofollow">LZ78</a> (just see if we can extend a factor that occurred before at least twice, or we make a new record and start a new factor). I also understand the naive version of <a href="http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform" rel="nofollow">Burrows-Wheeler Transform</a> (maintain the invariant that the first column is sorted, and keep adding that column and resorting until the matrix is square).</p> <p>I also understand why all these (parts of) compression algorithms work:</p> <ol> <li>LZ77 asymptotically optimal since in the long term and with an infinite window all factors that exist are composed of prefixes earlier in the input which LZ77 can find.</li> <li>LZ78 is also pretty good since if a factor occurs at least once before it can be compressed the second time, so long as it is not a suffix of another factor found earlier.</li> <li>BWT, by grouping same letters on the left hand side (of the matrix), and finding patterns in the preceding letters in the right hand side, can exploit bigram repetitions, recursively.</li> </ol> <p>The BWT code below works, but the inverse is not efficient. What are the optimizations, and how can I understand why they work?</p> <p><strong>BWT</strong></p> <pre><code>def rot(v): return v[-1] + v[:-1] def bwt_matrix(s): return sorted(reduce(lambda m,s : m + [rot(m[-1])],xrange(len(s)-1),[s])) def last_column(m): return ''.join(zip(*m)[-1]) def bwt(s): bwtm = bwt_matrix(s) print 'BWT matrix : ', bwtm return bwtm.index(s), ''.join(last_column(bwtm)) def transpose(m): return [''.join(i) for i in zip(*m)] def ibwt(s): return reduce(lambda m, s: transpose(sorted(transpose([s]+m))),[s]*len(s),[]) s = 'sixtysix' index, bwts = bwt(s) print 'BWT, index : ', bwts, index print 'iBWT : ', ibwt(bwts) </code></pre> <p><strong>BWT output</strong></p> <pre><code>BWT matrix : ixsixtys ixtysixs sixsixty sixtysix tysixsix xsixtysi xtysixsi ysixsixt BWT, index : ssyxxiit 3 iBWT : ixsixtys ixtysixs sixsixty sixtysix tysixsix xsixtysi xtysixsi ysixsixt </code></pre> <p>Which is correct.</p> <p><strong>LZ77</strong></p> <pre><code>def lz77(s): lens = len(s) factors = [] i = 0 while i &lt; lens: max_match_len = 0 current_word = i j = 0 while j &lt; lens-1: if current_word &gt;= lens or s[current_word] != s[j]: j -= (current_word - i) if current_word - i &gt;= max_match_len: max_match_len = current_word - i if current_word &gt;= lens: break current_word = i else: current_word += 1 j += 1 if max_match_len &gt; 1: factors.append(s[i:i+max_match_len]) i += max_match_len else: factors.append(s[i]) i += 1 return ','.join(factors) </code></pre> <p><strong>LZ78</strong></p> <pre><code>def lz78(s): empty = '' factors = [] word = empty for c in s: word += c if word not in factors: factors.append(word) word = empty if word is not empty: factors.append(word) return ','.join(factors) </code></pre> <p><strong>Correct outputs against 7th Fibonacci word:</strong></p> <pre><code>LZ77( abaababaabaab ): a,b,a,aba,baaba,ab LZ78( abaababaabaab ): a,b,aa,ba,baa,baab </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T14:17:39.953", "Id": "33828", "Score": "0", "body": "A couple of bugs: (i) in `rot` `v[-1]` should be `v[-1:]` (ii) in `lz78` there's a reference to an undefined variable `empty`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T14:25:04.413", "Id": "33829", "Score": "0", "body": "Hey @GarethRees. Thanks! But if I make v[-1]+v[:-1] v[-1:]+v[:-1] I will get rot('abcde') = 'e'+'abcd' which is the same as v[-1] ? Please explain this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T14:28:48.687", "Id": "33830", "Score": "0", "body": "With `v[-1]` it only works for strings: try `rot(range(3))` for example. With `v[-1:]` it works for all sequences. (Perhaps \"bug\" was a bit strong.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T14:40:16.237", "Id": "33833", "Score": "0", "body": "No no you are right. I thought 'maybe he means that, but that would be *extremely* forward thinking of him considering bwt is mostly applied to strings' but you are right...I even have a use for applying it to sequences!" } ]
[ { "body": "<h3>1. Introduction</h3>\n\n<p>The only actual question you asked is about how to make the inverse Burrows–Wheeler transform go faster. But as you'll see below, that's plenty for one question here on Code Review. If you have anything to ask about your LZ77 and LZ78 implementations, I suggest you start a new question.</p>\n\n<h3>2. A bug</h3>\n\n<p>First, the output of the function <code>ibwt</code> doesn't match the example output in the question:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; from pprint import pprint\n&gt;&gt;&gt; pprint(ibwt('ssyxxiit'))\n['iisstxxy',\n 'xxiiysts',\n 'stxxsiyi',\n 'iystixsx',\n 'xsiyxtis',\n 'tixssyxi',\n 'yxtiissx',\n 'ssyxxiit']\n</code></pre>\n\n<p>You should always prepare your question by copying and pasting input and output from source files and from an interactive session, rather than typing in what you think it should be. It's easy to introduce or cover up mistakes if you do the latter.</p>\n\n<p>So it looks as if there is a missing <code>transpose</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; pprint(transpose(ibwt('ssyxxiit')))\n['ixsixtys',\n 'ixtysixs',\n 'sixsixty',\n 'sixtysix',\n 'tysixsix',\n 'xsixtysi',\n 'xtysixsi',\n 'ysixsixt']\n</code></pre>\n\n<h3>3. Avoiding transpositions</h3>\n\n<p>With that bug fixed, let's see how long the function takes on a medium-sized amount of data:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; import random, string\n&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; s = ''.join(random.choice(string.printable) for _ in range(1024))\n&gt;&gt;&gt; t = bwt(s)\n&gt;&gt;&gt; timeit(lambda:ibwt(t[1]), number=1)\n49.83987808227539\n</code></pre>\n\n<p>Not so good! What can we change? Well, an obvious idea is to cut out all those calls to <code>transpose</code>. The function <code>ibwt</code> transposes the matrix in order to sort it, and then transposes it back again each time round the loop. By keeping the matrix in transposed form throughout, it would be possible to avoid having to call <code>transpose</code> at all:</p>\n\n<pre><code>def ibwt2(s):\n \"\"\"Return the inverse Burrows-Wheeler Transform matrix based on the\n string s.\n\n &gt;&gt;&gt; ibwt2('SSYXXIIT')[3]\n 'SIXTYSIX'\n\n \"\"\"\n matrix = [''] * len(s)\n for _ in s:\n matrix = sorted(i + j for i, j in zip(s, matrix))\n return matrix\n</code></pre>\n\n<p>That simple change results in a big improvement:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; s = ''.join(random.choice(string.printable) for _ in range(1024))\n&gt;&gt;&gt; t = bwt(s)\n&gt;&gt;&gt; timeit(lambda:ibwt2(t[1]), number=1)\n0.9414288997650146\n</code></pre>\n\n<h3>4. Aside on programming style</h3>\n\n<p>Something that's perhaps worth mentioning at this point is that you seem quite keen on transforming code so as to use a functional style (for example in <a href=\"https://codereview.stackexchange.com/q/21019/11728\">this question</a>, where you wanted to express a loop using <code>reduce</code>). Transforming code into pure functional form is an excellent intellectual exercise, but you have to be aware of two problems that often arise:</p>\n\n<ol>\n<li><p>Pure functional programs can easily end up doing a lot of allocation and copying. For example, it is often tempting to transform your data into a format suitable for passing in to a function (rather than transforming your function so that it operates on the data you have). Thus in <code>ibwt</code> it is convenient to call <code>sorted</code> on the data in row-major order, but convenient to append a new instance of the string <code>s</code> in column-major order. In order to express both of these operations in the most convenient way, the function has to transpose the matrix back and forth, and since it do so functionally, each transposition has to copy the whole matrix.</p></li>\n<li><p>Pursuit of pure functional style often results in <a href=\"https://en.wikipedia.org/wiki/Tacit_programming\" rel=\"nofollow noreferrer\"><em>tacit</em> or <em>point-free programming</em></a> where variable names are avoided and data is routed from one function to another using <a href=\"https://en.wikipedia.org/wiki/Combinatory_logic\" rel=\"nofollow noreferrer\">combinators</a>. This can seem very elegant, but variable names have <em>two</em> roles in a program: they don't just move data around, they also act as mnemonics to remind programmers of what the data <em>means</em>. Point-free programs can end up being totally mysterious because you lose track of exactly what is being operated on.</p></li>\n</ol>\n\n<p>Anyway, aside over. Can we make any more progress on the inverse Burrows–Wheeler transform?</p>\n\n<h3>5. An efficient implementation</h3>\n\n<p>If you look at what the inverse Burrows–Wheeler transform does, you'll see that it repeatedly permutes an array of strings (by sorting them). The permutation is exactly the same at each step (exercise: prove this!). For example, if we are given the string <code>SSYXXIIT</code>, then at each step we apply the permutation <code>SSYXXIIT</code> → <code>IISSTXXY</code>, which (taking note of where repeated letters go) is the permutation <code>01234567</code> → <code>56017342</code>.</p>\n\n<p>This observation allows us to reconstruct a row of the matrix without having to compute the whole matrix. In this example we want to reconstruct row number 3. Well, we know that the final matrix looks like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>I.......\nI.......\nS.......\nS*......\nT.......\nX.......\nX.......\nY.......\n</code></pre>\n\n<p>so the first element of the row is <code>S</code>. What's the next letter of this row (marked with <code>*</code>)? Where did this come from? Well, we know that the last step of the transform must have looked like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>S0...... I5......\nS1...... I6......\nY2...... -&gt; S0......\nX3...... -&gt; S1......\nX4...... -&gt; T7......\nI5...... -&gt; X3......\nI6...... X4......\nT7...... Y2......\n</code></pre>\n\n<p>So the <code>*</code> must have come from row 1 (which is the image of 3 under the permutation), and so it must be <code>I</code> (which is element number 1 of the sorted string <code>IISSTXXY</code>).</p>\n\n<p>We can follow this approach all the way along the row. Here's an implementation in Python:</p>\n\n<pre><code>def ibwt3(k, s):\n \"\"\"Return the kth row of the inverse Burrows-Wheeler Transform\n matrix based on the string s.\n\n &gt;&gt;&gt; ibwt3(3, 'SSYXXIIT')\n 'SIXTYSIX'\n\n \"\"\"\n def row(k):\n permutation = sorted((t, i) for i, t in enumerate(s))\n for _ in s:\n t, k = permutation[k]\n yield t\n return ''.join(row(k))\n</code></pre>\n\n<p>Let's check that works:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; ibwt3(3, 'SSYXXIIT')\n'SIXTYSIX'\n&gt;&gt;&gt; s = ''.join(random.choice(string.printable) for _ in range(1024))\n&gt;&gt;&gt; t = bwt(s)\n&gt;&gt;&gt; ibwt3(*t) == s\nTrue\n</code></pre>\n\n<p>and is acceptably fast:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; timeit(lambda:ibwt3(*t), number=1)\n0.0013821125030517578\n</code></pre>\n\n<p>(If you compare my <code>ibwt3</code> to the <a href=\"https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform#Sample_implementation\" rel=\"nofollow noreferrer\">sample Python implementation on Wikipedia</a> you'll see that mine is not only much simpler, but also copes with arbitrary characters, not just bytes in the range 0–255. So either I've missed something important, or the Wikipedia article could be improved.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T15:51:52.933", "Id": "21120", "ParentId": "21058", "Score": "23" } } ]
{ "AcceptedAnswerId": "21120", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:06:23.913", "Id": "21058", "Score": "16", "Tags": [ "python", "performance", "strings", "compression" ], "Title": "Increasing speed of BWT inverse" }
21058
<p>I'm new to Python and GAE, but years of procedural programming. I have this code, but I know that there must be some better solution to avoid retyping code.</p> <p>The first and last section of code are identical in both GET and POST methods, so I suppose there must be another way to share the identical code.</p> <pre><code># This class manage the user account class MyAccount(webapp2.RequestHandler): def get(self): """ Shows actual user account """ # Get actual user user = users.get_current_user() if user: # Get the actual user data data = Person.gql("WHERE username = :nick", nick=user.nickname()).get() # Test if we found the user if data: templateValues['data'] = data template = jinja_environment.get_template('myAccount.htm') else: templateValues['custom_msg'] = "The logged user is not available." template = jinja_environment.get_template('customMessage.htm') else: templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account" template = jinja_environment.get_template('customMessage.htm') # Render the page self.response.out.write(template.render(templateValues)) def post(self): """ Saves user updated data """ # Get actual user user = users.get_current_user() if user: # Get the actual user data person = Person.gql("WHERE username = :nick", nick=user.nickname()).get() # Test if we found the user if person: person.username = self.request.get('username') person.password = self.request.get('password') if person.email: self.request.get('email') person.name = self.request.get('name') person.lastname = self.request.get('lastname') person.idnumber = self.request.get('idnumber') templateValues['data'] = person template = jinja_environment.get_template('myAccount.htm') else: templateValues['custom_msg'] = "The logged user is not available." template = jinja_environment.get_template('customMessage.htm') else: templateValues['custom_msg'] = "You are not logged in. Please, login to access to your account." template = jinja_environment.get_template('customMessage.htm') # Render the page self.response.out.write(template.render(templateValues)) </code></pre>
[]
[ { "body": "<p>This line looks suspicious:</p>\n\n<pre><code> if person.email: self.request.get('email')\n</code></pre>\n\n<p>I assume it should be:</p>\n\n<pre><code> person.email = self.request.get('email')\n</code></pre>\n\n<p>Your code seem to be using excessive indentation. The python standard is four space per level. </p>\n\n<p>You are using <code>templateValues</code> but don't seem to define it anywhere.</p>\n\n<p>To refactor this, I'd start by removing the section of that that's different between the two methods into their own function:</p>\n\n<pre><code># This class manage the user account\nclass MyAccount(webapp2.RequestHandler):\n\n def show_user(self, user):\n # Get the actual user data\n data = Person.gql(\"WHERE username = :nick\",\n nick=user.nickname()).get()\n # Test if we found the user\n if data:\n templateValues['data'] = data\n template = jinja_environment.get_template('myAccount.htm')\n else:\n templateValues['custom_msg'] = \"The logged user is not available.\"\n template = jinja_environment.get_template('customMessage.htm')\n\n return template, templateValues\n\n\n\n def get(self):\n \"\"\" Shows actual user account \"\"\"\n\n # Get actual user\n user = users.get_current_user()\n if user:\n template, templateValues = self.show_user(user)\n else:\n templateValues['custom_msg'] = \"You are not logged in. Please, login to access to your account\"\n template = jinja_environment.get_template('customMessage.htm')\n\n # Render the page\n self.response.out.write(template.render(templateValues))\n\n def update_user(self, user):\n # Get the actual user data\n person = Person.gql(\"WHERE username = :nick\",\n nick=user.nickname()).get()\n # Test if we found the user\n if person:\n person.username = self.request.get('username')\n person.password = self.request.get('password')\n person.email = self.request.get('email')\n person.name = self.request.get('name')\n person.lastname = self.request.get('lastname')\n person.idnumber = self.request.get('idnumber')\n\n templateValues['data'] = person\n template = jinja_environment.get_template('myAccount.htm')\n else:\n templateValues['custom_msg'] = \"The logged user is not available.\"\n template = jinja_environment.get_template('customMessage.htm')\n\n return template, templateValues\n\n\n def post(self):\n \"\"\" Saves user updated data \"\"\"\n # Get actual user\n user = users.get_current_user()\n if user:\n template, templateValues = self.update_user(user)\n else:\n templateValues['custom_msg'] = \"You are not logged in. Please, login to access to your account.\"\n template = jinja_environment.get_template('customMessage.htm')\n # Render the page\n self.response.out.write(template.render(templateValues))\n</code></pre>\n\n<p>The only thing different between <code>post</code> and <code>get</code> is the function they call. We'll just pass the function as a parameter to a new function.</p>\n\n<pre><code> def request(self, handler):\n \"\"\" Shows actual user account \"\"\"\n\n # Get actual user\n user = users.get_current_user()\n if user:\n template, templateValues = handler(user)\n else:\n templateValues['custom_msg'] = \"You are not logged in. Please, login to access to your account\"\n template = jinja_environment.get_template('customMessage.htm')\n\n # Render the page\n self.response.out.write(template.render(templateValues))\n\n def get(self):\n return self.request(self.show_user)\n\n def post(self):\n return self.request(self.update_user)\n</code></pre>\n\n<p>The current code repeats calls to <code>get_template</code> a lot. So we'll refactor it so that it only happens once. We'll just store the name of the template in a variable and load it just before we render it.</p>\n\n<pre><code>def show_user(self, user):\n # Get the actual user data\n data = Person.gql(\"WHERE username = :nick\",\n nick=user.nickname()).get()\n # Test if we found the user\n if data:\n templateValues['data'] = data\n template = 'myAccount.htm'\n else:\n templateValues['custom_msg'] = \"The logged user is not available.\"\n template = 'customMessage.htm'\n\n return template, templateValues\n\n\n\ndef request(self, handler):\n \"\"\" Shows actual user account \"\"\"\n\n # Get actual user\n user = users.get_current_user()\n if user:\n template, templateValues = handler(user)\n else:\n templateValues['custom_msg'] = \"You are not logged in. Please, login to access to your account\"\n template = 'customMessage.htm'\n\n # Render the page\n template = jinja_environment.get_template(template)\n self.response.out.write(template.render(templateValues))\n</code></pre>\n\n<p>But we can clean up our actual work functions a little more:</p>\n\n<pre><code>def show_user(self, user):\n # Get the actual user data\n data = Person.gql(\"WHERE username = :nick\",\n nick=user.nickname()).get()\n # Test if we found the user\n if data:\n return 'myAccount.htm', {\n 'data' : data\n }\n else:\n return 'custom_msg.htm', {\n 'custom_msg' : \"The logged user is not available.\"\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T16:52:41.807", "Id": "33841", "Score": "0", "body": "Yeah, thanks. I love python everyday more and more. It's flexibility has no limits!!\nGreat trick the function as parameter to a function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T17:04:02.503", "Id": "33842", "Score": "0", "body": "By the way, I pasted the code in my text editor, which made this strange indentation (double tab, instead tab), but is 4 spaces normally. And you are right in the other 2 supositions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T15:45:00.160", "Id": "21065", "ParentId": "21061", "Score": "1" } }, { "body": "<p>A little more clean up (sorry, I can't code on the answer link):</p>\n\n<p>Get inside request the common part for show_user and update_user (which only differs on the name of the var, data or person). This is the final code. Thank you very much.</p>\n\n<pre><code># This class manage the user account\nclass MyAccount(webapp2.RequestHandler):\n\n def show_user(self, person):\n templateValues = {}\n templateValues['data'] = person\n template = 'myAccount.htm'\n\n return template, templateValues\n\n def update_user(self, person):\n person.username = self.request.get('username')\n person.password = self.request.get('password')\n person.email = self.request.get('email')\n person.name = self.request.get('name')\n person.lastname = self.request.get('lastname')\n person.idnumber = self.request.get('idnumber')\n\n templateValues = {}\n templateValues['data'] = person\n template = 'myAccount.htm'\n\n return template, templateValues\n\n def requested(self, handler):\n \"\"\" Shows actual user account \"\"\"\n\n # Get actual user\n user = users.get_current_user()\n if user:\n # Get the actual user data\n person = Person.gql(\"WHERE username = :nick\",\n nick=user.nickname()).get()\n # Test if we found the user\n if person:\n template, templateValues = handler(person)\n else:\n templateValues['custom_msg'] = \"The logged user is not available.\"\n template = 'customMessage.htm'\n else:\n templateValues['custom_msg'] = \"You are not logged in. Please, login to access to your account\"\n template = 'customMessage.htm'\n\n # Render the page\n template = jinja_environment.get_template(template)\n self.response.out.write(template.render(templateValues))\n\n def get(self):\n return self.requested(self.show_user)\n\n def post(self):\n return self.requested(self.update_user)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:53:20.993", "Id": "21111", "ParentId": "21061", "Score": "0" } } ]
{ "AcceptedAnswerId": "21065", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T12:42:09.623", "Id": "21061", "Score": "3", "Tags": [ "python", "beginner", "google-app-engine" ], "Title": "User account code with GET and POST" }
21061
<pre><code>List&lt;int&gt; types = new List&lt;int&gt;(); foreach (var d in myTableList) { if (!types.Contains((int)d.item_type)) types.Add((int)d.item_type); } </code></pre> <p>I have a table in db called myTable. There is a column in it called item_type. It is integer.</p> <p>I want to make a list which would have all item_type which are in myTableList, but there shouldn't be duplicates.</p> <p>I tried:</p> <pre><code>types = myTableList.Distinct(x =&gt; x.item_type) </code></pre> <p>but I want types to be list of integers, not items of type myTable.</p>
[]
[ { "body": "<p>Try</p>\n\n<pre><code>types = myTableList\n .Select(x =&gt; (int)x.item_type)\n .Distinct();\n</code></pre>\n\n<p>You may also want to add <code>.ToList()</code> at the end if you want to match original code</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T13:59:15.417", "Id": "21064", "ParentId": "21063", "Score": "7" } }, { "body": "<p>Another option is to just use a <code>HashSet&lt;T&gt;</code> to do the distinction for you:</p>\n\n<pre><code>var types = new HashSet&lt;int&gt;(myTableList.Select(x =&gt; (int)x.item_type)).ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T09:21:27.093", "Id": "34045", "Score": "0", "body": "`Distinct` does exactly that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T10:10:04.453", "Id": "34046", "Score": "0", "body": "Just to expand my previous comment... Distinct uses `HashSet` to ensure uniqueness of elements, and outputs element if it has not been seen before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T22:16:10.847", "Id": "34082", "Score": "0", "body": "Yes, hence why I said \"another option\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T05:21:02.400", "Id": "21216", "ParentId": "21063", "Score": "1" } } ]
{ "AcceptedAnswerId": "21064", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T13:39:58.023", "Id": "21063", "Score": "1", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "Optimizing a distinction code" }
21063
<p>I wrote my own version of <code>endswith</code> just like in high-level programming languages in C which I would like reviews on.</p> <p>There are 2 versions. One is my own and the other is from <a href="https://github.com/rustyrussell/ccan/" rel="nofollow">ccan</a>. For some reason, I feel that <a href="https://github.com/rustyrussell/ccan/" rel="nofollow">ccan</a>'s version is better than mine until proven wrong.</p> <p><a href="https://github.com/rustyrussell/ccan/" rel="nofollow">ccan</a>/str's version:</p> <pre><code>static inline bool strends(const char *str, const char *postfix) { if (strlen(str) &lt; strlen(postfix)) return false; return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0; } </code></pre> <p>My version:</p> <pre><code>bool strends(const char *str, const char *postfix) { register const char *end = str + strlen(str) - 1; register const char *epostfix = postfix + strlen(postfix) - 1; while (end &gt; str &amp;&amp; epostfix &gt; postfix) if (*end-- != *epostfix--) return false; return true; } </code></pre> <p><strong>Update</strong> This is the newer version of mine:</p> <pre><code>bool strends(const char *str, const char *postfix) { register const char *end = str + strlen(str) - strlen(postfix); if (strlen(str) &lt; strlen(postfix)) return false; while (*end) if (*end++ != *postfix++) return false; return true; } </code></pre> <p>I wonder which one is better and why (in terms of readability, performance and so on). Please be specific and provide your research if possible.</p> <p>Thanks in advance.</p>
[]
[ { "body": "<p>I like the more the first, because it works at an higher level of abstraction and it makes it clear that you are interested in comparing a part of the string with the postfix.</p>\n\n<p>I'd probably introduce another variable to clearly represent that you are comparing the postfix with the latest <code>strlen(postfix)</code> chars of the original string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T00:00:14.203", "Id": "33874", "Score": "0", "body": "Hmm, total agreed :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T17:42:42.877", "Id": "21069", "ParentId": "21066", "Score": "4" } }, { "body": "<p>Your version will fail when <code>strlen(postfix)</code> > <code>strlen(str)</code>. Once your loop reaches the start of <code>str</code>, it will end the loop and return <code>true</code> which isn't correct.</p>\n\n<p>Also, unless there is some special property about the <code>register</code> keyword that makes this work - comparing <code>end</code> to <code>epostfix</code> doesn't make sense to me - it will always be true or always be false depending on where the two strings are in memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:36:12.917", "Id": "33850", "Score": "0", "body": "My bad on that one, didn't mean it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:18:08.883", "Id": "21071", "ParentId": "21066", "Score": "2" } }, { "body": "<p>Your version has its problems: why do you use a loop? The postfix is either at the end or it is not.</p>\n\n<p>The ccan version is optimal. One might think that calling <code>strlen</code> twice on each string is wasteful, but as long as optimisation is enabled, this gets optimised away. Having said that, I'd write it as follows, but even with -O1 this ends up more or less the same (at assembler level) as the ccan code:</p>\n\n<pre><code>int endswith(const char *s, const char *t)\n{\n size_t len_s = strlen(s);\n size_t len_t = strlen(t);\n if (len_t &lt;= len_s) {\n return strcmp(s + len_s - len_t, t) == 0;\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T23:59:16.240", "Id": "33873", "Score": "0", "body": "I know that calling `strlen` isn't wasteful since it has a `pure` attribute. Your kind of wrong about the first statement `The postfix is either at the end or it is not`; well, the postfix should be something like `aaa` while str can be like `bbbaaa`, you may have not thought about it harder (If I understand correctly)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T01:08:04.417", "Id": "33875", "Score": "0", "body": "Ok, I see now - you are doing a backwards `strcmp` with your loop. Sorry, I didn't read your function carefully enough." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:34:07.330", "Id": "21083", "ParentId": "21066", "Score": "1" } }, { "body": "<p>In your updated version, you do basically the same as ccan (you can/should switch the first statement with the if statement). The ccan way is the way I would prefer. Code reuse is most of the time a good idea. I would rather trust the common implementations of string.h in terms of safety (It would surprise me if a bug survived 30 years of usage) and speed for typical usage (It would surprise me too, if there is a significant faster way to do it without any drawbacks for such a simple function).</p>\n\n<p>Everyone reading your code has to think what is happening and if it is right. Everyone reading strcmp knows whats happening and will probably trust the correctness.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T16:54:31.327", "Id": "21121", "ParentId": "21066", "Score": "1" } } ]
{ "AcceptedAnswerId": "21121", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T16:01:16.833", "Id": "21066", "Score": "6", "Tags": [ "c" ], "Title": "string manipulation, which version of those 2 functions is better?" }
21066
<p>I'm building a symfony project and at some point I've come up with a switch case to manage the acl rights. I would prefer using a dynamic access to the constant but havn't find a good solution. I've seen reflection but that doesn't seem to be the proper solution to me.</p> <pre><code>$mask = null; switch ($participant-&gt;getRight()) { case 'VIEW': $mask = MaskBuilder::MASK_VIEW; break; case 'EDIT': $mask = MaskBuilder::MASK_EDIT; break; case 'OPERATOR': $mask = MaskBuilder::MASK_OPERATOR; break; default: break; } $this-&gt;aclManager-&gt;addObjectPermission($project, $mask, $user); </code></pre> <p>So, this switch is in a <code>foreach</code>, that gets the <code>$user</code> entity, then with the result of the list box from the view, I get the rights of the user which can be (for now) EDIT VIEW or OPERATOR. These right were chosen because they are directly related to the <a href="http://symfony.com/doc/current/cookbook/security/acl_advanced.html#built-in-permission-map" rel="nofollow">MaskBuilder masks</a>. </p> <p>The thing is, if there is a refactor to be done, I will need to modify this switch AND the part where the form is defined. I would like to do something like</p> <pre><code>$mask = 'MASK_' . $participant-&gt;getRight(); $this-&gt;aclManager-&gt;addObjectPermissions($project, MaskBuilder::$mask, $user); </code></pre> <p>But havn't find a way to do it.</p> <p>Is my switch a good way to do it ? Or is there a proper php way to do the same, that would reduce refactor cost?</p>
[]
[ { "body": "<p>You mean something like this? </p>\n\n<pre><code>$mask = constant('Symfony\\Component\\Security\\Acl\\Permission\\MaskBuilder::MASK_' . $participant-&gt;getRight()) ?: null;\n$this-&gt;aclManager-&gt;addObjectPermission($project, $mask, $user);\n</code></pre>\n\n<p>Or if you don't care about readability:</p>\n\n<pre><code>$this-&gt;aclManager-&gt;addObjectPermission($project, constant('Symfony\\Component\\Security\\Acl\\Permission\\MaskBuilder::MASK_' . $participant-&gt;getRight())?:null, $user);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:43:19.890", "Id": "33870", "Score": "0", "body": "I'll definately try it tomorrow! I had try something similar with `constant` but it wasn't working. Something about private member, but maybe this way will work" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:14:17.563", "Id": "33902", "Score": "0", "body": "`Couldn't find constant MaskBuilder::MASK_VIEW` Since the constant is defined in another file I don't have access to it directly with the constant function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T15:43:00.800", "Id": "33909", "Score": "0", "body": "That sucks :( I'm all out of ideas on that front then (aside from `require_once()`'ing the file that contains the MaskBuilder class..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T16:09:46.007", "Id": "33914", "Score": "0", "body": "Yeah I thought about that but that would be breaking the way symfony include files because I already have a `use .../MaskBuidler` statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T16:42:14.743", "Id": "33915", "Score": "0", "body": "True. Also, the way Spiny Norman answered below doesn't seem to be an improvement over the way you wrote it (multiple function calls, array, etc are detrimental to performance). Perhaps Corwin or similar will jump into this question and offer a better answer than I have to offer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T19:36:08.170", "Id": "35600", "Score": "1", "body": "constant works fine, you just have to use the fully qualified classname: `constant('Symfony\\Component\\Security\\Acl\\Permission\\MaskBuilder::MASK_VIEW')`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:37:39.347", "Id": "21077", "ParentId": "21072", "Score": "2" } }, { "body": "<p>If you want to keep the constant names intact, you could use:</p>\n\n<pre><code>$mapping = array(\n 'VIEW' =&gt; MaskBuilder::MASK_VIEW,\n 'EDIT' =&gt; MaskBuilder::MASK_EDIT,\n 'OPERATOR' =&gt; MaskBuilder::MASK_OPERATOR,\n);\n\n$mask = array_key_exists($participant-&gt;getRight(), $mapping) \n ? $mapping[$participant-&gt;getRight()] \n : null;\n$this-&gt;aclManager-&gt;addObjectPermission($project, $mask, $user);\n</code></pre>\n\n<p>Or alternatively, put the mapping function on your MaskBuilder (especially if you don't have outside access to the constants on MaskBuilder):</p>\n\n<pre><code>class MaskBuilder\n{\n // (...)\n public static function getMask($right)\n {\n $mapping = array(\n 'VIEW' =&gt; self::MASK_VIEW,\n 'EDIT' =&gt; self::MASK_EDIT,\n 'OPERATOR' =&gt; self::MASK_OPERATOR,\n );\n\n if (array_key_exists($right, $mapping)) {\n return $mapping[$right];\n }\n\n return null;\n }\n}\n\n// (...later...)\n$this-&gt;aclManager-&gt;addObjectPermission(\n $project, \n MaskBuilder::getMask($participant-&gt;getRight()), \n $user\n);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:11:24.757", "Id": "33901", "Score": "0", "body": "Yeah I dont have access to map builder, it's a built-in librairy in Symfony" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:43:37.657", "Id": "34023", "Score": "0", "body": "@HugoDozois You might consider creating your own class that contains the 'getMask()' method. I.m.o. this answer/solution is clean and flexible (I update the answer above to reflect this option)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:30:54.910", "Id": "21109", "ParentId": "21072", "Score": "2" } }, { "body": "<p>I found the solution somewhere from the documentation. I don't know why I had not seen that before.</p>\n\n<p><a href=\"http://symfony.com/doc/2.1/cookbook/security/acl.html#cumulative-permissions\" rel=\"nofollow\">Symfony2</a> provides an easier way of doing what I was looking for:</p>\n\n<pre><code>$builder = new MaskBuilder();\n$mask = $builder-&gt;add($participant-&gt;getRight())-&gt;get();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:12:21.707", "Id": "21127", "ParentId": "21072", "Score": "3" } }, { "body": "<p>I would create a final type code class:</p>\n\n<pre><code>&lt;?php\n\nfinal class Mask {\n\n private $_name;\n private $_value;\n\n private static $_view;\n private static $_edit;\n private static $_operator;\n\n public static function View() {\n if (self::$_view == NULL) {\n self::$_view = new Mask(\"View\", 1);\n }\n return self::$_view;\n }\n\n public static function Edit() {\n if (self::$_edit == NULL) {\n self::$_edit = new Mask(\"Edit\", 2);\n }\n return self::$_edit;\n }\n\n public static function Operator() {\n if (self::$_operator == NULL) {\n self::$_operator = new Mask(\"Operator\", 4);\n }\n\n return self::$_operator;\n }\n\n private function __construct($name, $value) {\n $this-&gt;_name = $name;\n $this-&gt;_value = $value;\n }\n\n public function Name() {\n //can be localized or create a new method to get the localized name\n return $this-&gt;_name;\n }\n\n public function Value() {\n return $this-&gt;_value;\n }\n\n public function __toString() {\n return $this-&gt;_value;\n }\n\n}\n</code></pre>\n\n<ul>\n<li>Type hinted usage</li>\n<li>Can be add more method to the class</li>\n</ul>\n\n<p>Helpful thing can be to create a static method to get all type, and another one to parse the type from a value. Whith these things a $participant->getRight() could return an instance of Mask so the switch can be removed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:53:56.077", "Id": "21164", "ParentId": "21072", "Score": "1" } } ]
{ "AcceptedAnswerId": "21127", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T18:56:27.680", "Id": "21072", "Score": "3", "Tags": [ "php", "authorization" ], "Title": "Building an ACL based on permission level" }
21072
<p>I have the following bit of code the calls out to two different command line components (each wrapped in their own Task)</p> <pre><code>public async Task&lt;FileInfo&gt; RasterizeAllPdfs(IEnumerable&lt;Uri&gt; targetUris, FileInfo destination = null) { // rasterize uris to files in the rasterizedOutput directory await rasterize(rasterizedOutput.Value, targetUris); // concatenate all pdfs in this directory return await concatenatePdfs(rasterizedOutput.Value.EnumerateFiles("*.pdf"), destination); } </code></pre> <p>What I would like is for the method to return a task immediately and for the returned task to become resolved once the task returned by concatentatePdfs finishes running.</p> <p>It <em>seems</em> to work correctly (as in it's returning correct output) but I'm not 100% sure that I'm using the async and await keywords properly</p>
[]
[ { "body": "<p>You are using <code>async</code>/<code>await</code> absolutely correctly, that's how they were supposed to be used. </p>\n\n<p>Please note that from this code it's hard to tell whether the method will return the <code>Task</code> immediately, since it will be waiting synchronously for <code>rasterize</code> method to return the <code>Task</code>, and thus the answer depends on the implementation of <code>rasterize</code>.</p>\n\n<p>As a side note - you are using implicit dependency here (first method prepares files in folder, and second method enumerates all pdf files there). I would prefer explicit dependency: <code>rasterize</code> to return a collection of FileInfo objects consumed by the <code>concatenatePdfs</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:02:02.887", "Id": "33862", "Score": "0", "body": "Thanks, this is all private to a class so I'm not terribly concerned about explicit vs implicit dependencies. I think I might want to change what I'm doing though. I want the second method to be a continuation of the first completing successfully but I don't want to block the thread while this happens (hence return immediately). Do I have to use `ContinueWith()` in that case? Is that correct? Basically if this was jQuery deferreds I would want to return `firstMethodDeferred.pipe(secondMethod)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:15:44.463", "Id": "33864", "Score": "0", "body": "`await` does exactly that. You can think of it as \"the code after await will execute after the awaiting task completes\". It's implemented slightly differently to `ContinueWith`, but idea is the same" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:27:57.047", "Id": "33865", "Score": "0", "body": "So I'm not quite clear how to combine the two, simply placing the second line into a `ContinueWith` block doesn't work because now my return is `Task<Task<FileInfo>>` I basically have two tasks that I want to combine to run in sequence" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:28:10.623", "Id": "33866", "Score": "0", "body": "And about \"I don't want to block the thread while this happens\" - it will not block the thread if `rasterize` doesn't do heavy things synchronously, that is before the first await (assuming you're using awaits there as well). Just for you to understand: the first part of the method till first `await` is executed synchronously, and will continue to run synchronously in case when task being awaited is already completed at the time of awaiting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:30:33.363", "Id": "33867", "Score": "0", "body": "\"So I'm not quite clear...\" - you don't need `ContinueWith` here, your current code will run methods in sequence" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:57:32.740", "Id": "21081", "ParentId": "21078", "Score": "7" } } ]
{ "AcceptedAnswerId": "21081", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:43:47.353", "Id": "21078", "Score": "3", "Tags": [ "c#", "asynchronous", "async-await" ], "Title": "Am I using async C# correctly?" }
21078
<p>I created a quick program to test the precision of randomness generated by the <code>.rand</code> method. The primary question is whether I can use the <code>.times</code> method in place of the <code>while</code> code blocks to increase efficiency and: </p> <ol> <li>Whether such a practice would reduce the amount of processing required/if this would be at all significant.</li> <li>Whether it's a more common approach, or alternatively is it an infeasible/awkward approach.</li> <li><p>Even if it is a less acceptable approach than the one I've taken, how would I use the <code>.times</code> method to execute the same task. If it is inappropriate when should I use <code>.times</code>?</p> <pre><code># Initializes array and iterator. x = [] i = 0 # Stores 4000 random numbers 0..1 in array 'x' while i &lt; 4000 x &lt;&lt; rand(2) i += 1 end # Initializes array for the purpose of storing zeros and ones in separate # arrays for the sake of counting how many instances of each occur in the sample count_one = [] count_zero = [] # Resets iterator to 0 i = 0 # Stores instances of zero in `count_zero` and instances of one in `count_one` while i &lt; x.length if x[i] == 1 count_zero &lt;&lt; x[i] i += 1 else count_one &lt;&lt; x[i] i += 1 end end # Calculates final averages zero_average = count_zero.length.to_f/x.length.to_f * 100.0 one_average = count_one.length.to_f/x.length.to_f * 100.0 </code></pre></li> </ol> <p>Additionally, I am curious as to: </p> <ol> <li>How I could possibly have coded this for flexibility to better anticipate future needs. Example: If I later needed to perform the same operations on a larger range of numbers.</li> <li>If I am using extraneous/obvious facts in my commenting or if my commenting is otherwise not in good practice.</li> <li>What more insight I might be able to gain in general regarding my current coding practices. Thank you.</li> </ol>
[]
[ { "body": "<p>It looks like you've done some procedural programming before? In Ruby you usually avoid using iterator variables like the i for simplicity.</p>\n\n<p>The first while loop could be: <code>4000.times { x &lt;&lt; rand(2) }</code>\nA while loops is actually slightly quicker (>10%) but seldom used because object iterators are prettier.</p>\n\n<p>You could also use a functional approach like: <code>randoms = 4000.times.map { rand(2) }</code></p>\n\n<p>Also, descriptive, variable names are generally preferable.</p>\n\n<p>As for the second half of the script. Why store all the zeros and ones when you can just count them? This definitely will be faster as it doesn't require building up an array.</p>\n\n<p>e.g. <code>zeros_ratio = randoms.count(0) / randoms.length.to_f * 100</code></p>\n\n<p>So if you study <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html\" rel=\"nofollow\">http://www.ruby-doc.org/core-1.9.3/Array.html</a> a bit, you'll see how you can do a lot with 3 lines!</p>\n\n<p>You could make the script more flexible of course by parameterising it. Set 4000 to a variable at the beginning instead of referencing it explicitly in the working bits of your code.</p>\n\n<p>Commenting is nice, but usually a bit higher level than what you have there. Assume the reader could understand your code by reading it (so they can guess what a variable assignment to an appropriately named variable means), but comment to save them from having to think too hard about what the structure of your code is or what more complicated or crucial bits do.</p>\n\n<p>One general piece of advice for learning coding is to read the code of more advanced programmers. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:14:57.913", "Id": "21112", "ParentId": "21080", "Score": "1" } }, { "body": "<p>If you're interested in more idiomatic Ruby, my advice would be to thoroughly understand <strong>Array</strong>, <strong>Enumerable</strong>, and the <strong>functional style</strong> enabled by using blocks.</p>\n\n<p>The functional style allows you to use the output of one method directly as input to another method without intermediate variables. This is known as <em>method chaining</em>, and it reduces the number of intermediate variables you need to create.</p>\n\n<p>Let's start with your array creation:</p>\n\n<pre><code># Initializes array and iterator.\nx = []\ni = 0\n\n# Stores 4000 random numbers 0..1 in array 'x' \nwhile i &lt; 4000\n x &lt;&lt; rand(2)\n i += 1\nend\n</code></pre>\n\n<p>First, a bit about code comments. These are a bit gratuitous, as these repeat what the code says. Good comments should explain <em>why</em> something was done, not <em>what</em> is being done. If you feel that the code is non-obvious enough that you'll need a <em>what</em> comment, then it's time to think about refactoring so the code is a bit more self-explanatory.</p>\n\n<p>I've been programming in Ruby for years and have never needed an iteration variable or a while loop. Why? Because the iteration methods such as <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html\">Array</a>'s <code>each</code> or <a href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html\">Enumerable</a>'s <code>each_with_index</code> are so powerful. So, as you mentioned, you <em>could</em> use <code>times</code> and do this:</p>\n\n<pre><code>x = []\n4000.times do\n x &lt;&lt; rand(2)\nend\n</code></pre>\n\n<p>This is an improvement, but in this case we can do better. If you look at the constructor options for Array, you'll notice that you can specify the size <em>and also pass a block for an initial value</em>. Therefore, this can be written as:</p>\n\n<pre><code>Array.new(4000){ rand(2) }\n\n#=&gt; [1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0...]\n</code></pre>\n\n<p>The output is the same: a 4000-element array consisting of random zeros and ones.</p>\n\n<p>Now let's look at what you want to do next, according to your comment:</p>\n\n<pre><code># Initializes array for the purpose of storing zeros and ones in separate\n# arrays for the sake of counting how many instances of each occur in the sample\n</code></pre>\n\n<p>So we want to separate the array into two buckets, based on their value. Thinking functionally, we should ask if, instead of iterating over intermediate output and creating a new data structure (which is also intermediate output because it will be thrown away once you count them), is there something we can do directly to the array? It turns out that the Enumerable module contains <code>partition</code> which can take a block that does exactly that. </p>\n\n<pre><code>Array.new(4000){ rand(2) }.partition{ |digit| digit.zero? }\n\n#=&gt; [[0, 0, 0, 0, 0, 0, 0, 0, ...], [1, 1, 1, 1, 1, 1, 1, 1, ...]]\n</code></pre>\n\n<p>Partition will separate the array into two sub-arrays: one for which the block returns true; and the other for which the block returns false. Note that I also used the <code>zero?</code> method which is available for numbers (see <a href=\"http://www.ruby-doc.org/core-1.9.3/Fixnum.html#method-i-zero\">Fixnum#zero?</a>) where I could have just said <code>digit == 0</code>. Either one is fine, but using <code>zero?</code> allows me to use a shortcut. This is equivalent: </p>\n\n<pre><code>Array.new(4000){ rand(2) }.partition(&amp;:zero?)\n\n#=&gt; [[0, 0, 0, 0, 0, 0, 0, 0, ...], [1, 1, 1, 1, 1, 1, 1, 1, ...]]\n</code></pre>\n\n<p>This is known as the <code>Symbol#to_proc</code> trick which I won't go into detail here, but it basically allows you to shorten a block in the form <code>{|x| x.method}</code> to <code>&amp;:method</code>. Whenever you want to call the same method on every item in an array, it is useful. You'll see this quite often in Ruby code these days.</p>\n\n<p>Now, you don't really want these sub-arrays, you just want to know how many zeros and ones there are. Again thinking functionally, for each element in the array, you'd like its size. Enumerable's <code>map</code> is useful for transforming each element of an array.</p>\n\n<pre><code>Array.new(4000){ rand(2) }.partition(&amp;:zero?).map{ |subarray| subarray.size }\n\n#=&gt; [2038, 1962]\n</code></pre>\n\n<p>Which, using the <code>Symbol#to_proc</code> trick can be shortened to</p>\n\n<pre><code>Array.new(4000){ rand(2) }.partition(&amp;:zero?).map(&amp;:size)\n\n#=&gt; [1994, 2006]\n</code></pre>\n\n<p>So there you have it: using idiomatic Ruby and functional style, you can reduce the first 28 lines down to a single short, yet readable line. To answer question #1, any speed difference would be insignificant with arrays of this size. (Thought it would be interesting to benchmark the two approaches with huge arrays)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:41:57.350", "Id": "34032", "Score": "0", "body": "How do you access the partitioned arrays to calculate the percentage? And say I wanted to work with a larger range of randomly generated numbers, like (1..64). Would partition become inappropriate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T22:36:36.953", "Id": "34035", "Score": "1", "body": "Partition only separates into two parts. But Enumerable has `group_by` which handles an arbitrary number of parts. I highly recommend becoming *very* familiar with the methods available to you on `Array` and `Enumerable`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:54:00.727", "Id": "21180", "ParentId": "21080", "Score": "7" } }, { "body": "<p>When you do <em>not</em> provide a block to a method from a container which is expecting one, Ruby (1.9) does generally <em>not</em> return an Error but an Enumerator, which has all kinds of methods of it's own:</p>\n\n<pre><code>puts 4000.times.count{ rand(2).zero? } #=&gt; 1975\n</code></pre>\n\n<p>Choosing between <code>times</code> or <code>each</code> (<code>(0..4000).each.count...</code>) or <code>for</code> or <code>while</code> is not very important. It's what you do inside the loop that , ehm, counts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T00:04:11.553", "Id": "21402", "ParentId": "21080", "Score": "1" } } ]
{ "AcceptedAnswerId": "21180", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:54:57.937", "Id": "21080", "Score": "5", "Tags": [ "ruby", "array", "random", "iterator", "iteration" ], "Title": "Most efficient way to iterate through arrays/can I use .times method in place of while method?" }
21080
<p>A basic shell function to <a href="https://unix.stackexchange.com/questions/9123/is-there-a-one-liner-that-allows-me-to-create-a-directory-and-move-into-it-at-th/9124#9124">create a directory and change to it</a> goes like this:</p> <pre><code>mkcd () { mkdir "$1" &amp;&amp; cd "$1"; } </code></pre> <p>This works well in many cases but breaks in unusual cases (e.g. if the argument begins with <code>-</code>).</p> <p>I'm writing a more sophisticated version. This version calls <code>mkdir -p</code> to create parent directories if needed and just change to the directory if it already exists. It has these design goals:</p> <ul> <li>Work in any POSIX compliant shell.</li> <li>Cope with any file name.</li> <li>If the shell has logical directory tracking, where <code>foo/..</code> is the current directory even if <code>foo</code> is a symbolic link to a directory, then the function must follow that logical tracking: it must act as if the <code>cd</code> builtin was called and magically created the target directory.</li> <li>If a directory is created, it is guaranteed that the function changes into it, as long as there is no race condition (another process moving a parent directory, changing relevant permissions, …).</li> </ul> <p>Here is my best current effort. Does it meet the goals above? Are there situations where the behavior is surprising?</p> <pre class="lang-bsh prettyprint-override"><code>mkcd () { case "$1" in */..|*/../) cd -- "$1";; # that doesn't make any sense unless the directory already exists /*/../*) (cd "${1%/../*}/.." &amp;&amp; mkdir -p "./${1##*/../}") &amp;&amp; cd -- "$1";; /*) mkdir -p "$1" &amp;&amp; cd "$1";; */../*) (cd "./${1%/../*}/.." &amp;&amp; mkdir -p "./${1##*/../}") &amp;&amp; cd "./$1";; ../*) (cd .. &amp;&amp; mkdir -p "${1#.}") &amp;&amp; cd "$1";; *) mkdir -p "./$1" &amp;&amp; cd "./$1";; esac } </code></pre>
[]
[ { "body": "<p>Some error messages may be confusing like:</p>\n\n<pre><code>$ mkcd /foo/../bar\nmkcd:cd:3: no such file or directory: /foo/..\n$ mkcd /bin/../bar\nmkdir: cannot create directory `./bar': Permission denied\n</code></pre>\n\n<p>Probably not much you can do about that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T23:46:44.030", "Id": "33872", "Score": "1", "body": "I don't find the message from `cd` particularly bad: at least it's true. On the other hand the message from `mkdir` is wrong in that case. `mkdir … 2>&1 | sed …`? Or rather `error=$(mkdir 2>&1 …) || …` to keep the return status." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T23:41:20.020", "Id": "21085", "ParentId": "21082", "Score": "2" } }, { "body": "<p>You should be able to get away with handling only two error cases (empty or no parameter) and three path possibilities: Absolute path, relative path which starts with <code>./</code> and other (\"dangerous\") paths:</p>\n\n<pre><code>mkcd() {\n if [ -z \"${1:-}\" ]\n then\n printf '%s\\n' 'Usage: mkcd PATH'\n return 2\n fi\n\n case \"$1\" in\n /*|./*) break;;\n *) set -- \"./$1\";;\n esac\n\n mkdir -p \"$1\" &amp;&amp; cd \"$1\"\n}\n</code></pre>\n\n<p>You won't need the <code>--</code> separator. It might be surprising that <code>mkcd foo/../bar</code> would create <em>both</em> directories if they don't exist, but that's more to do with <code>mkdir</code> than the script.</p>\n\n<p>Of course, this doesn't recursively simplify the path, which you'd need to do if you want to create the simplest absolute path defined (as printed by <code>readlink -f</code>, which is not in POSIX). But this would be surprising behavior, since <code>cd foo/../..</code> fails even when <code>../</code> exists.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T12:49:43.913", "Id": "38097", "Score": "0", "body": "If it was only a matter of the initial `-`, then `mkdir -p -- \"$1\" && cd -- \"$1\"` would almost suffice (except for the oddball case of a [directory named `-`](http://unix.stackexchange.com/questions/53017/how-do-you-enter-a-directory-thats-name-is-only-a-minus/53021#53021)). The real complexity is in simulating the shell's logical directory tracking, when the argument contains `foo/..` where `foo` is a symlink." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T12:04:58.497", "Id": "24662", "ParentId": "21082", "Score": "1" } }, { "body": "<p>I try this command <code>mkcd --help</code> results in a new folder named <code>--help</code> and it cd to this folder, but if I try <code>mkdir --help</code> gives below output that I believe the correct behavior:</p>\n\n<pre><code>Usage: mkdir [OPTION]... DIRECTORY...\nCreate the DIRECTORY(ies), if they do not already exist.\n\nMandatory arguments to long options are mandatory for short options too.\n -m, --mode=MODE set file mode (as in chmod), not a=rwx - umask\n -p, --parents no error if existing, make parent directories as needed\n -v, --verbose print a message for each created directory\n -Z set SELinux security context of each created directory\n to the default type\n --context[=CTX] like -Z, or if CTX is specified then set the SELinux\n or SMACK security context to CTX\n --help display this help and exit\n --version output version information and exit\n\nGNU coreutils online help: &lt;https://www.gnu.org/software/coreutils/&gt;\nFull documentation at: &lt;https://www.gnu.org/software/coreutils/mkdir&gt;\nor available locally via: info '(coreutils) mkdir invocation'\n</code></pre>\n\n<p>I can't remove <code>--help</code> folder after it created, <code>zsh-5.7</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T02:22:11.567", "Id": "212356", "ParentId": "21082", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T22:25:31.857", "Id": "21082", "Score": "11", "Tags": [ "bash", "shell", "unix" ], "Title": "Make a directory and change to it" }
21082
<p>My code blinks text for an interval of time then clears the text.</p> <p>I plan to use this code in a quiz web app. When the user gets an answer right, "CORRECT!" will blink on the screen for 10 seconds. When the user gets an answer wrong, "INCORRECT!" will blink on the screen for 10 seconds.</p> <p>I'm looking for feedback on how I could simplify and improve it?</p> <p>JS Bin: <a href="http://jsbin.com/ojetow/1/edit" rel="nofollow">http://jsbin.com/ojetow/1/edit</a></p> <pre><code>&lt;div id="blinkText"&gt;&lt;/div&gt; &lt;script&gt; // Takes text to blink and id of element to blink text in function blinkText(text, id) { // Blink interval setInterval(blinker, 250); // Flag to see what state text is in (true or false) var flag = true; // Number of times to blink text var blinkNum = 10; var i = 1; var divID = document.getElementById(id); function blinker() { if (i &lt; blinkNum) { if (flag) { divID.innerHTML = text; flag = false; } else { divID.innerHTML = ""; flag = true; } i++; } else { // Delete if it's still showing divID.innerHTML = ""; // Stop blinking clearInterval(blinker); } } } blinkText("Hello World", "blinkText"); &lt;/script&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T15:08:28.713", "Id": "33908", "Score": "0", "body": "I would suggest using a library, for example:\nhttp://docs.jquery.com/UI/Effects/Pulsate" } ]
[ { "body": "<p>It doesn't look very complex to me but the variable names could use some attention, as they're not very descriptive. I'd suggest:</p>\n\n<ul>\n<li><code>textHidden</code> instead of <code>flag</code></li>\n<li><code>timesBlinked</code> instead of <code>i</code></li>\n<li><code>targetElement</code> instead of <code>divID</code> (it's not an id anymore, but the element referred to by the id)</li>\n</ul>\n\n<p>I would also toggle the element visibility instead of removing and adding the text for several reasons, one of them being that removing text can also change the element's height and/or width, which can cause problems with the layout.</p>\n\n<pre><code>if( textHidden ) {\n targetElement.style.visibility = 'visible';\n} else {\n targetElement.style.visibility = 'hidden';\n}\n\ntextHidden = !textHidden; // flip the flag\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:35:50.670", "Id": "21110", "ParentId": "21086", "Score": "4" } } ]
{ "AcceptedAnswerId": "21110", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T00:48:59.773", "Id": "21086", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "Blink Text with JavaScript" }
21086
<p>I have such method and have a hard time optimizing it to run better. It takes roughly 1 sec with 100 units to get between <code>NSLog(@"Debug2")</code> and <code>NSLog(@"Debug3")</code>. And 2 sec on iPhone.</p> <p>Method idea: </p> <p><strong>Input</strong>: </p> <ul> <li><code>NSMutableArray</code> <code>times</code> - containing times (2012-12-12, 2013-01-19) and etc </li> <li><code>NSMutableArray</code> <code>objectArray</code> - contains <code>LogUnit</code> objects.</li> </ul> <p><strong>Output</strong>: Array of computed views.</p> <p>Main idea: a view for each time with objects from <code>objectArray</code> whose time is the same.</p> <p>I have made it faster by showing a small proportion of objects (see <code>counted</code> in code and <code>_breakPlease</code>), yet it's still not fast enough.</p> <pre><code>- (NSMutableArray*) sortViews: (NSMutableArray *)times and:(NSMutableArray *)objectArray { NSLog(@"debug2"); NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:times.count]; NSString *number = [NSString stringWithFormat:@"SortLog%i ",[[NSUserDefaults standardUserDefaults] stringForKey:@"ObjectNumber"].intValue]; NSString *comp = [[NSUserDefaults standardUserDefaults] stringForKey:number]; LogUnit *unit; int counted = 0; for(int x = 0; x != times.count; x++) { @autoreleasepool { UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)]; foo.backgroundColor = [UIColor clearColor]; int f = 0; int h = 0; NSString *attributeName = @"realTime"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K IN %@", attributeName, [times objectAtIndex:x]]; // Filter the objectArray by the time, so we don't have to run through all the objects in objectArray, and check if time is right. NSArray *filtered = [objectArray filteredArrayUsingPredicate:predicate]; for(int i = 0; i != filtered.count; i++) { unit = [filtered objectAtIndex:i]; // Filter units by user choice (comp). Like comp = Warnings or comp = Errors and etc. if([[unit status] isEqualToString:comp] || [comp isEqualToString:NULL] || comp == NULL) { // testing if the unit is correct to use if([unit getEvent] != NULL) { // below is some computation for frames, to get them to proper position unit.view.frame = CGRectMake(unit.view.frame.origin.x, f * unit.view.frame.size.height + 30, unit.view.frame.size.width, unit.view.frame.size.height); [foo addSubview:unit.view]; counted++; f++; h = unit.view.frame.size.height * f; } } } UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)]; myLabel.backgroundColor = [UIColor clearColor]; myLabel.font = [UIFont boldSystemFontOfSize:20]; myLabel.textColor = [UIColor colorWithRed:88 green:154 blue:251 alpha:1]; myLabel.textAlignment = UITextAlignmentCenter; myLabel.text = [times objectAtIndex:x]; // Just adding a label with "2012-12-30" or etc on top of the view. [foo addSubview:myLabel]; foo.frame = CGRectMake(0,0, 320, h + 30 ); h = 0; [views addObject:foo]; // counting added views for performance, if more than 30, return, and show only small portion of whole units, user has the option to show all the units if he wants to, but that takes a time to load.. if(counted &gt; 30 &amp;&amp; filtered.count != counted) { if(_breakPlease == false) { _broken = true; break; } } } } NSLog(@"debug3"); return views; } </code></pre>
[]
[ { "body": "<p><code>times.count</code> in <code>for(int x = 0; x != times.count; x++)</code> is a method call, move it to a variable. Also, you should probably use the <code>&lt;</code> instead of <code>!=</code> as it is more common.</p>\n\n<p>However, as you don't really need the index of the element, you can replace both iterations</p>\n\n<pre><code>for(int i = 0; i != filtered.count; i++) {\n unit = [filtered objectAtIndex:i];</code></pre>\n\n<p>by native iteration</p>\n\n<pre><code>for (LogUnit* unit in filtered) {</code></pre>\n\n<p>Is <code>@autoreleasepool</code> necessary in every iteration? Having it outside <code>for</code> should help performance as well. In most application you are not required to use <code>@autoreleasepool</code> at all.</p>\n\n<pre><code>NSString *attributeName = @\"realTime\";\nNSPredicate *predicate = [NSPredicate predicateWithFormat:@\"%K IN %@\", attributeName, [times objectAtIndex:x]];\n// Filter the objectArray by the time, so we don't have to run through all the objects in objectArray, and check if time is right.\nNSArray *filtered = [objectArray filteredArrayUsingPredicate:predicate];\n</code></pre>\n\n<p>Your filtering doesn't do what your comment describes. You don't want to run through all the objects but that's exactly the thing <code>filteredArrayUsingPredicate:</code> does. Only using reflexion and moving the objects into a new array. By using the filtering code, you are losing performance.</p>\n\n<p>There are various code quality issues not related to performance:</p>\n\n<ol>\n<li><p>usage of variable names <code>x</code>, <code>f</code>, <code>h</code>, <code>objectArray</code>. Use more descriptive names or use <code>i</code>, <code>j</code>, <code>k</code> for iterators.</p></li>\n<li><p>Move some code to separate methods, e.g. view generation.</p></li>\n<li><p>Don't use <code>NULL</code> in Obj-C, use <code>nil</code>. <code>NULL</code> is to be used only when you interact with C pointers, not Obj-C objects.</p></li>\n<li><p><code>[comp isEqualToString:NULL]</code> will never evaluate to <code>YES</code> (<code>true</code>)</p></li>\n<li><p><code>if(_breakPlease == false)</code> Don't use <code>false</code> in Obj-C. Use <code>YES</code> or <code>NO</code>. Never ever compare a <code>BOOL</code> with a bool literal. Use logical operators instead, e.g. <code>if (!_breakPlease)</code>.</p></li>\n</ol>\n\n<p><b>Algorithm performance:</b></p>\n\n<p>The main problem of your algorithm is its complexity. Basically you have two arrays and you compare objects from an array with all objects from the other array. That's <code>O(n^2)</code></p>\n\n<p>There are many ways how you could improve this, I will list some of them:</p>\n\n<ol>\n<li><p>Don't use a <code>NSArray</code> to store the log units. Use a <code>NSDictionary</code> where time is the key and log unit, or possibly array of log units with the same time, is the value. Finding log units with the given time will be trivial then.</p></li>\n<li><p>Sort <code>times</code> and <code>objectArray</code> by time. You can then iterate through both arrays at the same time and you get <code>O(n + n * log n)</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T10:27:17.343", "Id": "33890", "Score": "0", "body": "Thank you for your answer, and tips on quality of my code. Just one thing about filteredArrayUsingPredicate.. I shouldn't use it, and just iterate through whole objectArray and inside that loop check if time is correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T10:37:34.147", "Id": "33891", "Score": "0", "body": "@Datenshi Yes, just remove the filtering and add a check after the second `for`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T10:41:00.057", "Id": "33892", "Score": "0", "body": "@Datenshi Added more iteration improvements." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T10:02:52.900", "Id": "21104", "ParentId": "21099", "Score": "2" } }, { "body": "<p>if you are looping over a collection, you should use enumeration. This could be fast enumeration (as shown by Sulthan <code>for (LogUnit* unit in filtered)</code>) or even better block based enumeration.</p>\n\n<pre><code>[filtered enumerateObjectsUsingBlock:^(LogUnit *unit, NSUInteger idx, BOOL *stop) {\n //…\n}];\n</code></pre>\n\n<p>This has <strike>two</strike> one advantage<strike>s</strike> over fast enumeration:</p>\n\n<ul>\n<li><strike>it is even faster (on stack overflow some say ~15%)</strike><sub>this was misinformation</sub></li>\n<li>You get also an index passed into the block, that you can use for calculating frames and similar</li>\n</ul>\n\n<p>further benefits of enumeration in general</p>\n\n<ul>\n<li>The enumeration is more efficient than using NSEnumerator directly.</li>\n<li>The syntax is concise.</li>\n<li>The enumerator raises an exception if you modify the collection while enumerating.</li>\n<li>You can perform multiple enumerations concurrently.</li>\n</ul>\n\n<p>apple's doc: <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html#//apple_ref/doc/uid/20000135-BBCFABCB\" rel=\"nofollow\">Enumeration: Traversing a Collection’s Elements</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T21:22:03.980", "Id": "41199", "Score": "0", "body": "Do you have a link handy for the ~15% performance estimate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T21:38:58.273", "Id": "41201", "Score": "0", "body": "Hey @Nate, see my edited answer. it is not true. and that answer disappeared from stackoverflow. indeed fast enumeration usually is a bit after than block-based enumeration." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T11:44:12.443", "Id": "21107", "ParentId": "21099", "Score": "2" } } ]
{ "AcceptedAnswerId": "21104", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T07:25:51.597", "Id": "21099", "Score": "1", "Tags": [ "objective-c", "ios" ], "Title": "Optimizing iOS method in objective-c" }
21099
<p>Someone asked me if I can create factory pattern in java without using If-else construct. So I come with the following. Please provide your inputs if this seems a good example for using factories.</p> <pre><code>public enum EnumButtonFactory { RADIO(RadioButton.class), SUBMIT(SubmitButton.class), NORMAL(NormalButton.class); private Class&lt;? extends Button&gt; button; EnumButtonFactory(Class&lt;? extends Button&gt; b) { this.button = b; } public Button get() { try { return button.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:31:59.087", "Id": "33899", "Score": "2", "body": "Can you provide an example for the use case? What do you want to replace with this implementation. This could help to get the direction. Because the typical factory pattern does not necessarily need if-then-else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T00:58:33.753", "Id": "34269", "Score": "1", "body": "You could use a hash and pull the correct factory out of the hash based on some criteria. You could also do something like a chain of responsibility. @tb I think the problem the OP is trying to solve is a builder or abstract factory that needs to pull up one of several specific factories." } ]
[ { "body": "<p>This is a good example for demonstrating that you can implement factory pattern without conditional statements. Of course, no piece of code is good for every imaginable requirement.</p>\n\n<p>In real world cases factory pattern usually needed because some aspect of the object building is not trivial. One such case is when you do not have the concrete classes at compile time. e.g. when you are a library/framework developer and the user will have the concrete classes. In that case you would want to externalize the class names to the program configuration. This program requires that you have the <code>SubmitButton.class</code> et al at compile time, and is dependent of those concrete classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:38:16.207", "Id": "34006", "Score": "0", "body": "I somewhat agree but typically Factory pattern solves the problem of object creation and needs a sub class to be there. When you say that some classes are not known at run time, can you elaborate that how will have your factory return those objects? IMHO the case you are talking about fits into the domain of Proxy pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:42:03.553", "Id": "21115", "ParentId": "21102", "Score": "5" } }, { "body": "<p>I think its not appropriate to call it Factory pattern. Most people refer to <strong>Factory Method Pattern</strong> as <strong>Factory Pattern</strong>. I have seen some references where its called as <strong>Simple Factory Pattern</strong> to clearly distinguish the two. Also its not a GOF pattern. </p>\n\n<p>You can use different approaches but idea is that you are creating objects based on some parameter. In one case i had used reflection to implement <strong>Simple Factory Pattern</strong> because i had around 100 odd classes so putting if/else would have been a daunting task. </p>\n\n<pre><code> String qualifiedClassName = \"Library1\"; //fully qualified class name\n Library library = (Library) Class.forName(qualifiedClassName).newInstance(); \n library.execute(); //call method after creating object\n</code></pre>\n\n<p><strong>Library</strong> class is super class and <strong>Library1</strong> is one of the sub class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T04:33:47.520", "Id": "21326", "ParentId": "21102", "Score": "2" } }, { "body": "<p>A static createInstance method would be safer instead of newInstance. Also, agreeing with rai.skumar, I would rather call it Factory Strategy or something similar. But actually I find your idea quite smart and elegant :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T08:59:35.733", "Id": "21330", "ParentId": "21102", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T08:36:57.780", "Id": "21102", "Score": "10", "Tags": [ "java", "design-patterns" ], "Title": "FactoryPattern without If-else construct" }
21102
<p>I'm currently using this pattern to create and extend a globally accessible custom plugin to be used in a web application:</p> <pre><code>; // defensive programming: script may be concatenated with others (function($) { "use strict"; // allow Plugin to be extended from other scripts var window.Plugin = window.Plugin || {}; var privateVars = { // this contains all of the plugin's "private static" fields }; function someHelperFunction() { // this is a private method } $.extend(window.Plugin, { method1: function() { // this is a public method }, method2: function() { // this is a public method } }); })(jQuery); </code></pre> <p>This approach looks fine to me and seems to tick all the boxes. However, since I'm far from a JS guru I wonder:</p> <p><strong>Are there any issues with the above pattern that I should be aware of?</strong></p> <p>Now suppose I want to introduce global configuration that affects the behavior of all subsequent calls to <code>method1</code>, for example allow the user to register a callback that will get fired every time before <code>method1</code> executes.</p> <p>In my mind, this syntax would be nice:</p> <pre><code>window.Plugin.method1.registerCallback(function() { ... }); window.Plugin.method1(); // take it for a test drive </code></pre> <p><strong>Is this a good idea? If not, why? What would be a better approach?</strong></p> <p>To implement this, I would do</p> <pre><code>window.Plugin = { ... }; // as above window.Plugin.method1.registerCallback = function() { // this would write something inside privateVars }; </code></pre> <p><strong>Is there a more convenient way to add many properties to <code>method1</code> like this?</strong></p> <p>For example, one that would not require one statement per property to be added. Should I use <code>jQuery.extend</code> for this as well?</p>
[]
[ { "body": "<p>The usual way to create a plugin is to declare a namespace or use an existing and append to it. Usually done using the module pattern:</p>\n\n<pre><code>(function(ns){\n\n //private scoping\n var privVar = '...';\n function priv(){...}\n\n //expose a function\n ns.myFunc = function(){...};\n\n}(this.myLib = this.myLib || {}));\n\n//using the exposed myFunc\nmyLib.myFunc();\n</code></pre>\n\n<p>Issues with your code? Well, it depended on jQuery just to append methods. It's not really necessary to use extend. With the above pattern, you can cleanly add functions to the namespace.</p>\n\n<p>If you really need just some parts of jQuery, you can grab their code and just use it directly. I usually interrogate the code and pick out only the parts that are necessary. Or you can roll your own jQuery build. They have instructions on their GitHub on how to roll your own mix of jQuery.</p>\n\n<p>Now, for function callbacks, you should use the a technique similar to pub-sub or event emitters or jQuery's <code>on</code> method. The syntax looks like this:</p>\n\n<pre><code>myLib.on('fnName',function(){...});\n</code></pre>\n\n<p>where <code>fnName</code> is the function name that is equivalent to the function called.</p>\n\n<p>Now how to implement?</p>\n\n<p>Well, each of your functions should call a special internal function that fires callbacks collected in your library. Basically, the <code>on</code>, method of your library just collects callbacks and registers them in an internal cache id'ed with the name of the function. The implementation would look like this:</p>\n\n<pre><code>(function(){\n\n //handler cache\n var handlers = {};\n\n //our internal function that executes handlers with a given name\n function executeHandlers(eventName){\n //get all handlers with the selected name\n var handler = handlers[eventName] || []\n , len = handler.length\n , i\n ;\n //execute each\n for(i = 0; i&lt; len; i++){\n //you can use apply to specify what \"this\" and parameters the callback gets\n handler[i].apply(this,[]);\n }\n }\n\n //our on function which collects handlers\n ns.on = function(eventName,handler){\n //if no handler collection exists, create one\n if(!handlers[eventName]){\n handlers[eventName] = [];\n }\n handlers[eventName].push(handler);\n }\n\n //so we expose a shout function\n ns.shout = function(){\n\n ...stuff shout does...\n\n //now we execute callbacks registered to shout\n executeHandlers('shout');\n }\n\n}(this.myLib = this.myLib || {}));\n\n//we register a callback\nmyLib.on('shout',function(){\n //executed after calling shout\n});\n\n//execute shout\nmyLib.shout();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:07:47.800", "Id": "21147", "ParentId": "21105", "Score": "9" } } ]
{ "AcceptedAnswerId": "21147", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T10:57:01.853", "Id": "21105", "Score": "7", "Tags": [ "javascript", "design-patterns", "plugin" ], "Title": "Pattern for creating a globally accessible custom plugin" }
21105
<p>Could I code differently to slim down the point of this Python source code? The point of the program is to get the user's total amount and add it to the shipping cost. The shipping cost is determined by both country (Canada or USA) and price of product: The shipping of a product that is $125.00 in Canada is $12.00.</p> <pre><code>input ('Please press "Enter" to begin') while True: print('This will calculate shipping cost and your grand total.') totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', ''))) Country = str(input('Type "Canada" for Canada and "USA" for USA: ')) usa = "USA" canada = "Canada" lessFifty = totalAmount &lt;= 50 fiftyHundred = totalAmount &gt;= 50.01 and totalAmount &lt;= 100 hundredFifty = totalAmount &gt;= 100.01 and totalAmount &lt;= 150 twoHundred = totalAmount if Country == "USA": if lessFifty: print('Your shipping is: $6.00') print('Your grand total is: $',totalAmount + 6) elif fiftyHundred: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif hundredFifty: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) if Country == "Canada": if lessFifty: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif fiftyHundred: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif hundredFifty: print('Your shipping is: $12.00') print('Your grand total is: $',totalAmount + 12) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) endProgram = input ('Do you want to restart the program?') if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'): break </code></pre>
[]
[ { "body": "<p>Sure you can condense some things, and improve the input loop. But I find your original code easy to read, whereas this is probably harder to read : </p>\n\n<pre><code>banner = 'Now we\\'ll calculate your total charge, including shipping.'\ncost_prompt = 'Enter your total purchase amount : '\ncountry_prompt = 'Where are you shipping to ?\\nEnter \"USA\" for the USA or \"Canada\" for Canada : '\nshippingis = 'Your shipping is '\ngrandtotalis = 'Your grand total is: '\nexit_prompt = 'Type q to quit, or enter to continue: '\nshiplaw = {\n 'USA' : {\n 0 : 6, 1 : 8, 2 : 10, 3 : 0\n },\n 'CANADA' : {\n 0 : 8, 1 : 10, 2 : 12, 3 : 0\n }\n }\n\ndef get_int(prompt):\n try: return int(float(raw_input(prompt).replace(',','').replace('$','')))\n except: return None\n\ndef dollars_n_cents(*vals):\n return '$' + str(int(sum(vals))) + '.00'\n\ndef response(total,shipping):\n shippingstr = 'free!' if shipping == 0 else dollars_n_cents(shipping)\n return (shippingis + shippingstr, grandtotalis + dollars_n_cents(total,shipping))\n\n\ndef run():\n while True:\n print banner\n total_amount = get_int(cost_prompt)\n while total_amount is None: total_amount = get_int(cost_prompt)\n country_str = raw_input(country_prompt)\n while country_str.upper() not in shiplaw: country_str = raw_input(country_prompt)\n result = response(total_amount,shiplaw[country_str.upper()][min(3,total_amount/50)])\n print '\\n'.join(result)\n try : \n if raw_input(exit_prompt)[0] == 'q': break\n except : pass\n\nimport sys\nif __file__ == sys.argv[0]:\n run()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T06:31:57.707", "Id": "21097", "ParentId": "21113", "Score": "0" } }, { "body": "<ul>\n<li><p>First thing is you don't perform much test on the user input. That's fine if that's just a little tool for yourself but I you plan to make it available for other users, it might be a good idea to have a few more checks.</p></li>\n<li><p>You are storing \"USA\" and \"Canada\" in variables which looks like a good idea. However, you don't use it later on. You could do something like : <code>Country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))</code> and then <code>if Country == canada:</code> and <code>if Country == usa:</code></p></li>\n<li><p>A string can't be both \"Canada\" and \"Usa\". Thus, <code>if Country == canada:</code> could become <code>elif Country == canada:</code></p></li>\n<li><p>As this \"print('Your shipping is: $X.00') print('Your grand total is: $',totalAmount + X)\" is repeted many times. It would probably be a could thing to make it a function taking a shippingFee and totalAmount as arguments and doing all the printing for you. Otherwise, instead of having the printing everywhere, you could just update a shippingFee variable and make the printing at the end.</p></li>\n<li><p>I'm not sure that storing the result of the comparison in variables is a really good idea, especially if you give them names containing written numbers : if you want to change one thing, you'll end up changing everything. On top of that, your conditions are dependant on each other : if you've already checked that <code>totalAmount &lt;= 50</code>, if your elif condition, you already know that <code>totalAmount &gt; 50</code>. Thus, your logic could be : <code>if totalAmount &lt;= 50: foo elif totalAmount &lt;=100: bar elif totalAmount &lt;= 150: foobar else: barfoo</code></p></li>\n<li><p>Other variables have non conventional names. For instance, <code>country</code> would be better than <code>Country</code></p></li>\n<li><p>It might be interesting to check the amount before considering the country.</p></li>\n</ul>\n\n<p>In conclusion, the code could be like (it doesn't behave exactly like your and I haven't tested it):</p>\n\n<pre><code>usa = \"USA\"\ncanada = \"Canada\"\n\ninput ('Please press \"Enter\" to begin')\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n\n totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', '')))\n country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))\n if country not in (canada, usa):\n print \"Invalid country\"\n continue\n\n shippingFee = 0\n if totalAmount&lt;50:\n shippingFee = 6\n elif totalAmount &lt; 100:\n shippingFee = 8\n elif totalAmount &lt; 150:\n shippingFee = 10\n\n if shippingFee != 0 and country == canada:\n shippingFee = shippingFee+2\n\n if shippingFee: # this could be using a ternary operator but that's a detail\n print('Your shipping is: Free')\n else:\n print('Your shipping is: $',shippingFee)\n print('Your grand total is: $',totalAmount + shippingFee)\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T08:57:26.383", "Id": "33886", "Score": "0", "body": "`if shippingFee` should probably be `if not shippingFee`. For consistency, `if shippingFee != 0` can also be written as just `if shippingFee`. Rather than listing all case variations of 'no' and 'false', just use call `lower()` on `input`. On a final note, in Python generally underscore_style is preferred over camelCase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T09:58:57.210", "Id": "33889", "Score": "0", "body": "line 9, in <module>\n country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))\nTypeError: input expected at most 1 arguments, got 5" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T06:45:55.010", "Id": "21098", "ParentId": "21113", "Score": "2" } }, { "body": "<p>I would not hard-code the fee logic, but instead store it as pure data. It's easier to maintain, even allowing to load it from a file.\nThen, it boils down to a range-based lookup, which is quite classical (cf <code>HLOOKUP</code> in spreadsheet software, with so called \"approximate search\").</p>\n\n<p>In Python, we can perform such a search via <code>bisect</code>, relying on lexicographic order (and infinity as an unreachable upper bound).</p>\n\n<p>Separated core logic would look like :</p>\n\n<pre><code>from bisect import bisect\n\n#For each country, list of (x,y) = (cost_threshold, fee)\n#For first x such cost &lt;= x, pick y for fee.\ninf = float(\"inf\")\nshippingFees = { 'USA' : [ (50, 6), (100, 8), (150, 10), (inf, 0) ],\n 'CANADA' : [ (50, 8), (100, 10), (150, 12), (inf, 0) ]\n }\n#Make sure it is sorted (required for lookup via bisect)\n#FIXME : Actually it would be better to assert it is already sorted,\n# since an unsorted input might reveal a typo.\nfor fee in shippingFees.values() : fee.sort()\n\ndef getShippingFee(amount, country):\n fees = shippingFees[country.upper()] #raise KeyError if not found.\n idx = bisect(fees, (amount,) )\n return fees[idx][1]\n</code></pre>\n\n<hr>\n\n<h2>Update</h2>\n\n<p>Here is a sample of \"working application\" using the helper function, assuming you have saved the code snippet above as <code>prices.py</code> (which should be stored in a module, but that's another story).</p>\n\n<p>NB : I have dropped the exit part, since I don't like to type <code>no</code> when I can hit CTRL+C.</p>\n\n<pre><code>#!/usr/bin/python2\n\"\"\" Your description here \"\"\"\n\nfrom prices import getShippingFee\n\nprint('This will calculate shipping cost and your grand total.')\n\nwhile True:\n\n #TODO : proper input processing, python3 compatible.\n totalAmount = float(raw_input('Enter your total amount: ').replace(',', '').replace('$', ''))\n country = raw_input('Type \"Canada\" for Canada and \"USA\" for USA: ').strip().upper()\n\n try : #TODO : proper country check.\n shippingFee = getShippingFee(totalAmount, country)\n grandTotal = totalAmount + shippingFee\n if shippingFee :\n print('Your shipping cost is: %.2f' % shippingFee)\n else :\n print('Your shipping is free!')\n print('Your grand total is: %.2f' % grandTotal)\n\n except KeyError :\n print (\"Sorry, we don't ship to this hostile country : %s\" % country)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:36:20.053", "Id": "33895", "Score": "0", "body": "Could you explain more into your script? I don't understand how to make it work into a working application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:42:31.687", "Id": "33974", "Score": "0", "body": "This is a great answer especially in a production environment where the code is liable to be changed by someone other than the original author. Someone could easily guess how to add another country or modify the fees structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:04:48.813", "Id": "34015", "Score": "1", "body": "@sotapme Thank you ! The main benefit is that the very same data structure can be reused, to generate shipping cost table in web page for instance. This follows [DRY](http://c2.com/cgi/wiki?DontRepeatYourself) principle : _Every piece of knowledge must have a single, unambiguous, authoritative representation within a system._" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:17:57.743", "Id": "21108", "ParentId": "21113", "Score": "10" } }, { "body": "<p>One thing you could do is to calculate the shippingCost first, and then print with this logic</p>\n\n<pre><code>if shippingCost = 0\n print: free shipping\nelse \n print: your shipping is shippingCost\nend\nprint: grandtotal = totalAmount+shippingCost\n</code></pre>\n\n<p>It should not be too hard to translate this into proper python.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:40:17.327", "Id": "21114", "ParentId": "21113", "Score": "0" } }, { "body": "<ul>\n<li>Your example is broken. I don't think <code>while True: print(...)</code> is what you are looking for.</li>\n<li>I cannot see why you are eliminating all the commas from the input <code>totalAmount</code> and use <code>int(float(...))</code> anyway.</li>\n<li>Your <code>elif twoHundred:</code> will fail for <code>0</code>.</li>\n</ul>\n\n<p>I suggest to put input validation into a for loop with some error handling. Just as a recommendation.</p>\n\n<pre><code># Get total amount and country\nwhile True:\n try:\n total_amount = input('Enter your total amount: ')\n total_amount = total_amount.replace('$', '').replace(',', '.')\n total_amount = float(total_amount)\n break\n except ValueError:\n print('Invalid floating point value')\n</code></pre>\n\n<p>More importantly, it's considered best practice to compare lowercase strings to allow the user to not care about case sensitivity. You are currently not using the <code>usa</code> and <code>canada</code> variables.</p>\n\n<pre><code>usa = \"usa\"\ncanada = \"canada\"\n\nif Country.lower() == usa:\n ...\nif Country.lower() == canada:\n ...\n\nif endProgram.lower() in ('no', 'false'):\n break\n</code></pre>\n\n<p>And Dennis' answer helps as well.</p>\n\n<pre><code>#!/usr/bin/env python3\n\nprint('This will calculate shipping cost and your grand total.')\ninput('Please press \"Enter\" to begin ')\n\n# Get total amount and country\nwhile True:\n try:\n total_amount = input('Enter your total amount: ')\n total_amount = total_amount.replace('$', '').replace(',', '.')\n total_amount = float(total_amount)\n break\n except ValueError:\n print('Invalid floating point value')\n\ncountry = input('Type \"Canada\" for Canada and \"USA\" for USA: ')\n\n# evaluation of user data\nusa = \"usa\"\ncanada = \"canada\"\nless_fifty = total_amount &lt;= 50\nfifty_hundred = total_amount &gt; 50.0 and total_amount &lt;= 100\nhundred_fifty = total_amount &gt; 100.0 and total_amount &lt;= 150\n\nif country == usa:\n if less_fifty:\n shipping = 6\n elif fifty_hundred:\n shipping = 8\n elif hundred_fifty:\n shipping = 10\n else:\n shipping = None\n\nelif country == canada:\n if less_fifty:\n shipping = 8\n elif fifty_hundred:\n shipping = 10\n elif hundred_fifty:\n shipping = 12\n elif twoHundred:\n shipping = None\n\n# print output\nif shipping is None:\n print('Your shipping is free!')\n shipping = 0\nelse:\n print('Your shipping is: $', shipping)\nprint('Your grand total is: $', total_amount + shipping)\n\nendProgram = input ('Do you want to restart the program? ')\nif endProgram.lower() in ('no', 'false'):\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:20:09.517", "Id": "33903", "Score": "0", "body": "Damn, a duplicate. I don't think it's on purpose, he was told to go here, and his previous question has been automatically migrated too. Voting to close this one, please answer to the other question which has been around for a longer time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:10:34.510", "Id": "21117", "ParentId": "21113", "Score": "5" } }, { "body": "<p>First make sure the script work: proper indenting, shebang, correct logic. When the user enters 170$, you give him free shipping only because <code>twoHundred</code> evaluates to <code>totalAmount</code> which evaluates to true, so it seems simple to just say \"otherwise, it's free\". You also don't handle errors. I decided to handle the \"wrong country\" error, but many things could go wrong when inputing the total amount. As other said, first separate printing from application logic:</p>\n\n<pre><code>#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\ninput ('Please press \"Enter\" to begin')\n\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n totalAmount = int(float(input('Enter your total amount: ') \\\n .replace(',', '').replace('$', '')))\n Country = str(input('Type \"Canada\" for Canada and \"USA\" for USA: '))\n\n lessFifty = totalAmount &lt;= 50\n fiftyHundred = totalAmount &gt;= 50.01 and totalAmount &lt;= 100\n hundredFifty = totalAmount &gt;= 100.01 and totalAmount &lt;= 150\n\n if Country == \"USA\":\n if lessFifty: shippingCost = 6\n elif fiftyHundred: shippingCost = 8\n elif hundredFifty: shippingCost = 10\n else: shippingCost = 0\n elif Country == \"Canada\":\n if lessFifty: shippingCost = 8\n elif fiftyHundred: shippingCost = 10\n elif hundredFifty: shippingCost = 12\n else: shippingCost = 0\n else:\n print(\"Unknown country.\")\n break\n\n print('Your shipping cost is: ${:.2f}'.format(shippingCost))\n print('Your grand total is: ${:.2f}'.format(totalAmount + shippingCost))\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):\n break\n</code></pre>\n\n<p>You can notice that the if blocks are still repetitive. You can use a dictionary to store the shipping costs.</p>\n\n<pre><code>#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\ninput ('Please press \"Enter\" to begin')\n\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n totalAmount = int(float(input('Enter your total amount: ') \\\n .replace(',', '').replace('$', '')))\n country = str(input('Type \"Canada\" for Canada and \"USA\" for USA: '))\n\n if country not in ['Canada', 'USA']:\n print(\"Unknown country.\")\n break\n\n if totalAmount &lt;= 50: amountCategory = 'lessFifty'\n elif totalAmount &gt;= 50.01 and totalAmount &lt;= 100: amountCategory = 'fiftyHundred'\n elif totalAmount &gt;= 100.01 and totalAmount &lt;= 150: amountCategory ='hundredFifty'\n else: amountCategory = 'free'\n\n shippingCosts = {\n 'USA': {'lessFifty': 6, 'fiftyHundred': 8, 'hundredFifty': 10, 'free': 0},\n 'Canada': {'lessFifty': 8, 'fiftyHundred': 10, 'hundredFifty': 12, 'free': 0}\n }\n\n shippingCost = shippingCosts[country][amountCategory]\n\n print('Your shipping cost is: ${:.2f}'.format(shippingCost))\n print('Your grand total is: ${:.2f}'.format(totalAmount + shippingCost))\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ['no', 'No', 'NO', 'false', 'False', 'FALSE']:\n break\n</code></pre>\n\n<p>I also used a list instead of a tuple to check for endProgram since it's more idiomatic. I don't think there's much more to do at this point to reduce size. You could find a smarter way to compute the shipping cost (see <a href=\"http://en.wikipedia.org/wiki/Kolmogorov_complexity\" rel=\"nofollow\">Kolmogorov complexity</a>) but that would make it harder to change the rules for no good reason. The block which compute amountCategory isn't too nice but since <code>if</code>s are not expressions in Python you can't write <code>amountCategory = if ...: 'lessFifty' else: 'free'</code>. You could use a function if you wanted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:20:28.940", "Id": "21119", "ParentId": "21113", "Score": "2" } }, { "body": "<p>Just to add that you can do <code>a &lt;= x &lt; y</code> in Python, which to me is a lot easier to write and read than setting up three variables just to say what range the total amount is within:</p>\n\n<pre><code>shipping = None\nif total_amount &lt;= 50:\n shipping = 6\nelif 50 &lt; total_amount &lt;= 100:\n shipping = 8\nelif 100 &lt; total_amount &lt;= 150:\n shipping = 10\nif country == 'canada' and shipping:\n shipping += 2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T21:25:28.367", "Id": "21138", "ParentId": "21113", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:48:53.977", "Id": "21113", "Score": "5", "Tags": [ "python" ], "Title": "Calculate shipping cost" }
21113
<p>I need to write a procedure, that will take a dictionary consisting of server names and their available slots and a number of slots required, and redispatch it over the servers, so that every server would accept only that many assignments as he has free slots; servers with higher number of free slots would be assigned in first place; whole procedure would be robust and not prone to any stupid math errors I might have done. So far I've came up with something like that:</p> <pre><code>import operator slots_required = 8 hosts = {'server1': 3, 'server2': 7, 'server3': 1} jobs = {} if slots_required &gt; sum(hosts.values()): print " [!] Not enough resources! Exiting." else: print " [x] entering while loop" while slots_required &gt; 0: print " [x] while loop on interation: %s" % slots_required for host in sorted(hosts.iteritems(), key=operator.itemgetter(1), reverse=True): # if for any reason slots_required number is 0 or less, break if slots_required &lt;= 0: break # if the host has no slots free we're not iterating over it and removing it if host[1] == 0: hosts.pop(host[0]) break else: print " [x] for loop, host: %s" % host[0] jobs[slots_required] = host slots_required -= 1 hosts[host[0]] = host[1] - 1 print " [x] slots_required value after decreasing: %s" % slots_required print " [x] exited the for loop" print " [x] Iteration down to ZERO! Exiting!" print " [x] exiting while loop" print jobs print hosts print slots_required </code></pre> <p>Feel free to play around and change server numbers, their free slots and slots required of course. The numbers I've added are only for example and testing purposes, and the print functions can be taken out as well, the only thing I am interested in at the end is the jobs dictionary with server names and their assignments (there will be jobID inserted next to server name in jobs dictionary instead of a number, as it is right now). Is there a better, nicer, safer and quicker way of doing that? I've feeling the code although working in my tests, is extremely ugly and could be more functional.</p>
[]
[ { "body": "<p>You can solve this mathematically. Let's suppose there are \\$m\\$ hosts and \\$n\\$ jobs. Sort the hosts into ascending order by their slots, so that \\$s_i\\$ is the number of slots for host number \\$i\\$, and we have \\$s_0 ≤ s_1 ≤ \\dotsb ≤ s_{m−1}\\$.</p>\n\n<p>Now we can immediately figure out how many jobs host 0 gets. Case (i): if \\$s_0m ≥ n\\$, then we can distribute jobs evenly across the hosts, so that every host gets either \\$\\lceil{n \\over m}\\rceil\\$ or \\$\\lfloor{n \\over m}\\rfloor\\$ jobs. Because jobs are distributed to the hosts with higher capacity first, we can be sure that host 0 gets \\$\\lfloor{n \\over m}\\rfloor\\$ jobs. Case (ii): if \\$s_0m &lt; n\\$, then we have to give each host at least \\$s_0\\$ jobs (and some hosts more).</p>\n\n<p>So host 0 gets \\$\\min(\\lfloor{n \\over m}\\rfloor, s_0)\\$ jobs, and then we can subtract 1 from \\$m\\$ and go on to host 1. Like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import operator\n\nclass CapacityError(Exception):\n pass\n\ndef schedule(hosts, n):\n \"\"\"\n Generate a schedule for picking `n` slots from `hosts` (a\n dictionary mapping hostname to capacity). Raise CapacityError if\n no such schedule is possible.\n\n &gt;&gt;&gt; sorted(schedule({'A': 3, 'B': 7, 'C': 1}, 8))\n [('A', 3), ('B', 4), ('C', 1)]\n \"\"\"\n if n &gt; sum(hosts.itervalues()):\n raise CapacityError()\n m = len(hosts)\n for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):\n j = min(n // m, slots)\n n -= j\n m -= 1\n yield host, j\n assert(n == m == 0)\n</code></pre>\n\n<h3>Update 1: generators</h3>\n\n<p>I've implemented this function in the form of a <a href=\"http://docs.python.org/2/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">generator</a> because that's the most flexible way in Python to produce a sequence of things (here, elements of a schedule). You can easily turn the result into a dictionary:</p>\n\n<pre><code>&gt;&gt;&gt; dict(schedule({'A': 3, 'B': 7, 'C': 1}, 8))\n{'A': 3, 'C': 1, 'B': 4}\n</code></pre>\n\n<p>or a list:</p>\n\n<pre><code>&gt;&gt;&gt; list(schedule({'A': 3, 'B': 7, 'C': 1}, 8))\n[('C', 1), ('A', 3), ('B', 4)]\n</code></pre>\n\n<p>or just process the items one at a time:</p>\n\n<pre><code>&gt;&gt;&gt; for host, slots in schedule({'A': 3, 'B': 7, 'C': 1}, 8):\n... print(\"{}: {}\".format(host, slots))\n... \nC: 1\nA: 3\nB: 4\n</code></pre>\n\n<p>(If you're not happy with using generators, you can easily change the implementation to return a dictionary instead. But it's worth learning to use them. See the <a href=\"http://docs.python.org/2/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">Python Tutorial</a>, or <a href=\"https://stackoverflow.com/q/102535/68063\">this question on Stack Overflow</a>.)</p>\n\n<h3>Update 2: job ids</h3>\n\n<p>You asked in comments how to assign individual jobs. Well, one idea would be to pass in a list of jobs to the scheduler, and get out a list of jobs for each host, like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import islice\n\ndef schedule2(hosts, jobs):\n \"\"\"\n Generate a schedule for assigning the list `jobs` to `hosts` (a\n dictionary mapping hostname to capacity). Raise CapacityError if\n no such schedule is possible.\n\n &gt;&gt;&gt; jobs = ['j{}'.format(i) for i in range(8)]\n &gt;&gt;&gt; dict(schedule2({'A': 3, 'B': 7, 'C': 1}, jobs))\n {'A': ['j1', 'j2', 'j3'], 'C': ['j0'], 'B': ['j4', 'j5', 'j6', 'j7']}\n \"\"\"\n n = len(jobs)\n if n &gt; sum(hosts.itervalues()):\n raise CapacityError()\n m = len(hosts)\n jobs = iter(jobs)\n for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):\n j = min(n // m, slots)\n n -= j\n m -= 1\n yield host, list(islice(jobs, j))\n assert(n == m == 0)\n</code></pre>\n\n<h3>Update 3: more explanation</h3>\n\n<p>You asked in comments for more explanation. Well, I'm going to assume that you know all about Python <em>iterables</em>, <em>iterators</em>, and <em>generators</em> (see <a href=\"http://docs.python.org/2/tutorial/classes.html#iterators\" rel=\"nofollow noreferrer\">the Python tutorial</a> and the answers to <a href=\"https://stackoverflow.com/a/231855/68063\">this question on Stack Overflow</a>).</p>\n\n<p>So the remaining difficult bit is why I write <code>jobs = iter(jobs)</code> and <code>list(islice(jobs, j))</code>. Remember that <code>jobs</code> is a sequence of jobs, and we want to split it up into lists of jobs assigned to each host. In the line</p>\n\n<pre><code> j = min(n // m, slots)\n</code></pre>\n\n<p>we compute the number of jobs to assign to the current host, so what we need to do is to take the next <code>j</code> elements from the list <code>jobs</code>. One way to do that would be able to keep a counter <code>k</code> of how far we got through the list <code>jobs</code>, and then take a slice of the next <code>j</code> elements starting at <code>k</code>. Like this:</p>\n\n<pre><code> k = 0\n for host, slots in sorted(hosts.iteritems(), key=operator.itemgetter(1)):\n j = min(n // m, slots)\n n -= j\n m -= 1\n yield host, jobs[k:k+j]\n k += j\n</code></pre>\n\n<p>There's nothing wrong with doing it like this, except that it's a bit of a pain keeping the counter <code>k</code> up to date. We don't really care about the value of <code>k</code>, we just want the <em>next j elements</em> from <code>jobs</code>, whatver they are. That's where <a href=\"http://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> comes in. The call <code>islice(iterator, j)</code> returns an iterator that takes <code>j</code> elements from <code>iterator</code>. Which is almost exactly what we need, except that it's an iterator, but we need a list. So we convert it to a list by calling the built-in function <a href=\"http://docs.python.org/2/library/functions.html#list\" rel=\"nofollow noreferrer\"><code>list</code></a>.</p>\n\n<p>Here's an example showing <code>islice</code> in action:</p>\n\n<pre><code>&gt;&gt;&gt; from itertools import count, islice\n&gt;&gt;&gt; c = count(1) # an iterator that counts upwards from 1\n&gt;&gt;&gt; a = islice(c, 5) # an iterator that gets 5 elements from c\n&gt;&gt;&gt; list(a)\n[1, 2, 3, 4, 5]\n&gt;&gt;&gt; list(islice(c, 3)) # get another 3 elements from c\n[6, 7, 8]\n</code></pre>\n\n<p>The only remaining problem with using <code>islice</code> to split up <code>jobs</code> is that this relies upon <code>jobs</code> being an <em>iterator</em> (a list won't work). So we use the built-in function <a href=\"http://docs.python.org/2/library/functions.html#iter\" rel=\"nofollow noreferrer\"><code>iter</code></a> to ensure that <code>jobs</code> is an iterator.</p>\n\n<p>You should try out all these functions in the interactive interpreter to get a feel for what they do and how they work.</p>\n\n<p>You also asked about <a href=\"http://docs.python.org/2/reference/simple_stmts.html#the-assert-statement\" rel=\"nofollow noreferrer\"><code>assert</code></a>. An assertion is a statement that tests a value and raises an exception if it's not true. It declares a condition that <em>must</em> be true at this point in the program. This is useful for programmers who want to read and understand the code, and it also catches implementation errors if these lead to the condition being violated. See <a href=\"http://en.wikipedia.org/wiki/Assertion_%28computing%29\" rel=\"nofollow noreferrer\">Wikipedia on assertions</a>.</p>\n\n<p>In this case, I want to declare that the program has generated an assignment for every host (that is, <code>m == 0</code> since <code>m</code> starts at the number of hosts and counts down for each one) and that every job has been assigned to some host (that is, <code>n == 0</code>, since <code>n</code> starts at the number of jobs, and gets reduced by <code>j</code> when we assign <code>j</code> jobs to some host).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:37:09.070", "Id": "33921", "Score": "0", "body": "Wow, that's some nice math there, but I think it doesnt produce desired output: a dictionary of hosts with assigned slots. What I can see it does, is returning list of hosts and number of assigned slots - not exactly the same thing. Also, why it doesnt work when I use it like `print ({'A': 3, 'B': 7, 'C': 1}, 8)` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:41:46.370", "Id": "33923", "Score": "0", "body": "`schedule` is a [generator function](http://docs.python.org/2/tutorial/classes.html#generators). Generators are very flexible: if you want to turn the output into a dictionary, you can call `dict(schedule(...))`. If you want to turn the output into a list, you can call `list(schedule(...))`. If you want to print out the assignments, you can write `for host, jobs in schedule(...): print(host, jobs)`. And so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:01:06.790", "Id": "33931", "Score": "0", "body": "As a note, you could replace the manual counter `m` with a `zip(..., range(len(hosts), 0, -1))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T11:30:31.697", "Id": "33976", "Score": "0", "body": "@GarethRees: Ok, now it's making bit more sense, however, given the fact its a generator, I cant squeeze inside a job_id generation to be assigned to a server. It seems, I'd have to create a dictionary using your generator and then iterate over that dictionary and assign a unique job_id to every key in that dictionary. Is that correct or is there a better way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T11:54:54.570", "Id": "33977", "Score": "0", "body": "See updated answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T12:09:20.233", "Id": "33979", "Score": "0", "body": "Very neat ! Without `itemgetter` [Code golf] : `for slots, host in sorted(zip(hosts.values(), hosts.keys())):` or `for slots, host in sorted((s,h) for h,s in hosts.items()):`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T18:32:19.490", "Id": "34014", "Score": "0", "body": "@GarethRees: Thanks, that's a great answer - I've tested the code and it indeed does what expected to do. However, I've some troubles in understanding how it works. I've made some reading on the functions you've used that are new to me (yeld, assert, iter, list, islice) but I am not quite gettign it, and I'd love to - would you mind breaking it line by line with explanation of the magic?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T18:32:50.470", "Id": "21125", "ParentId": "21122", "Score": "6" } } ]
{ "AcceptedAnswerId": "21125", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T17:23:10.183", "Id": "21122", "Score": "2", "Tags": [ "python", "hash-map", "iteration" ], "Title": "Iterating X times (where X > Y) over Y element dictionary" }
21122
<p>So I'm curious about a few things that I did here design wise, as well as one space I'm sure I can be given improvements from real haskellers.</p> <p><strong>The part I really think can be done better that I'm falling short is my validateItem/validateStore/validateUser methods, these just feel more convoluted than I'm sure a true haskeller could get them, little help there would be greatly appreciated.</strong></p> <p>Design wise, I'm curious if it is common to create alongside a data model a hand full of accessor functions like I did (I hear I could plausibly solve this with lenses). Is it common/uncommon to do so, are such usually not exposed or? </p> <p>Anything else you see feel free to comment on (I am truly no real haskeller), but those 2 points are the main things I would like feedback on, if you ignore the rest of it but give me input on those I would love it.</p> <p>Thanks!</p> <pre><code>import qualified Data.Set as S(fromList, isSubsetOf) import qualified Data.List as L(isInfixOf) type Name = String data Amount = Out | Some | Enough | Plenty deriving (Show, Eq) data Container = Container Name deriving (Show, Eq) data Category = Category Name deriving (Show, Eq, Ord) data Store = Store Name [Category] deriving (Show, Eq) data Item = Item Name Container Category Amount Store deriving Show instance Eq (Item) where (==) i1 i2 = (getItemName i1) == (getItemName i2) data User = User Name [Container] [Category] [Store] [Item] deriving Show instance Eq (User) where (==) u1 u2 = (getName u1) == (getName u2) store n1 c2ns = Store n1 $ map Category c2ns item n1 c1n c2n a s1 = Item n1 (Container c1n) (Category c2n) a s1 getName (User n1 _ _ _ _) = n1 getContainers (User _ c1 _ _ _) = c1 getCategories (User _ _ c2 _ _) = c2 getStores (User _ _ _ s1 _) = s1 getItems (User _ _ _ _ i1) = i1 getContainerName (Container n2) = n2 getCategoryName (Category n3) = n3 getStoreName (Store n3 _) = n3 getStoreCategories (Store _ c5) = c5 getItemName (Item n2 _ _ _ _) = n2 getItemContainer (Item _ c3 _ _ _) = c3 getItemCategory (Item _ _ c4 _ _) = c4 getItemAmount (Item _ _ _ a1 _) = a1 getItemStore (Item _ _ _ _ s2) = s2 setName (User _ c1 c2 s1 i1) n = validate $ User n c1 c2 s1 i1 setContainers (User n1 _ c2 s1 i1) c1 = validate $ User n1 c1 c2 s1 i1 setCategories (User n1 c1 _ s1 i1) c2 = validate $ User n1 c1 c2 s1 i1 setStores (User n1 c1 c2 _ i1) s = validate $ User n1 c1 c2 s i1 setItems (User n1 c1 c2 s1 _) i = validate $ User n1 c1 c2 s1 i setItemName u i n = setValue u i f where f (Item n2 c3 c4 a1 s2) = Item n c3 c4 a1 s2 setItemContainer u i c = setValue u i f where f (Item n2 c3 c4 a1 s2) = Item n2 c c4 a1 s2 setItemCategory u i c = setValue u i f where f (Item n2 c3 c4 a1 s2) = Item n2 c3 c a1 s2 setItemAmount u i a = setValue u i f where f (Item n2 c3 c4 a1 s2) = Item n2 c3 c4 a s2 setItemStore u i s = setValue u i f where f (Item n2 c3 c4 a1 s2) = Item n2 c3 c4 a1 s setValue u i f = setValue1 u [] i f setValue1 (User n1 c1 c2 s1 []) ia i f = validate $ User n1 c1 c2 s1 [] setValue1 (User n1 c1 c2 s1 ((Item n2 c3 c4 a1 s2):is)) ia i f | n2 /= i = setValue1 (User n1 c1 c2 s1 is) ((Item n2 c3 c4 a1 s2):ia) i f | otherwise = validate $ User n1 c1 c2 s1 $ ia ++ ((f $ Item n2 c3 c4 a1 s2):is) addContainer u c = setContainers u (c:getContainers u) addCategory u c = setCategories u (c:getCategories u) addStore u s = setStores u (s:getStores u) addItem u i = setItems u (i:getItems u) validateItem c1 c2 s2 i1 | not $ getItemContainer i1 `elem` c1 = Left $ i1n ++ "'s container '" ++ i1c1n ++ "' is unknown" | not $ getItemCategory i1 `elem` c2 = Left $ i1n ++ "'s category '" ++ i1c2n ++ "' is unknown" | not $ getItemStore i1 `elem` s2 = Left $ i1n ++ "'s store '" ++ i1sn ++ "' is unknown" | otherwise = Right i1 where i1n = getItemName i1 i1c1n = getContainerName $ getItemContainer i1 i1c2n = getCategoryName $ getItemCategory i1 i1sn = getStoreName $ getItemStore i1 validateStore c2 s1 | S.fromList (getStoreCategories s1) `S.isSubsetOf` S.fromList c2 = Right s1 | otherwise = Left $ getStoreName s1 ++ " has an unknown category" validate u = validateItems &gt;&gt; validateStoreCategories &gt;&gt; Right u where c1 = getContainers u c2 = getCategories u s1 = getStores u i1 = getItems u validateItems = foldl (\x y -&gt; x &gt;&gt; validateItem c1 c2 s1 y) (validateItem c1 c2 s1 $ head i1) i1 validateStoreCategories = foldl (\x y -&gt; x &gt;&gt; validateStore c2 y) (validateStore c2 $ head s1) s1 -- -- -- TEST JUNK BELOW -- -- myHouse = [Container "Bathroom Closer", Container "Fridge", Container "Pantry", Container "Cabinet", Container "Freezer"] myKindOfStuff = [Category "Groceries", Category "Bathroom"] myCity = [Store "King Soopers" [Category "Groceries"], Store "Safeway" [Category "Groceries"]] myStuff = [Item "Milk" (Container "Fridge") (Category "Groceries") Out (Store "King Soopers" [Category "Groceries"])] me = User "Yay" myHouse myKindOfStuff myCity myStuff test = foldl1 (&gt;&gt;) $ map print $ testSummary:"":"Failed tests:":failedResults where testSummary = concat $ (show $ length passedResults):" tests passed, and ":(show $ length failedResults):" failed.":[] failedResults = filter (L.isInfixOf "Failed") testSet passedResults = filter (L.isInfixOf "Passed") testSet testSet = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16] t1 = case validate me of (Right u) -&gt; "t1 Passed: " ++ (show u); (Left x) -&gt; "t1 Failed: " ++ x t2 = case addStore me $ store "badCategory" ["Groceries", "Bathroom", "bad"] of (Right u) -&gt; "t2 Failed: " ++ (show u); (Left x) -&gt; "t2 Passed: " ++ x t3 = case addStore me $ store "noCategory" [] of (Right u) -&gt; "t3 Passed: " ++ (show u); (Left x) -&gt; "t3 Failed: " ++ x t4 = case addStore me $ store "goodCategory" ["Groceries"] of (Right u) -&gt; "t4 Passed: " ++ (show u); (Left x) -&gt; "t4 Failed: " ++ x t5 = case addStore me $ store "goodCategories" ["Groceries", "Bathroom"] of (Right u) -&gt; "t5 Passed: " ++ (show u); (Left x) -&gt; "t5 Failed: " ++ x t6 = case addItem me $ item "badContainer" "bad" "Groceries" Some (head myCity) of (Right u) -&gt; "t6 Failed: " ++ (show u); (Left x) -&gt; "t6 Passed: " ++ x t7 = case addItem me $ item "blankContainer" [] "Groceries" Some (head myCity) of (Right u) -&gt; "t7 Failed: " ++ (show u); (Left x) -&gt; "t7 Passed: " ++ x t8 = case addItem me $ item "goodContainer" "Fridge" "Groceries" Some (head myCity) of (Right u) -&gt; "t8 Passed: " ++ (show u); (Left x) -&gt; "t8 Failed: " ++ x t9 = case addItem me $ item "badCategory" "Fridge" "bad" Some (head myCity) of (Right u) -&gt; "t9 Failed: " ++ (show u); (Left x) -&gt; "t9 Passed: " ++ x t10 = case addItem me $ item "blankCategory" "Fridge" "" Some (head myCity) of (Right u) -&gt; "t10 Failed: " ++ (show u); (Left x) -&gt; "t10 Passed: " ++ x t11 = case addItem me $ item "goodCategory" "Fridge" "Groceries" Some (head myCity) of (Right u) -&gt; "t11 Passed: " ++ (show u); (Left x) -&gt; "t11 Failed: " ++ x t12 = case addItem me $ item "badStoreName" "Fridge" "Groceries" Some $ store "bad" [] of (Right u) -&gt; "t12 Failed: " ++ (show u); (Left x) -&gt; "t12 Passed: " ++ x t13 = case addItem me $ item "blankStoreName" "Fridge" "Groceries" Some $ store "" [] of (Right u) -&gt; "t13 Failed: " ++ (show u); (Left x) -&gt; "t13 Passed: " ++ x t14 = case addItem me $ item "badStoreCategory" "Fridge" "Groceries" Some $ store "Safeway" ["bad"] of (Right u) -&gt; "t14 Failed: " ++ (show u); (Left x) -&gt; "t14 Passed: " ++ x t15 = case addItem me $ item "blankStoreCategory" "Fridge" "Groceries" Some $ store "Safeway" [] of (Right u) -&gt; "t15 Failed: " ++ (show u); (Left x) -&gt; "t15 Passed: " ++ x t16 = case addItem me $ item "goodStoreCategory" "Fridge" "Groceries" Some $ store "Safeway" ["Groceries"] of (Right u) -&gt; "t16 Passed: " ++ (show u); (Left x) -&gt; "t16 Failed: " ++ x </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:25:33.187", "Id": "33960", "Score": "0", "body": "I don't know enough Haskell to give this a full review, but it seems to me that record syntax could eliminate at least some of the annoying get functions, especially for `User`? Also, some type signatures would really help here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:34:49.067", "Id": "33994", "Score": "0", "body": "@Yuushi thanks I always put type signatures after I get the whole thing working and want to export the module, and as such end up forgetting them! Thanks for the reminder! As for the record syntax, I don't want to pollute importers of the module, I spoke this over with #haskell last night and they told me the get/set functions are normal approach but also record syntax is common, and idiomatically how the get/set functions tend to work while record syntax isn't exported, thanks for looking it over! That's a review, write it as an answer and you'll get my vote for the help :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T18:36:17.803", "Id": "21126", "Score": "1", "Tags": [ "haskell", "validation" ], "Title": "Data model with validation in haskell couple convoluted functions" }
21126
<p>I am learning MVC, and trying to understand routing.</p> <p>I understand that if I want to show an individual blog post for site.com/54, my route would be something like</p> <pre><code>//index.php $controller = new Controller(); if ( preg_match("#/(0-9.)#", $uri, $matches) ) { $controller-&gt;showAction($matches[1]); } </code></pre> <p>which would lead to my controller</p> <pre><code>//controllers.php class Controller { private function showAction($id) { $post = getPostById($id); $view = new View('views/show.php'); } } </code></pre> <p>And, on the other hand, a sensible thing to do for different static pages is perhaps</p> <pre><code>//index.php ... } elseif ($uri == '/about') { $controller-&gt;aboutAction(); } elseif ($uri == '/contact') { $controller-&gt;contactAction(); } elseif ($uri == '/') { $controller-&gt;indexAction(); } else { $controller-&gt;missingAction(); } </code></pre> <p>My question is, what about the in-between? For example, apple.com/ipad/overview/ and apple.com/ipad/features/. They are different pages, so it seems like the latter is sensible (i.e. unique controller method for each page). But then, when you're on /overview, you still need to know you're a sub-page of /ipad (so you can highlight the iPad button in the navigation). If you did the first method (regex parsing), you'd know that (i.e. you could use $matches[1] when constructing your navigation). If you use the second method, it seems like in your view you'd have to do something like <code>$current_product = 'ipad'</code> so your nav would know about it. But this could get cumbersome.</p> <p>What's the appropriate method?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T21:19:04.770", "Id": "185417", "Score": "0", "body": "The desire to improve code is implied for all questions on this site. Question titles should reflect the purpose of the code, not how you wish to have it reworked. See [ask]." } ]
[ { "body": "<p>Have you thought about calling the overview only when the URI ends in \"overview\" and preceded by a product slug?</p>\n\n<pre><code>$controller = new Controller();\nif ( preg_match(\"#^/([a-zA-Z0-9_-]+)/overview/?$#\", $uri, $matches) ) {\n $controller-&gt;showOverview($matches[1]);\n}\n</code></pre>\n\n<p>This way, you define your routes with the following assumption:</p>\n\n<pre><code>/:product\n/:product/specs\n/:product/comments\n/about\n</code></pre>\n\n<p>You should check out the Slim Framework: <a href=\"http://www.slimframework.com/\" rel=\"nofollow\">http://www.slimframework.com/</a></p>\n\n<p>I've used it just for routing when performance was a crucial requirement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:23:10.380", "Id": "33990", "Score": "0", "body": "+1 (not enough rep), this makes sense to me. Btw, what does :product mean? I've seen this markup before. Why not $product?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T20:01:57.333", "Id": "34024", "Score": "1", "body": "Sam, the notation `:key` is used by many routing frameworks to denote a named parameter in the URL. Instead of using the regular expression `(?<product>[a-zA-Z]+)`, a framework like Slim will allow you to say `:product` and pass that value to your controller's action." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:10:25.737", "Id": "21177", "ParentId": "21128", "Score": "2" } } ]
{ "AcceptedAnswerId": "21177", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:20:27.507", "Id": "21128", "Score": "1", "Tags": [ "php", "mvc", "url-routing" ], "Title": "Trying to understand appropriate routing in MVC" }
21128
<p>I have the following logic:</p> <pre><code>bool a; bool b; int v = 0; //code here to set the values of a and b... if(b) { v = a ? 1 : 2; } else { v = a ? 0 : 1; } </code></pre> <p>I believe that there may be a way to minimize this logic (or rewrite it in a more clever way) that I am not thinking of.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T09:04:20.133", "Id": "34099", "Score": "1", "body": "I find this question too abstract; it can't be answered in a meaningful way. What do `a`, `b`, and `v` *represent?* The *clever way* is often the *wrong way*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:14:46.957", "Id": "34111", "Score": "1", "body": "this example is probably just something he typed up that mimics his real code. I've had to do the same thing when I'm working on proprietary code and need help trying to make my logic better. if i could post my code I would, but there are a few occasions where I can't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:26:30.367", "Id": "34113", "Score": "0", "body": "Also on that note I would like to inject a personal preference of mine. If you do have code that affects the return value, I find it easier to set the value when I do checks for things. This way I can always highlight that code and click Refactor my IDE will (usually) put something like `v=CheckForSomeVariable()` and that will make my code easier to read. That is personal preference though." } ]
[ { "body": "<pre><code>int v = b ? (a ? 1 : 2) : (a ? 0 : 1);\n</code></pre>\n\n<p><strong>EDIT #1:</strong></p>\n\n<p>As per <a href=\"https://codereview.stackexchange.com/users/2041/svick\">svick</a>, parsed out conditional operator on separate lines:</p>\n\n<pre><code>int v = b\n ? (a ? 1 : 2)\n : (a ? 0 : 1);\n</code></pre>\n\n<p><strong>EDIT #2:</strong></p>\n\n<p>Here's one I don't like, but it has no branching whatsoever:</p>\n\n<pre><code>int v = Convert.ToInt32(b) + Convert.ToInt32(!a);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:11:49.200", "Id": "33927", "Score": "1", "body": "I want to avoid ternanary inside ternary because it seems unreadable at least to me" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:12:33.377", "Id": "33928", "Score": "0", "body": "You may wish to update your question to state that fact then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:20:18.523", "Id": "33929", "Score": "0", "body": "It might help if you put each of the nested ternaries on its own line." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:10:09.073", "Id": "21132", "ParentId": "21130", "Score": "5" } }, { "body": "<p>You can also avoid the else blocks entirely by realizing that <code>!b=0, b=1</code> and <code>a=0, !a=1</code>, like:</p>\n\n<pre><code>bool a;\nbool b;\nint v = 0; //a &amp;&amp; !b (0 + 0 = 0)\n\n//code here to set the values of a and b...\n\nif (b) \n v++; //a &amp;&amp; b (0 + 1 = 1)\nif (! a)\n v++; //!a &amp;&amp; b (1 + 1 = 2), !a &amp;&amp; !b (1 + 0 = 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:32:05.480", "Id": "21148", "ParentId": "21130", "Score": "2" } }, { "body": "<p>This post reminds me of part of a \"how to write clean code\" and one of the challenges that the speaker proposed was to not use if statements on behavioral code. Obviously if statements on logical code is only (for lack of a better word) logical. So what this implies is that you would use polymorphic classes to give you the desired output. so as a super simple example i'll use the standard math example.</p>\n\n<p>consider this code</p>\n\n<pre><code>public int SomeFunction()\n{\n int a=3;\n int b=4;\n\n int c;\n //some logical operations\n //that gives a value to c\n\n switch(c)\n {\n case 1:\n return a+b;\n case 2:\n return a-b;\n case 3:\n return a*b;\n case 4:\n return a^b;\n default:\n return 0;\n }\n}\n</code></pre>\n\n<p>as you can see from this code it does 2 things. Which doing more than one thing breaks the single responsibility principle. And although this is a simple example readability is not that impaired.\nSo a suggested way to fix this is to use a factory for the logic, and polymorphism for the operations. This would work out good because then everything can stick with the SRP, and makes debugging a little bit easier. Keep in mind because of how simple this example is it may feel like it is too complicated of a process, but a principle is simple idea that you can build off of. So lets build this. First our polymorphic class, we'll make a parent class called <code>MathOperator</code>. it has a constructor that takes 2 numbers, and has a abstract method <code>Operate</code> that returns a number. Next we make a <code>MathFactory</code>. This class has nothing but static methods to get what we desire. One of the methods is <code>GetProperMathOperator(int)</code>. It would replace the switch statement in the previous example with <code>var mathOperation = MathFactory.GetProperMathOperator(c);</code> then we can simply just <code>return mathOperation.Operate();</code> so our code would look something like this</p>\n\n<pre><code>public int SomeFunction()\n{\n int c;\n //some logical operations\n //that gives a value to C\n\n var mathOperation = MathFactory.GetProperMathOperator(c);\n mathOperation.SetValues(3,4);\n\n return mathOperation.Operate();\n}\n</code></pre>\n\n<p>but for testing purposes that code is a little difficult because this class depends on 2 other classes. So it would be better to take that code out and move it to the calling class. So to make it easier to test this function we would want to modify the method to ask for the proper MathOperator. Now you just set the values to what you need, and return the operatored number.</p>\n\n<pre><code>public int SomeFunction(MathOperator mathOperation)\n{\n mathOperation.SetValues(3,4);\n return mathOperation.Operate();\n}\n</code></pre>\n\n<p>So does this answer the OP's question? not directly. But since his code looks more like it is an abbreviated example of what his code really does, then I would think that he could use this principle to refactor his code into something that is a little cleaner, and would make the function easier to test and debug.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T09:00:00.483", "Id": "34098", "Score": "0", "body": "I'd upvote this if it didn't introduce a temporal coupling. It's just too easy to forget calling `SetValues`. Why not pass the values as parameters to `Operate` directly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T19:56:44.620", "Id": "34107", "Score": "0", "body": "because in the OP's post he mentioned that there was some code in his method that ended up setting the value of `a` and `b`. Even though they were bool values it still affected what the returned value is. so the `SetValues` portion was to reflect that. Another reason for it was that if a person was doing TDD then they would know how that function is supposed to operate, and what it was supposed to return based on the tests." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T03:27:53.433", "Id": "21212", "ParentId": "21130", "Score": "0" } } ]
{ "AcceptedAnswerId": "21148", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:48:18.793", "Id": "21130", "Score": "4", "Tags": [ "c#", "optimization" ], "Title": "Optimize boolean statements" }
21130
<p>Anyone have any comments? Just trying to better my code if can be done.</p> <pre><code>public class SacWidget extends AppWidgetProvider { String roseUrl; AQuery aq; public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; for (int i = 0; i &lt; N; i++) { int appWidgetId = appWidgetIds[i]; Intent intent = new Intent(context, DangerRose.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setImageViewBitmap(R.id.ivdangerrose, getRose()); appWidgetManager.updateAppWidget(appWidgetId, views); } } private Bitmap getRose() { Bitmap bitmap = null; File f = new File("/storage/emulated/0/acr/sac/dangerrose.png"); try { bitmap = BitmapFactory.decodeStream(new FileInputStream(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } return bitmap; } } </code></pre>
[]
[ { "body": "<p>I'm not too familiar with Android, so the following is just some generic Java notes:</p>\n\n<ol>\n<li><p>Fields <code>roseUrl</code> and <code>aq</code> seem unused as well as the <code>pendingIntent</code> local variable. You might remove them.</p></li>\n<li><p>You could use a foreach loop: </p>\n\n<pre><code>for (final int appWidgetId: appWidgetIds) ...\n</code></pre></li>\n<li><p><a href=\"https://stackoverflow.com/q/3855187/843804\">It isn't the best idea to use <code>printStackTrace()</code> in Android exceptions</a>.</p></li>\n<li><p>The <code>getRose()</code> method creates a stream (<code>new FileInputStream(f)</code>). I'm not sure whether <code>BitmapFactory.decodeStream</code> closes it before it returns or not. If not, you should close it.</p></li>\n</ol>\n\n<p>Notes for the edit:</p>\n\n<ol>\n<li><p>You should close the stream in a <code>finally</code> block. If <code>BitmapFactory.decodeStream</code> throws an exception it won't be closed. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><p>The following two lines are duplicated:</p>\n\n<pre><code>File ext = Environment.getExternalStorageDirectory();\nFile file = new File(ext,\"acr/sac/dangerrose.png\");\n</code></pre>\n\n<p>You could extract them out to a method.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:26:27.003", "Id": "33932", "Score": "1", "body": "Thanks for the answer, I really appreciate it. I cleaned up the code a bit. I cannot find a close for the IS in any of the documentation.... hmmmm...." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:18:28.267", "Id": "21133", "ParentId": "21131", "Score": "3" } }, { "body": "<ol>\n<li><p>Bad variable names. Please do not use things like <code>N</code>, <code>i</code>, and <code>f</code> (and if you are, at least be consistent and make them all lowercase). That <code>aq</code> is questionable as well.</p></li>\n<li><p>Using <code>for (int appWidgetId : appWidgetIds)</code> would save you a couple lines, and get rid of that atrocious <code>i</code> and <code>N</code> variables as well.</p></li>\n<li><p>Personally I wouldn't bother declaring <code>N</code> as <code>final</code> (or at all, since you could just as easily use <code>appWidgetIds.length</code> in your <code>for</code> loop condition even if you don't do #2) unless there is reason to. Like if you're going to refer to it from an anonymous class. Note that if you do #2 above, <code>N</code> goes away completely.</p></li>\n<li><p>Close your <code>FileInputStream</code>. Instead of doing <code>File f = ...</code> do <code>FileInputStream input = new FileInputStream(new File(\"/storage/...\"));</code> and then <code>input.close();</code> when you are done with it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:43:05.380", "Id": "21149", "ParentId": "21131", "Score": "2" } } ]
{ "AcceptedAnswerId": "21133", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T19:57:34.903", "Id": "21131", "Score": "3", "Tags": [ "java", "android", "file" ], "Title": "Android widget code" }
21131
<p>I testing F# code which calculates "nearness" of two N-dimensional points using a least square euclidean distance algorithm. The class library is written in F# and the calling will be from VB.NET. The code will eventually be used for scientific binary data, however I wanted a simple real world test environment.</p> <p>I choose to create an rgb color table class based upon a list of color names along with their 3 digit rgb value. The rgb values will be used for the distance algorithm. The code works, however I'd like to make sure that the distance algorithm in written in an efficient manner. The code will be called heavily in the final package. </p> <p>My VB code will create the class instance, adds colors to the color table and finally searches for the nearest match of an unnamed color. The results is DarkGoldenRod.</p> <pre class="lang-vb prettyprint-override"><code>Dim GreenYellow() As Double = {173, 255, 47} Dim Orange() As Double = {255, 127, 0} Dim Lavender() As Double = {230, 230, 250} Dim Magenta() As Double = {255, 0, 255} Dim DarkGoldenRod() As Double = {184, 134, 11} Dim test() As Double = {122, 122, 122} Dim objFSColorTable As New MyFSColorTable("GreenYellow", GreenYellow) objFSColorTable.AddEntry("Lavender", Lavender) objFSColorTable.AddEntry("Orange", Orange) objFSColorTable.AddEntry("Magenta", {255, 0, 255}) objFSColorTable.AddEntry("DarkGoldenRod", {184, 134, 11}) Dim name = objFSColorTable.ColorSearch(test) </code></pre> <p>The F# code contains the color table library which should be self explanatory</p> <pre><code>type MyColor = { Name: string; Values: float[]; } type MyFSColorTable(name: string, rgb:float[]) = class let mutable myHash = Hashtable() let mutable CurName = name let mutable CurDist = 0.0 let mutable CurColor = { Name = name; Values = rgb; } let mutable CurList = [CurColor] member x.AddColor name rgb = CurList &lt;- List.append CurList [{Name = name; Values = rgb}] member x.Name = name // Euclidean distance between 2 vectors member x.Dist (V1: float[]) V2 = Array.zip V1 V2 |&gt; Array.map(fun (v1, v2) -&gt; (v1 - v2) * (v1 - v2)) |&gt; Array.sum // Loop thru color hash and find the nearest match member x.ColorSearch (R1: float[]) = let mutable mindist = x.Dist R1 CurList.Head.Values let mutable name = CurList.Head.Name for i in (CurList) do let mutable s = 0.0 s &lt;- x.Dist R1 i.Values if s &lt; mindist then mindist &lt;- s name &lt;- i.Name name // RGB Hash Table member x.RGBHash = myHash member x.AddEntry (name:string) (rgb: float[]) = x.AddColor name rgb end </code></pre>
[]
[ { "body": "<pre><code>type MyColor = \n { Name: string;\n Values: float[];\n }\n</code></pre>\n<p>The usual syntax is to put the opening <code>{</code> right after <code>=</code>.</p>\n<p>Also, why are you using <code>float</code>s (or <code>Double</code>s in VB) for the values? Integers should be enough. And it might be easier to use existing <code>Color</code> type, either <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.color.aspx\" rel=\"nofollow noreferrer\">from <code>System.Windows.Media</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx\" rel=\"nofollow noreferrer\">from <code>System.Drawing</code></a>. As an added advantage, you could reuse the existing definitions for various colors.</p>\n<pre><code>type MyFSColorTable(name: string, rgb:float[]) = class\n</code></pre>\n<p>Collection really shouldn't take its first member in constructor. Either take all colors in the constructor (which means you wouldn't need <code>mutable</code> collection inside), or have a method for adding new colors.</p>\n<p>Also, using <code>class</code> here is not necessary. If you remove that, don't forget to also remove the <code>end</code>.</p>\n<pre><code>let mutable myHash = Hashtable()\nlet mutable CurName = name\nlet mutable CurDist = 0.0\n</code></pre>\n<p>These members don't seem to be used in the program, so you should remove them. Also, try to avoid using <code>mutable</code>.</p>\n<pre><code>let mutable CurColor = \n { Name = name;\n Values = rgb;\n }\n</code></pre>\n<p>This is only used to support the first item from constructor, remove it.</p>\n<pre><code>let mutable CurList = [CurColor]\n</code></pre>\n<p><code>CurList</code> is not a very good name. Don't use abbreviations like <code>Cur</code>, they are unclear. And in this case, it doesn't add anything. A better name would be <code>Colors</code>.</p>\n<pre><code>member x.AddColor name rgb = CurList &lt;- List.append CurList [{Name = name; Values = rgb}]\n</code></pre>\n<p>Adding to the end of <code>list</code> is inefficient. You can add a value to the front of the list by using <code>::</code>: <code>{Name = name; Values = rgb}::Colors</code>.</p>\n<pre><code>member x.Name = name\n</code></pre>\n<p>This member is not used. And it's very confusing, because it returns the name of the first color that was added to the collection. Remove it.</p>\n<pre><code>member x.Dist (V1: float[]) V2 =\n</code></pre>\n<p>This function doesn't use any instance fields, so it should be <code>static</code>. And it should be probably also private (i.e. <code>static let dist V1 V2 =</code>)</p>\n<pre><code>Array.map(fun (v1, v2) -&gt; (v1 - v2) * (v1 - v2))\n</code></pre>\n<p>You could avoid the repetition by using <a href=\"http://msdn.microsoft.com/en-us/library/ee370371.aspx\" rel=\"nofollow noreferrer\"><code>pown</code></a>: <code>Array.map (fun (v1, v2) -&gt; pown (v1 - v2) 2)</code>.</p>\n<pre><code>// Loop thru color hash and find the nearest match\nmember x.ColorSearch (R1: float[]) = \n</code></pre>\n<ol>\n<li><p>The comment is inaccurate, the function doesn't use any hash.</p>\n</li>\n<li><p><code>R1</code> is a really bad name. And <code>ColorSearch</code> is not a great name either, something like <code>FindNearestColor</code> would be much better.</p>\n</li>\n<li><p>The whole method is written in a purely <a href=\"http://en.wikipedia.org/wiki/Imperative_programming\" rel=\"nofollow noreferrer\">imperative style</a>. If you're going to write this way, there pretty much isn't a reason why you should use F#, F# is a poor imperative language.</p>\n<p>A better way to write this method would be to use <a href=\"http://msdn.microsoft.com/en-us/library/ee353586.aspx\" rel=\"nofollow noreferrer\"><code>List.minBy</code></a>:</p>\n</li>\n</ol>\n\n<pre><code>member x.FindNearestColor (rgb : float[]) =\n let nearestColor =\n Colors |&gt; List.minBy (fun color -&gt; dist rgb color.Values)\n nearestColor.Name\n</code></pre>\n<p>Also, it seems you think searching through the list could be inefficient (because it seems you attempted to use a hash table). But you can't use hash table for something like this. You could use something like an <a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"nofollow noreferrer\">R-tree</a>, but implementing that would be much more complicated. So I would do that only if performance of this method was really bad.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Dim objFSColorTable As New MyFSColorTable(&quot;GreenYellow&quot;, GreenYellow)\nobjFSColorTable.AddEntry(&quot;Lavender&quot;, Lavender)\nobjFSColorTable.AddEntry(&quot;Orange&quot;, Orange)\nobjFSColorTable.AddEntry(&quot;Magenta&quot;, {255, 0, 255})\nobjFSColorTable.AddEntry(&quot;DarkGoldenRod&quot;, {184, 134, 11})\n</code></pre>\n<p>This is quite verbose. A better way would be to use <a href=\"http://msdn.microsoft.com/en-us/library/dd293617.aspx\" rel=\"nofollow noreferrer\">collection initializer</a>. How exactly would that look depends on how do you decide to fix initialization of <code>MyFSColorTable</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T14:53:36.050", "Id": "34157", "Score": "0", "body": "svick, I appreciate the comments. I'm not sure if you wanted to say \"Adding to the end of list is ineffective\" or perhaps \"inefficient\", as you can add to the end of the list. And yes, I should have definitely cleaned up my work in progress a little more before posting. The \"pown\" and \"List.MinBy\" comments were exactly the type of insights I was looking for in working with a new language. I used the floating point because the rgb color was only a test for my bigger picture numerics. In fact, that is why I didn't use a built-in color." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:02:09.480", "Id": "34158", "Score": "0", "body": "@dgp Yeah, I did mean inefficient (adding to the end of `list` is O(n), adding to the front is O(1))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:12:24.750", "Id": "34180", "Score": "0", "body": "I revised the code, however I didn't see where to post revised code in the faq." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T16:18:30.777", "Id": "34183", "Score": "0", "body": "@dgp You might want to have a look at the meta question [*Is it valid to reask (many) question on same script?*](http://meta.codereview.stackexchange.com/q/651/2041)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T21:19:54.477", "Id": "21137", "ParentId": "21134", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:20:45.160", "Id": "21134", "Score": "2", "Tags": [ "algorithm", "vb.net", "f#" ], "Title": "VB.Net interfacing with F# Euclidean Distance Algorithm" }
21134
<p>I came up with this jQuery snippet to add/remove a class on <code>&lt;label&gt;</code> tags that contain either checkboxes or radio buttons, in order to improve usability so users can see what item(s) they have selected.</p> <p>But I would like to know if there's a way to optimize the code (or not if that's the case).</p> <pre><code>$('label input[type=radio], label input[type=checkbox]').click(function() { $('label:has(input:checked)').addClass('active'); $('label:has(input:not(:checked))').removeClass('active'); }); </code></pre>
[]
[ { "body": "<p>You are probably pretty good here. </p>\n\n<p>You might be able to micro optimize by only highlighting / un-highlighting the corresponding label of the input but unless you have 100s of labels on your form I wouldn't bother. Especially since the radio button implementation would not be simple.</p>\n\n<p>The only caveat I have is that if you have a label with the class active that has an input of any type (textbox) that class will also be removed upon clicking any of the checkboxes. But I doubt that really matters for you.</p>\n\n<p>demo: <a href=\"http://jsfiddle.net/JsUWv/\" rel=\"nofollow\">http://jsfiddle.net/JsUWv/</a></p>\n\n<p>\"Don't optimize until you need to.\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:16:48.850", "Id": "33949", "Score": "0", "body": "*\"Don't optimize until you need to.\"*-- Hmm, I would've never thought of this when writing JavaScript; I'm clearly just starting with JS. Nonetheless, yes, when it comes to forms I try to keep them as short as possible, but if there's a case where it is necessary to have long forms with loads of check boxes and radio buttons, I would like the page to perform as efficiently as possible. I think I'll leave what I have as is since I only have a couple of radio buttons and checkboxes on the form I'm implementing this snippet on. Thanks a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:50:54.663", "Id": "33999", "Score": "0", "body": "@nickles80 this website is about 'code review' - try to assist people to get their code as good as possible and correct mistakes or bad practice. *Even* if you *normally* wouldn't optimize the code (e.g. the code is part of an admin page that is only used once a month, where performance isn't a big issue)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:32:23.997", "Id": "34004", "Score": "0", "body": "@thaJeztah That is fair. But he specifically asked if it needed it. I didn't think it did. Optimizing this snippet would take it from 4 lines to probably somewhere around 50. And _might_ be a little faster. Sometimes in reviewing code, the code doesn't need any improvements." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T23:17:04.383", "Id": "21143", "ParentId": "21135", "Score": "1" } }, { "body": "<p>You're adding a <code>click</code> handler to all your inputs, and then implementing the <code>click</code> handler such that each click processes <em>all</em> the labels. This is probably not what you want. </p>\n\n<p>I'd suggest the following:</p>\n\n<pre><code>$('label input[type=checkbox]').click(function() {\n $(this.parentNode).toggleClass('active', this.checked);\n});\n\n$('label input[type=radio]').click(function() {\n $('input[name=\"' + this.name + '\"]').each(function(){\n $(this.parentNode).toggleClass('active', this.checked);\n });\n});\n</code></pre>\n\n<p>Happily enough, that approach is also more efficient, as it's processing 1 element per click for checkboxes instead of <code>n</code> elements per click. For radio buttons it still has to process multiple elements, but the number processed is still less than the total number of elements on the page (assuming the page contains more than a single group of radio buttons). </p>\n\n<p>Here's a live example: <a href=\"http://jsfiddle.net/DfU3R/3/\" rel=\"nofollow\">http://jsfiddle.net/DfU3R/3/</a></p>\n\n<p>As nickles80 rightly notes, however, the performance difference between the two approaches will likely be negligible, and premature optimization is the root of all evil.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T02:42:57.647", "Id": "33942", "Score": "0", "body": "Although `$(elem.parentNode)` is better than `$(elem).parent()` performance-wise, I think you should use the latter. If you're using jQuery, use it properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T02:44:27.723", "Id": "33943", "Score": "0", "body": "Also, instead of that bloated `applyClass` function, just use `toggleClass`; it takes a second parameter as a boolean: `$(this).parent().toggleClass('active', this.checked);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:31:53.390", "Id": "33944", "Score": "0", "body": "Well spotted on the second point, it's much more compact using `toggleClass()`. On the first point, however, I have to disagree. Using jQuery properly doesn't necessarily mean giving it a monopoly on all DOM accesses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:21:06.500", "Id": "33950", "Score": "0", "body": "@aroth Yes, as I mentioned on *nickles80*'s answer, if there's a case where it is necessary to have long forms with loads of check boxes and radio buttons, I would like the page to perform as efficiently as possible, which means that your suggested improved snippet seems to do exactly that. Will certainly consider it for the future. Thanks a lot for the jsfiddle demo as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:38:49.820", "Id": "33971", "Score": "0", "body": "@Ricardo Read my answer below; For long forms, event delegation is the best approach" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T00:04:35.503", "Id": "21146", "ParentId": "21135", "Score": "3" } }, { "body": "<p>I know you've marked this question answered, but since this website is about 'code review', and further improvements are possible</p>\n\n<p>You're currently attaching event-handlers on each checkbox, which is inefficient, it's far more efficient to use 'delegation', making use of event-bubbling. Reducing the amount of event-handlers is better for performance and reduces the risk for memory-leaks, especially if you're adding/removing elements to your page dynamically.</p>\n\n<p>More information on Event Delegation:</p>\n\n<p>In general: <a href=\"http://davidwalsh.name/event-delegate\" rel=\"nofollow\">http://davidwalsh.name/event-delegate</a></p>\n\n<p>jQuery.on(): <a href=\"http://api.jquery.com/on/#direct-and-delegated-events\" rel=\"nofollow\">http://api.jquery.com/on/#direct-and-delegated-events</a> </p>\n\n<p>With jQuery, you can make use of 'delegation' by putting a .on() event handler on a parent element. A performance comparison can be found here\n<a href=\"http://jsperf.com/jquery-live-vs-delegate-vs-on/34\" rel=\"nofollow\">http://jsperf.com/jquery-live-vs-delegate-vs-on/34</a></p>\n\n<p>(although you're not using the .live() function, it is to illustrate using separate event-handlers vs. a single handler/delegation)</p>\n\n<p>Here's some information that explains how it works:\n<a href=\"http://www.jquery4u.com/jquery-functions/on-vs-live-review/\" rel=\"nofollow\">http://www.jquery4u.com/jquery-functions/on-vs-live-review/</a></p>\n\n<p>For your specific example, the code would be like this:</p>\n\n<pre><code>$(document).on('click', 'label input[type=checkbox]').click(function() {\n $(this.parentNode).toggleClass('active', this.checked);\n});\n</code></pre>\n\n<p>This will create a <em>single</em> event-handler that handles <em>all</em> click events on 'checkboxes' <em>if they are wrapped in a label</em> like this:</p>\n\n<pre><code>&lt;label&gt;&lt;input type='checkbox' id='check1' value='1' /&gt;Check me&lt;/label&gt;\n</code></pre>\n\n<p><strong>However</strong>, if you don't 'wrap' your input in a label, but have them separate, using the 'for' attribute:</p>\n\n<pre><code>&lt;input type='checkbox' id='check1' value='1' /&gt; &lt;label for='check1'&gt;check me&lt;/label&gt;\n</code></pre>\n\n<p>Then the code above won't work, in this case you'll have to select the label in a different way:</p>\n\n<pre><code>$(document).on('click', 'input[type=checkbox]').click(function() {\n $(\"label[for='\" + this.id + \"']\").toggleClass('active', this.checked);\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:22:00.243", "Id": "33989", "Score": "0", "body": "Very well explained, and the link references are a great help. You also addressed different situations (`<input>`s inside and outside the `<label>`), which can certainly happen down the road. Did not know about the concept of 'delegation' until now. Thanks a million for all the information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:45:07.473", "Id": "33995", "Score": "0", "body": "@Ricardo glad I was able to help. Kinda made it my mission to try to educate people a bit. Hoping other people will read and learn as well" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:24:22.437", "Id": "34029", "Score": "0", "body": "If we want to squeeze out every bit of performance, you should replace `$(this).attr('id')` with simply `this.id`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:25:21.117", "Id": "34030", "Score": "0", "body": "@JosephSilber good suggestion, I'll modify my answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:43:53.377", "Id": "21163", "ParentId": "21135", "Score": "3" } } ]
{ "AcceptedAnswerId": "21163", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T20:27:58.383", "Id": "21135", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Add/remove class to label tags" }
21135
<p>I am new to Python and I want to see how can I improve my code to make it faster and cleaner. Below you can see the code of Margrabe's Formula for pricing Exchange Options. </p> <p>I think the part where I check if the argument is None and if not take predetermined values, can be improved but i don't know how to do it. Is using scipy.stats.norm for calculating the pdf and cdf of the normal distribution faster than manually coding it myself?</p> <pre><code> from __future__ import division from math import log, sqrt, pi from scipy.stats import norm s1 = 10 s2 = 20 sigma1 = 1.25 sigma2 = 1.45 t = 0.5 rho = 0.85 def sigma(sigma1, sigma2, rho): return sqrt(sigma1**2 + sigma2**2 - 2*rho*sigma1*sigma2) def d1(s1, s2, t, sigma1, sigma2, rho): return (log(s1/s2)+ 1/2 * sigma(sigma1, sigma2, rho)**2 * t)/(sigma(sigma1, sigma2, rho) * sqrt(t)) def d2(s1, s2, t, sigma1, sigma2, rho): return d1(s1,s2,t, sigma1, sigma2, rho) - sigma(sigma1, sigma2, rho) * sqrt(t) def Margrabe(stock1=None, stock2=None, sig1=None, sig2=None, time=None, corr=None): if stock1 == None: stock1 = s1 if stock2 == None: stock2 = s2 if time == None: time = t if sig1 == None: sig1 = sigma1 if sig2 == None: sig2 = sigma2 if corr==None: corr = rho dd1 = d1(stock1, stock2, time, sig1, sig2, corr) dd2 = d2(stock1, stock2, time, sig1, sig2, corr) return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2) print "Margrabe = " + str(Margrabe()) </code></pre>
[]
[ { "body": "<p>First of all, when you compare to <code>None</code>, you are better off using <code>if stock1 is None:</code> - an object can define equality, so potentially using <code>==</code> could return <code>True</code> even when <code>stock1</code> is not <code>None</code>. Using <code>is</code> checks <em>identity</em>, so it will only return <code>True</code> in the case it really is <code>None</code>.</p>\n\n<p>As to simplifying your code, you can simply place the default values directly into the function definition:</p>\n\n<pre><code>def margrabe(stock1=s1, stock2=s2, sig1=t, sig2=sigma1, time=sigma2, corr=rho):\n dd1 = d1(stock1, stock2, time, sig1, sig2, corr)\n dd2 = d2(stock1, stock2, time, sig1, sig2, corr)\n return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)\n</code></pre>\n\n<p>This makes your code significantly more readable, and much shorter.</p>\n\n<p>It is also worth a note that <code>CapWords</code> is reserved for classes in Python - for functions, use <code>lowercase_with_underscores</code> - this is defined in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP-8</a> (which is a great read for making your Python more readable), and helps code highlighters work better, and your code more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:06:25.540", "Id": "21140", "ParentId": "21139", "Score": "1" } } ]
{ "AcceptedAnswerId": "21140", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:01:59.283", "Id": "21139", "Score": "2", "Tags": [ "python" ], "Title": "Improving my code of Margrabe Formula in Python" }
21139
<p>The problem with computing a radix using a non-imperative style of programming is you need to calculate a list of successive quotients, each new entry being the quotient of the last entry divided by the radix. The problem with this is (short of using despicable hacks like log) there is no way to know how many divisions an integer will take to reduce to 0. </p> <p>I'm fine with doing this with a generator :</p> <pre><code>def rep_div(n,r): while n != 0: yield n n /= r </code></pre> <p>But I don't like this for some reason. I feel there must be a clever way of using a lambda, or some functional construction, without building a list like is done here :</p> <pre><code>def rep_div2(n,r): return reduce(lambda v,i: v+[v[-1]/r],question_mark,[n]) </code></pre> <p>Once the repeated divisions can be generated radix is easy :</p> <pre><code>def radix2(n,r): return map(lambda ni: ni % r,(x for x in rep_div(n,r))) </code></pre> <p>So my question is : is it possible to rewrite <code>rep_div</code> as a more concise functional construction, on one line?</p>
[]
[ { "body": "<p>From my perspective, I'd say use the generator. It's concise and easily readable to most people familiar with Python. I'm not sure if you can do this in a functional sense easily without recreating some of the toolkit of functional programming languages. For example, if I wanted to do this in Haskell (which I am by no means an expert in, so this may be a horrible way for all I know), I'd do something like:</p>\n\n<pre><code>radix :: Int -&gt; Int -&gt; [Int]\nradix x n = takeWhile (&gt; 0) $ iterate (\\z -&gt; z `div` n) x\n</code></pre>\n\n<p>You can certainly recreate <code>takeWhile</code> and <code>iterate</code>, however, this only works due to lazy evaluation. The other option is, as you've said, using <code>log</code> and basically recreating <code>scanl</code>:</p>\n\n<pre><code>def scanl(f, base, l):\n yield base\n for x in l:\n base = f(base, x)\n yield base\n\ndef radix(n, r):\n return scanl(operator.__floordiv__, n, (r for x in range((int)(log(n, r)))))\n</code></pre>\n\n<p>So my answer is going to be \"No\" (predicated on the fact that someone smarter than me will probably find a way). However, unless you are playing Code Golf, I'd again suggest sticking with the generator version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:04:00.543", "Id": "21155", "ParentId": "21151", "Score": "1" } } ]
{ "AcceptedAnswerId": "21155", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:18:20.403", "Id": "21151", "Score": "2", "Tags": [ "python", "functional-programming" ], "Title": "Most concise Python radix function using functional constructions?" }
21151
<p>This library is a markup parser which is intended to be used in node.js and browser environment. I've decided to use Jasmine for tests.</p> <p>The library's name is ivy-markup. URL: <a href="https://github.com/AlexAtNet/ivy-markup" rel="nofollow">https://github.com/AlexAtNet/ivy-markup</a></p> <p>It would be great to get comments on its usability and code structure.</p> <p>Main engineering ideas:</p> <ul> <li>Parser parses the rest of the stream by trying several possibilities (e.g. try to parse table, then line, then characters)</li> <li>Parser creates a tree of nodes</li> <li>Rendering is two-step: node rendering and HTML tag rendering</li> </ul> <p>Significant code fragments:</p> <p>parser.js</p> <pre><code> // Character ranges: (function () { /** * Reads whitespace characters from the stream. */ Parser.prototype.whitespace = function (state) { return state.read(this.whitespaceCharacter); }; /** * Reads whitespace character from the stream. */ Parser.prototype.whitespaceCharacter = function (state) { if (state.end() || !state.current(/[ \t]/)) { return null; } return state.fetch(); }; /** * Reads characters from the stream. * * Reads the current character and then calls the character method * until it returns null. * * Examples (| - state position): * " |asd, qwe. [a|...] " -&gt; {"asd, qwe. "}, " asd, qwe. |[a|...] " * " |e@mail.com!" -&gt; {"e"}, " e|@mail.com!" * " e|@mail.com!" -&gt; {"@mail.com"}, " e@mail.com|!" */ Parser.prototype.characters = function (state) { return this.createCharacterNode( (this.character(state) || state.fetch() || '') + (state.read(this.character) || '') ); }; /** * Reads character from the stream. * * Returns: * 1. current character when it is uppercase or lowercase letter * from A-Z, digit, comma, point, or white space * 2. character after backslash when it is not from #1 * 3. backslash when it is followed by the character from #1 * 4. null when the state ends or not #1-#3. * * Examples (| - state position): * a|sdf -&gt; s, as|df * a|\sdf -&gt; \, a\|sdf * a|\\sdf -&gt; \, a\\|sdf * a|\.sdf -&gt; ., a\.|sdf * asdf| -&gt; null, asdf| * * Called from: * characters */ Parser.prototype.character = function (state) { if (state.end()) { return null; } if (state.current(/[a-z\d\.\, ]/i)) { return state.fetch(); } if (state.current('\\')) { state.move(); if (state.end() || state.current(/[a-z\d]/i)) { return '\\'; } return state.fetch(); } return null; }; }()); </code></pre> <p>renderer.js</p> <pre><code> Renderer.prototype.node = function (node, callback) { var tag = this.tag.bind(this); switch (node.type) { case 'plugin': this.plugins[node.plugin.name].render(node, callback); break; case 'heading': this.nodes(node.nodes, function (result) { callback(tag('h' + node.level, { id : node.id }, result)); }.bind(this)); break; case 'list': this.nodes(node.nodes, function (result) { callback(tag({ 'unordered' : 'ul', 'ordered' : 'ol' }[node.list], result)); }); break; ... case 'table': this.nodes(node.nodes, function (result) { callback(tag('table', { 'class' : 'table' }, result)); }); break; case 'table-row': this.nodes(node.nodes, function (result) { callback(tag('tr', result)); }); break; ... </code></pre> <p>index.js</p> <pre><code>'use strict'; /*global module, window, require */ var noConflict, ivy; ivy = function (markup, done) { (function (markup, done) { var parser = new this.Parser(), tags = new this.Tags(), renderer = new this.Renderer(tags); renderer.render(parser.parse(markup), done); }.call(ivy, markup, done)); }; if (('undefined' !== typeof module) &amp;&amp; undefined !== module.exports) { ivy.Parser = require('./parser.js'); ivy.Tags = require('./tags.js'); ivy.Renderer = require('./tags.js'); module.exports = ivy; } else if ('undefined' !== typeof window) { if (undefined === window.ivy) { noConflict = (function (previous) { return function () { window.ivy = previous; return ivy; }; }(window.ivy)); } else { noConflict = (function (previous) { return function () { window.ivy = previous; return ivy; }; }(window.ivy())); } ivy.noConflict = noConflict; ivy.Parser = window.ivy.Parser; ivy.Tags = window.ivy.Tags; ivy.Renderer = window.ivy.Renderer; window.ivy = ivy; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:37:53.720", "Id": "33945", "Score": "0", "body": "My first comment would be: Don't make people include 4 separate script files to use your library. Why not provide a fifth script that just includes the other 4 scripts when it runs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:14:50.820", "Id": "33948", "Score": "0", "body": "Per the FAQ, your question needs to contain actual code for review here and not a link to the code. http://codereview.stackexchange.com/faq" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:34:40.840", "Id": "33952", "Score": "0", "body": "Sorry. I've added some significant code examples and engineering ideas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:56:10.397", "Id": "67187", "Score": "0", "body": "If your script is supposed to run in the browser and node per your description I'd suggest you use `this` rather than `window` in *index.js*" } ]
[ { "body": "<p>I've stared at the code for a while;</p>\n\n<ul>\n<li><p>I assuming you wrote <code>whitespaceCharacter</code> to mimic the separation between <code>characters</code> and <code>character</code>. However, since you only refer once to <code>whitespaceCharacter</code> I would put that function inside <code>Parser.prototype.whitespace</code>.</p></li>\n<li><p>The massive case statement in renderer.js gives me the heebeegeebees, one missing <code>break</code> and you are on the hook for some interesting debugging. Personally, I would probably go for something like this ( because <code>node.type</code> is a string):</p>\n\n<pre><code>var nodeTypeHandlers = {\n\n plugin : function(){\n this.plugins[node.plugin.name].render(node, callback);\n }, \n heading: function(){\n this.nodes(node.nodes, function (result) {\n callback(tag('h' + node.level, { id : node.id }, result));\n }.bind(this));\n },\n table: function(){\n this.nodes(node.nodes, function (result) {\n callback(tag('table', { 'class' : 'table' }, result));\n });\n },\n table-row: function(){\n this.nodes(node.nodes, function (result) {\n callback(tag('tr', result));\n });\n },\n ...\n}\n</code></pre>\n\n<p>and then simply execute <code>nodeTypeHandlers[node.type].call(this);</code></p></li>\n<li>Other than that, the code is well commented, readable and JSHint cannot find anything.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-07T14:25:08.710", "Id": "43706", "ParentId": "21153", "Score": "2" } } ]
{ "AcceptedAnswerId": "43706", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:29:23.530", "Id": "21153", "Score": "3", "Tags": [ "javascript", "parsing", "node.js", "template", "modules" ], "Title": "JavaScript templating language: ivy-markup" }
21153
<p>Simplified working <a href="http://jsbin.com/efeyuw/1" rel="nofollow">demo code here</a>.</p> <p>Relevant JS code:</p> <pre><code>;(function(exports) { //-------------------------------------------------------------------------- // // Private properties: // //-------------------------------------------------------------------------- var _msg = '', _ol = document.getElementById('debug'); //-------------------------------------------------------------------------- // // Public methods: // //-------------------------------------------------------------------------- exports.init = function(arg) { _msg = arg; // Add a listener to the `window.resize` event, pass `exports`/`self` as the scope: _addEvent(window, 'resize', _listenForChange, exports); }; //-------------------------------------------------------------------------- // // Private methods: // //-------------------------------------------------------------------------- function _addEvent(elem, type, handle, context) { // Attache event: if (elem) { if (elem.addEventListener) { // If the browser supports event listeners, use them: elem.addEventListener(type, function() { handle.call(context); }, false); } else if (elem.attachEvent) { // IE &amp; Opera: elem.attachEvent('on' + type, function() { handle.call(context); }); } else { // Otherwise, replace the current thing bound to `on[whatever]`! elem['on' + type] = function() { handle.call(context); }; } } } function _listenForChange() { var li = document.createElement('li'); li.innerHTML = String(_msg); _ol.appendChild(li); if (typeof console !== 'undefined') console.log(_msg); } return exports; // Expose the API. }(window.FOO = window.FOO || {})); //-------------------------------------------------------------------- window.onload = function() { FOO.init('world'); FOO.init('universe'); }; </code></pre> <h3>Problem with existing code:</h3> <p>When re-sizing the window, I only see "universe".</p> <h3>Goal:</h3> <p>When browser window re-sizes, I want to world "world" and "universe" output as a list item (and to the console).</p> <p>I want to have the ability to instantiate <code>FOO</code> multiple times and have it work independently from any other running instances.</p> <h3>My questions:</h3> <p>Is there a pattern (or patterns), similar to the one(s) that I'm currently using, that will allow me to run multiple instances of <code>FOO</code> without having the last <code>FOO</code> called trump all previously called <code>FOO</code>s?</p> <p>The code I posted is obviously not real world; my end goal is to allow/modify a plugin I wrote to be used without the end user having to worry if <code>FOO</code> is already being used by another script.</p> <p>Please let me know if I can clarify anything and/or provide more specific code.</p>
[]
[ { "body": "<p>There is only one copy of <code>window.FOO</code> and <code>window.FOO.init</code>, despite its name does not create new objects. <code>window.FOO.init</code> just overwrites <code>_msg</code> that <code>(function(exports) {...</code> closed over each time it is called. <code>_listenForChange()</code> holds a reference to the closed over <code>_msg</code>. If you want it to <em>keep a copy of the value</em> at the time <code>init</code> is called then you can do like so:</p>\n\n<pre><code>_addEvent(window, 'resize', listenForChange2(), exports);\n\nvar listenForChange2 = function() {\n var msg = _msg; // keep own copy of the _msg\n return function() {\n var li = document.createElement('li');\n li.innerHTML = String(\"second version \" + msg);\n _ol.appendChild(li);\n if (typeof console !== 'undefined') console.log(msg);\n }\n}\n</code></pre>\n\n<h2>Review of the code posted in the EDIT #1</h2>\n\n<p>First of all you are still confused about closures. It is important that you understand them because they are how you associate some state with a function. But explaining closures is not within the scope of Code Review. And you probably won't get any better answers than these, the accepted answer in <a href=\"https://stackoverflow.com/questions/111102/how-do-javascript-closures-work\">this SO question</a> and <a href=\"http://web.archive.org/web/20070510000404/http://laurens.vd.oever.nl/weblog/items2005/closures/\" rel=\"nofollow noreferrer\">this article</a> linked from there. You can fix your bug if you understand these. </p>\n\n<p>Also the answer above fixes the bug if you KEEP the parens here:</p>\n\n<pre><code>_addEvent(window, 'resize', listenForChange2(), exports);\n</code></pre>\n\n<p>I the <a href=\"http://jsbin.com/efeyuw/6/edit\" rel=\"nofollow noreferrer\">JSBIN you posted</a> just add the parens and It works. So I will not repeat how can you fix the answer in the new code. </p>\n\n<p>Onto the review. I will go over the code top down:</p>\n\n<pre><code> exports.init = function(arg) {\n</code></pre>\n\n<p>By convention <code>init</code> method of an object is used for object initialization. It is not what it does here. Better name</p>\n\n<pre><code> this._msg = arg;\n</code></pre>\n\n<p>You need not keep a copy of <code>_msg</code> since it will not be used elsewhere. You prepend the name with an underscore as if to indicate it is a private member (which practice I do not recommend BTW), but then expose it as public by assigning to <code>this.</code>. You can see, in the Firebug console for example, that Foo._msg is defined. </p>\n\n<pre><code> exports.listenForChange = function() {\n</code></pre>\n\n<p>You need not expose this either.</p>\n\n<pre><code> var listenForChange = function() {\n</code></pre>\n\n<p>would be just as good.</p>\n\n<pre><code> var msg = this._msg;\n</code></pre>\n\n<p>If you do not create a new function, copying the value does not do anything.</p>\n\n<pre><code> exports.addEvent = function(elem, type, handle, context) {\n</code></pre>\n\n<p>You need not expose this either, as it will not be called like <code>Foo.addEvent</code>.</p>\n\n<p>Also adding another layer of indirection solving any problem, does not apply here. \nWhenever there is something you do not understand, namely a bug, \nadding another layer exacerbates the problem. \nWhat does <code>this</code> refer to when the <code>listenForChange</code> function is run?</p>\n\n<p>Even if you fix your bug this may introduce another one: </p>\n\n<pre><code> elem['on' + type] = function() { handle.call(context); };\n</code></pre>\n\n<p>You are overwriting the onclick. Only the last handler assigned to the <code>onResize</code> will fire.</p>\n\n<p>This is unnecessary:</p>\n\n<pre><code> return exports; // Expose the API.\n</code></pre>\n\n<p>No one is using the returned value. \nMoreover the comment is misleading as everything you assingn to <code>exports.</code> will be exposed,\nwhether you return it or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T13:51:04.213", "Id": "33981", "Score": "0", "body": "On the `_addEvent()`, `listenForChange2()` should be just `listenForChange2`. It should not be a call, just a passing of `listenForChange2` to `_addEvent()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:42:52.910", "Id": "34022", "Score": "0", "body": "Thank you abuzittin-gillifirca and @joseph-the-dreamer, I really appreciate the pro help! I've updated my question (see \"EDIT #1\") to show my progress based on your feedback. If you have the spare time, I'd love to know what your thoughts are on my updated code/question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T20:44:12.830", "Id": "34690", "Score": "0", "body": "@abuzittin-gillifirca just curious if you have any feedback on the edit to my answer? Using your suggestion, I was only able to get \"world\" to output on `init` and everything else was \"universe\". Is there a pattern, or a way, for me to use `var foo1 = New FOO(), foo2 = New FOO(); foo1.init('world'); foo2.init('universe');`? I've nevered used `New` in a plugin before... Seems like that would do what I want, but would you recommended it based on what you've seen of my code? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T07:09:43.027", "Id": "34706", "Score": "0", "body": "@MickyHulse First of all in this http://jsbin.com/efeyuw/2 version you NEED the parentheses after listenForChange2, because the function you need is the result of calling listenForChange2 not listenForChange2 itself. Note listenForChange2 creates a new function each time it is called that is how it is possible to have different events firing. I will try review the newly posted code as soon as job permits. code cannot be posted in comments, so i will probably append it to the previous answer.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T20:53:02.027", "Id": "34771", "Score": "0", "body": "@abuzittingillifirca WOW, thank you!!!! Your latest update really helped to clarify things for me. Thanks so much for taking the time to help me out, I really appreciate it! I owe you one. Have an awesome day. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:57:11.927", "Id": "21170", "ParentId": "21156", "Score": "2" } } ]
{ "AcceptedAnswerId": "21170", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:32:24.777", "Id": "21156", "Score": "0", "Tags": [ "javascript", "design-patterns" ], "Title": "Using closure, alias and namespace extension patterns: How to allow for independent instantiations of plugin?" }
21156
<p>I use the following PHP Code to output the user's local time and the servers time (office time). <code>$local_time</code> and <code>$remote_time</code> are the corresponding UNIX timestamps:</p> <pre><code>&lt;span class='icon-time' data-time='&lt;?php echo $local_time; ?&gt;' id='local-time'&gt; Local : &lt;?php echo date('D, M j, h:ia', $local_time); ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class='icon-time text-&lt;?php echo (6 &gt; date('N') &amp;&amp; 9 &lt;= date('G') &amp;&amp; date('G') &lt;= 17) // change class if open/closed ? 'success' : 'error'; ?&gt;' data-time='&lt;?php echo $remote_time; ?&gt;' id='remote-time'&gt; Office : &lt;?php echo date('D, M j, h:ia', $remote_time); ?&gt;&lt;/span&gt; </code></pre> <p>I then have the following JavaScript to update the clocks in real-time:</p> <pre><code>// update local/office clocks window.setInterval(function () { lclock = $('#local-time'); rclock = $('#remote-time'); // convert to UNIX timestamp, add 60 secs since setInterval() will no start onload but after 60 secs ltime = new Date((lclock.data('time') * 1000) + 60000); rtime = new Date((rclock.data('time') * 1000) + 60000); lhours = ltime.getHours(); rhours = rtime.getHours(); // make 12hr time format and left-pad with zero lshours = ((0 === lhours) ? 12 : (lhours - ((12 &lt; lhours) ? 12 : 0))); rshours = ((0 === rhours) ? 12 : (rhours - ((12 &lt; rhours) ? 12 : 0))); lmins = ltime.getMinutes(); rmins = rtime.getMinutes(); rday = rtime.getDay(); // determine if office is closed and change class ostatus = 'icon-time ' + ((6 &gt; rday &amp;&amp; 0 &lt; rday &amp;&amp; 9 &lt;= rhours &amp;&amp; 17 &gt;= rhours) ? 'text-success' : 'text-error'); // update clock, increment timestamp by 60 secs lclock.text('Local : ' + days[ltime.getDay()] + ', ' + months[ltime.getMonth()] + ' ' + ltime.getDate() + ', ' + ((10 &gt; lshours) ? '0' + lshours : lshours) + ':' + ((10 &gt; lmins) ? '0' + lmins : lmins) + ((12 &lt;= lhours) ? 'pm' : 'am')).data().time += 60; // update clock, change CSS class, increment timestamp by 60 secs rclock.text('Office : ' + days[rtime.getDay()] + ', ' + months[rtime.getMonth()] + ' ' + rtime.getDate() + ', ' + ((10 &gt; rshours) ? '0' + rshours : rshours) + ':' + ((10 &gt; rmins) ? '0' + rmins : rmins) + ((12 &lt;= rhours) ? 'pm' : 'am')).attr('class', ostatus).data().time += 60; }, 60000); </code></pre> <p>It works great. However, after a few hours the time can end up being off by up to -7 minutes. I tried caching as many objects as I could and optimizing it the best I could to reduce the amount of variable value assignments, and used chaining as well, but can't see how else to speed it up to make it not lose time.</p> <ul> <li>How can I optimize this further, in either my method, code being used, or is there something I am doing wrong?</li> </ul>
[]
[ { "body": "<p>The thing to understand with <code>setInterval()</code> and other timer-based functions in general is that they <em>do not guarantee precise timing</em>. You request an interval of 60000ms, and your mistake is assuming that what you get is in fact an interval of <em>exactly</em> 60000ms. </p>\n\n<p>The main trick is to measure the actual amount of elapsed time between intervals, rather than assuming that each interval occurs exactly 60000ms after the previous one. Do that and you should see better results.</p>\n\n<p>Note that there may also be secondary effects caused by the execution time of your code itself. To get around <em>that</em>, instead of adding deltas on each invocation you could track the initial starting timestamp at which your script starts running, and then just always compute the total amount of time that has elapsed between that starting timestamp and now, and add that amount to the starting timestamp when displaying the time. That should give you very accurate output, and it solves the problem of the imprecise timer as well.</p>\n\n<p>Here's a similar <a href=\"http://www.suncoastpc.com.au/toys/jstimer/timer.js\" rel=\"nofollow\">JavaScript timer</a> that I coded awhile back that you can use as a reference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T06:22:45.250", "Id": "33956", "Score": "1", "body": "Excellent suggestions! I'll re-work it and see how it works out and will be back. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:02:53.150", "Id": "33972", "Score": "0", "body": "Re-did code per your suggestions and working great." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T05:28:29.723", "Id": "21158", "ParentId": "21157", "Score": "4" } } ]
{ "AcceptedAnswerId": "21158", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T05:17:18.867", "Id": "21157", "Score": "2", "Tags": [ "javascript", "php", "jquery", "optimization" ], "Title": "Optimize Clock Update Code To Prevent Bottleneck Resulting In Time Lost" }
21157
<p>I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns. I have the following code, which works as I want it to currently, but I feel it is a bit ugly. How can I simplify it/make it more pythonic (without changing the output behaviour)?</p> <p>For starters I think I could probably use the alignment <code>'&lt;'</code> option of the <a href="http://docs.python.org/2/library/string.html#formatstrings"><code>str.format</code></a> stuff if I could just figure out the syntax properly...</p> <pre><code>def tabulate(words, termwidth=79, pad=3): width = len(max(words, key=len)) ncols = max(1, termwidth // (width + pad)) nrows = len(words) // ncols + (1 if len(words) % ncols else 0) #import itertools #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue='')) # row-major table = [words[i::nrows] for i in xrange(nrows)] # column-major return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:20:20.877", "Id": "33959", "Score": "1", "body": "Not worth an answer, but you can get your rounded-up-not-down integer division to compute `nrows` in a much more compact form as `nrows = (len(words) - 1) // ncols + 1`. Seee e.g. http://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Quotients" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T12:26:36.657", "Id": "33980", "Score": "0", "body": "Thanks, I knew there was a better way when I was writing that... I'd just forgotten the usual trick (which, actually, I usually used adding the denominator - 1 to the numerator, i.e. `(len(words) + ncols - 1) // ncols` ... it seems to be equivalent to your trick" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T02:26:45.017", "Id": "35302", "Score": "0", "body": "I found a nice alternative, after `pip install prettytable`. No need to reinvent the wheel I guess .." } ]
[ { "body": "<p>A slightly more readable version:</p>\n\n<pre><code>def tabulate(words, termwidth=79, pad=3):\n width = len(max(words, key=len)) + pad\n ncols = max(1, termwidth // width)\n nrows = (len(words) - 1) // ncols + 1\n table = []\n for i in xrange(nrows):\n row = words[i::nrows]\n format_str = ('%%-%ds' % width) * len(row)\n table.append(format_str % tuple(row))\n return '\\n'.join(table)\n</code></pre>\n\n<p>Most notably, I've defined <code>width</code> to include padding and using string formatting to generate a format string to format each row ;).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T22:42:59.757", "Id": "22941", "ParentId": "21159", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T06:34:47.553", "Id": "21159", "Score": "5", "Tags": [ "python", "strings" ], "Title": "Nicely tabulate a list of strings for printing" }
21159
<p>The following functional program factors an integer by trial division. I am not interested in improving the efficiency (but not in decreasing it either), I am interested how it can be made better or neater using functional constructions. I just seem to think there are a few tweaks to make this pattern more consistent and tight (this is hard to describe), without turning it into boilerplate. </p> <pre><code>def primes(limit): return (x for x in xrange(2,limit+1) if len(factorization(x)) == 1) def factor(factors,p): n = factors.pop() while n % p == 0: n /= p factors += [p] return factors+[n] if n &gt; 1 else factors def factorization(n): from math import sqrt return reduce(factor,primes(int(sqrt(n))),[n]) </code></pre> <p>For example, <code>factorization(1100)</code> yields:</p> <pre><code>[2,2,5,5,11] </code></pre> <p>It would be great if it could all fit on one line or into two functions that looked a lot tighter -- I'm sure there must be some way, but I can not see it yet. What can be done?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:44:41.827", "Id": "33965", "Score": "0", "body": "so `factorization` is the function you want out of this? because you don't need `primes` to get it (note also that factorization calls primes and primes calls factorization, that does not look good)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:08.487", "Id": "33966", "Score": "0", "body": "Why would that not be good? I thought it looked cool. Please explain." } ]
[ { "body": "<p>A functional recursive implementation:</p>\n\n<pre><code>def factorization(num, start=2):\n candidates = xrange(start, int(sqrt(num)) + 1)\n factor = next((x for x in candidates if num % x == 0), None)\n return ([factor] + factorization(num / factor, factor) if factor else [num]) \n\nprint factorization(1100)\n#=&gt; [2, 2, 5, 5, 11]\n</code></pre>\n\n<p>Check <a href=\"https://github.com/tokland/pyeuler/blob/master/pyeuler/toolset.py\" rel=\"nofollow\">this</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:26.567", "Id": "33967", "Score": "0", "body": "Cool thanks. But I dislike recursion because of stack overflows or max recursion depth. I will try to understand your code though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:55:33.400", "Id": "33968", "Score": "0", "body": "I like get_cardinal_name !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:09:27.743", "Id": "33969", "Score": "0", "body": "Note that the function only calls itself for factors of a number, not for every n being tested, so you'll need a number with thousands of factor to reach the limit. Anyway, since you are learning on Python and functional programming, a hint: 1) lists (arrays) don't play nice with functional programming. 2) not having tail-recursion hinders functional approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:23:18.430", "Id": "33970", "Score": "0", "body": "Okay, cool tips about those things. Thanks. I will try to understand this better!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:43:23.810", "Id": "21168", "ParentId": "21165", "Score": "2" } } ]
{ "AcceptedAnswerId": "21168", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:58:40.743", "Id": "21165", "Score": "1", "Tags": [ "python", "functional-programming", "integer" ], "Title": "How to improve this functional python trial division routine?" }
21165
<p>I have made this HTML5 structure for a new website I am working on. I'd like to know if there is a more elegant approach to doing it.</p> <p><img src="https://i.stack.imgur.com/Bhu3J.jpg" alt="Here is the Wireframe"></p> <ol> <li>Is the wrapper for the two column considered bad practice?</li> <li>Should the secondary navigation on the left be an <code>article</code> or a <code>div</code>?</li> </ol> <p></p> <pre><code>&lt;body&gt; &lt;header class="main"&gt; &lt;p&gt;header&lt;/p&gt; &lt;/header&gt; &lt;div class="wrapper"&gt; &lt;!-- Column left --&gt; &lt;section class="column_left"&gt; &lt;header&gt; &lt;article&gt; &lt;h1&gt;H1 title&lt;/h1&gt; &lt;p&gt;Lorem ipsum dolor sit amen lorem ipsum dolor sit amen&lt;/p&gt; &lt;/article&gt; &lt;/header&gt; &lt;nav class="main"&gt; &lt;ul&gt; &lt;li&gt;- main navigation&lt;/li&gt; &lt;li&gt;- main navigation&lt;/li&gt; &lt;li&gt;- main navigation&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;div class="uploadyourphoto"&gt; &lt;p&gt;button call to action&lt;/p&gt; &lt;/div&gt; &lt;article class="secondarynav"&gt; &lt;h2&gt;Title h2 secondary menu&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;article class="secondarynav"&gt; &lt;h2&gt;Title h2 secondary menu&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;li&gt;navigation&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;/section&gt; &lt;!-- Content --&gt; &lt;section class="main"&gt; &lt;header class="slideshow"&gt; &lt;p&gt;slideshow widget&lt;/p&gt; &lt;/header&gt; &lt;article class="review"&gt; &lt;p&gt;review widget&lt;/p&gt; &lt;/article&gt; &lt;article class="product_grid"&gt; &lt;h2&gt;product grid title&lt;/h2&gt; &lt;p&gt;Text text text lorem ipsum dolor sit amen &lt;/p&gt; &lt;article class="products"&gt; &lt;ul&gt; &lt;li&gt;product 1&lt;/li&gt; &lt;li&gt;product 2&lt;/li&gt; &lt;li&gt;product 3&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;/article&gt;&lt; &lt;article class="product_grid"&gt; &lt;h2&gt;product grid title&lt;/h2&gt; &lt;p&gt;Text text text lorem ipsum dolor sit amen &lt;/p&gt; &lt;article class="products"&gt; &lt;ul&gt; &lt;li&gt;product 1&lt;/li&gt; &lt;li&gt;product 2&lt;/li&gt; &lt;li&gt;product 3&lt;/li&gt; &lt;/ul&gt; &lt;/article&gt; &lt;/article&gt; &lt;/section&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;/div&gt; &lt;!-- footer --&gt; &lt;footer&gt; &lt;div&gt;footer&lt;/div&gt; &lt;/footer&gt; &lt;/body&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:43:09.570", "Id": "33983", "Score": "0", "body": "When you say `Should the secondary navigation on the left should be a as well instead of an article or a div?` are you referring to the wireframe instead of an article or a div?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T07:21:08.767", "Id": "34043", "Score": "0", "body": "Do you have a page/example with real content? It's hard to tell what kind of content will be filled in. For example, is the \"H1 title\" the site or page heading? Is `.main` the site navigation? Is `.secondarynav` some kind of \"See also\" or is it a sub-menu of the global nav?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T09:01:05.733", "Id": "34149", "Score": "0", "body": "Hi, I used the same class .main for the main HEADER, NAV and SECTION (the main section is the right column, my content).\n\nThe H1 and paragraph are in the left column in all the pages and the H1 is the page title. The \".secondarynav\" is similar to \"see also\"... it's a menu but not very important." } ]
[ { "body": "<ol>\n<li><p>Don't worry about wrapping your content too much if the style cannot be achieved without it. If it can, the extra wrap may be overkill.</p></li>\n<li><p>Your markup relies a lot on the <code>&lt;article&gt;</code> where it may not be necessary. For instance, you put one <code>&lt;article&gt;</code> tag into another, which is odd. You also put and <code>&lt;article&gt;</code> tag into the <code>&lt;header&gt;</code>, which is also odd.</p></li>\n</ol>\n\n<p>If you want simple containers, I would recommend you stick with <code>&lt;div&gt;</code>s with semantic <code>class</code> attributes. They have been around for a while and used for wrapping other tags. They are the tried and true method and their lack of semantic meaning will not confuse the reader or crawler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T20:09:02.173", "Id": "21199", "ParentId": "21166", "Score": "2" } }, { "body": "<p>I'd keep the wrapper, that way you can apply margin, padding, etc. to it and style the entire page instead of replicating the CSS for the two columns.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:58:01.337", "Id": "21204", "ParentId": "21166", "Score": "1" } }, { "body": "<p>Using classes/ids like <code>column_left</code> isn't a very semantic approach; HTML structure doesn't have any concept of \"positioning\" and, assuming you care about HTML readers other than a desktop browser (like screen readers or <a href=\"http://trends.e-strategyblog.com/2013/01/10/percentage-web-traffic-mobile-devices/7164\" rel=\"nofollow\">mobile devices</a>), the idea of \"left\" just doesn't apply.</p>\n\n<p>Instead, try describing <strong>what</strong> the content is. Instead of <code>class=\"column_left\"</code>, you could use <code>id=\"sub-content\"</code> or <code>id=\"related\"</code>. Just choose something that describes the \"what\" without referring to appearance or positioning.</p>\n\n<p>In regards to your use of <code>article</code> elements, the <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-article-element\" rel=\"nofollow\">HTML5 spec</a> says:</p>\n\n<blockquote>\n <p>The <code>article</code> element represents a complete, or <strong>self-contained</strong>,\n composition in a document, page, application, or site and that is, in\n principle, <strong>independently distributable or reusable</strong>, e.g. in\n syndication. This could be a forum post, a magazine or newspaper\n article, a blog entry, a user-submitted comment, an interactive widget\n or gadget, or any other independent item of content.</p>\n</blockquote>\n\n<p>Key emphasis added to illustrate that <code>article</code> is meant to be used to say \"this is some <em>real</em> content\", distinguishing it from containers and markup added to \"frame\" the content (like sidebars).</p>\n\n<p>Also, your use of <code>section</code> elements is not in-keeping with the specification. The <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-article-element\" rel=\"nofollow\">HTML5 specification</a> says:</p>\n\n<blockquote>\n <p>The <code>section</code> element represents a generic section of a document or\n application. A section, in this context, is a thematic grouping of\n content, typically with a heading.</p>\n</blockquote>\n\n<p>It specifically warns:</p>\n\n<blockquote>\n <p>The <code>section</code> element is not a generic container element. When an\n element is needed for styling purposes or as a convenience for\n scripting, authors are encouraged to use the <code>div</code> element instead. A\n general rule is that the section element is appropriate only if the\n element’s contents would be listed explicitly in the document’s\n outline.</p>\n</blockquote>\n\n<p>So, the idea of a \"main\" section probably isn't right. Sections are meant to be ways partition a large article into headed-sections, in very much the way a Wikipedia article is laid out. You could easily say you have a \"main\" article, but a \"main\" section doesn't make as much sense, and you'd be better off replacing yours with simple <code>div</code> elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T13:52:18.830", "Id": "21292", "ParentId": "21166", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-01T08:06:17.800", "Id": "21166", "Score": "5", "Tags": [ "html5" ], "Title": "Structure of website columns and navigation" }
21166
<p>I have the following python functions for <a href="http://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">exponentiation by squaring</a> :</p> <pre><code>def rep_square(b,exp): return reduce(lambda sq,i: sq + [sq[-1]*sq[-1]],xrange(len(radix(exp,2))),[b]) def exponentiate(b,exp): return reduce(lambda res,(sq,p): res*sq if p == 1 else res,zip(rep_square(b,exp),radix(exp,2)),1) </code></pre> <p>They work. Calling <code>print exponentiate(2,10), exponentiate(3,37)</code> yields :</p> <pre><code>1024 450283905890997363 </code></pre> <p>as is proper. But I am not happy with them because they need to calculate a <strong>list</strong> of squares. This seems to be a problem that could be resolved by functional programming because : </p> <ol> <li>Each item in the list only depends on the previous one</li> <li>Repeated squaring is recursive</li> </ol> <p>Despite <a href="https://codereview.stackexchange.com/questions/21165/how-to-improve-this-functional-python-trial-division-routine#comment33965_21165">people mentioning that recursion is a good thing to employ in functional programming, and that lists are not good friends</a> -- I am not sure how to turn this recursive list of squares into a recursive generator of the values that would avoid a list. I know I could use a <em>stateful</em> generator with <code>yield</code> but I like something that can be written in one line. </p> <p>Is there a way to do this with tail recursion? Is there a way to make this into a generator expression? </p> <p>The only thing I have thought of is this <em>particularly ugly</em> and also broken recursive generator : </p> <pre><code>def rep_square(n,times): if times &lt;= 0: yield n,n*n yield n*n,list(rep_square(n*n,times-1)) </code></pre> <p>It never returns. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:16:07.310", "Id": "33973", "Score": "0", "body": "A bit of a naive question but why don't you just rewrite the definition of Function exp-by-squaring(x,n) from Wikipedia in proper python ? It seems fine as far as I can tell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:48:38.967", "Id": "35759", "Score": "0", "body": "@Josay because I want to make one myself." } ]
[ { "body": "<p>You haven't said anything against <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, so here's how I'd do it with generators:</p>\n\n<pre><code>from itertools import compress\nfrom operator import mul\n\ndef radix(b) :\n while b :\n yield b &amp; 1\n b &gt;&gt;= 1\n\ndef squares(b) :\n while True :\n yield b\n b *= b\n\ndef fast_exp(b, exp) :\n return reduce(mul, compress(squares(b), radix(exp)), 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:17:53.700", "Id": "34011", "Score": "0", "body": "I like that. Both these answers are awesome. Showing the beautiful ways of looking at it from two different and complimentary perspectives. Coolness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:49:58.310", "Id": "35760", "Score": "0", "body": "I chose this as the answer because although we have a *tail recursion* version, as asked, and this *generator expression* as asked, I really liked the use of `compress` and the idea of selectors -- which was new for me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:35:54.627", "Id": "21183", "ParentId": "21169", "Score": "1" } }, { "body": "<p>A tail recursive version could look something like this:</p>\n\n<pre><code>def rep_square_helper(x, times, res):\n if times == 1:\n return res * x\n if times % 2:\n return rep_square_helper(x * x, times // 2, res * x)\n else:\n return rep_square_helper(x * x, times // 2, res)\n\ndef rep_square(n, times):\n return rep_square_helper(n, times, 1)\n</code></pre>\n\n<p>Note that in python there is no real advantage to using tail recursion (as opposed to, say, ML where the compiler can <a href=\"http://c2.com/cgi/wiki?TailCallOptimization\" rel=\"nofollow\">reuse stack frames</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:16:28.820", "Id": "34010", "Score": "0", "body": "Oh I like that, that's *really* neat and clean. Exposes the algorithm logic perfectly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T10:15:58.700", "Id": "34101", "Score": "0", "body": "Why do we consider times=1 as the default case instead of times=0 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T17:01:37.547", "Id": "34105", "Score": "0", "body": "Because using this logic `times=0` is an edge case (but you're right, it should be dealt with)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:52:12.083", "Id": "35761", "Score": "0", "body": "@cmh What does ML stand for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T20:57:44.537", "Id": "35766", "Score": "1", "body": "@CrisStringfellow http://fr.wikipedia.org/wiki/ML_(langage)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:14:45.457", "Id": "21186", "ParentId": "21169", "Score": "1" } }, { "body": "<p>One of the things I do not like that much about python is the possibility and trend to crunch everything in one line for whatever reasons (no, do not compare with perl).</p>\n\n<p>For me, a more readable version:</p>\n\n<pre><code>def binary_exponent(base, exponent):\n \"\"\"\\\n Binary Exponentiation\n\n Instead of computing the exponentiation in the traditional way,\n convert the exponent to its reverse binary representation.\n\n Each time a 1-bit is encountered, we multiply the running total by\n the base, then square the base.\n \"\"\"\n # Convert n to base 2, then reverse it. bin(6)=0b110, from second index, reverse\n exponent = bin(exponent)[2:][::-1]\n\n result = 1\n for i in xrange(len(exponent)):\n if exponent[i] is '1':\n result *= base\n base *= base\n return result\n</code></pre>\n\n<p>source (slightly modified): <a href=\"http://blog.madpython.com/2010/08/07/algorithms-in-python-binary-exponentiation/\" rel=\"nofollow\">http://blog.madpython.com/2010/08/07/algorithms-in-python-binary-exponentiation/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T18:03:39.223", "Id": "21194", "ParentId": "21169", "Score": "1" } } ]
{ "AcceptedAnswerId": "21183", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:36:59.913", "Id": "21169", "Score": "1", "Tags": [ "python", "functional-programming", "recursion" ], "Title": "How to improve this functional python fast exponentiation routine?" }
21169
<p>This is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main() { int ch; int numberOfCharacters = 0; printf("please enter a word, and ctrl + d to see the resault\n"); while ((ch = getchar()) != EOF &amp;&amp; isprint(ch)) { numberOfCharacters++; } printf("The number of characters is %d", numberOfCharacters); return 0; } </code></pre> <p>Is this a good code?</p>
[]
[ { "body": "<p>Well, it doesn't do much. But it is not bad. A few issues:</p>\n\n<ul>\n<li>main() should have parameters</li>\n<li>excess blank lines (lines 5, 12, 16, 18) spoil the appearance</li>\n<li>no \\n on the last printf</li>\n<li>the spec doesn't say 'printable' characters, just characters.</li>\n<li>\"please\" needs a capital p and \"resault\" should be \"result\"</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T13:54:40.267", "Id": "33982", "Score": "0", "body": "thank you! i know it dosent do much, but since im a newbie i would love to get feedback like you just wrote so i will know for next time or when i have bigger programs @WilliamMorris" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T13:30:44.617", "Id": "21172", "ParentId": "21171", "Score": "1" } } ]
{ "AcceptedAnswerId": "21172", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:43:53.433", "Id": "21171", "Score": "1", "Tags": [ "c" ], "Title": "Devise a program that counts the number of characters in its input up to the end of file" }
21171
<p>My exercise was:</p> <blockquote> <p>Write a program that reads input as a stream of characters until encountering EOF. Have the program print each input character and its ASCII decimal value. Note that characters preceding the space character in the ASCII sequence are nonprinting characters. Treat them specially. If the nonprinting character is a newline or tab, print \n or \t, respectively. Print 10 pairs per line, except start a fresh line each time a newline character is encountered.</p> </blockquote> <p>This is my code (regarding the special characters, I defined only <code>\n</code> and <code>\t</code>):</p> <pre><code>#include &lt;stdio.h&gt; int special_chars(int ch); int main(void) { int x; printf("please enter a some characters, and ctrl + d to quit\n"); special_chars(x); return 0; } int special_chars(int ch) { int pairsNum = 0; while ((ch = getchar()) != EOF)// testing charecters while not end of file. { if (ch == '\n')// testing if a control charecter, and printing its { printf("\\n "); pairsNum++; } else if (ch == '\t') { printf("\\t "); pairsNum++; } else { printf("%c,%d ", ch, ch); pairsNum++; } if (pairsNum == 10)// counting the number of outputs, and printing a newline when is 10 (limit). printf("\n"); } return ch; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:12:44.047", "Id": "34019", "Score": "2", "body": "Surprised this works: `printf(\"%c,%d \", ch, ch);` %c is expecting a char while %d an int. While ch is always an int." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:57:08.603", "Id": "34033", "Score": "0", "body": "Because in C style formatted printing the 'verbs' like c or d don't expect anything, but take at least a word from the stack and format it according to their meaning/specs: c -> character, d -> decimal representation of the int/word." } ]
[ { "body": "<p>A few issues, in no particular order:</p>\n\n<ul>\n<li>put <code>main</code> last to avoid the need for a prototype.</li>\n<li><code>main</code> normally takes argc/argv parameters</li>\n<li><p><code>special_chars</code> should be static - but it is debateable whether a separate\nfunction is necessary in a short program like this.</p></li>\n<li><p>main defines variable <code>x</code> and passes it to <code>special_chars</code>. This is\nunnecessary. Just define <code>ch</code> in <code>special_chars</code> and define the function as\ntaking <code>void</code> (i.e. nothing)</p></li>\n<li>why does <code>special_chars</code> return a value?</li>\n<li>indenting is wrong</li>\n<li>too many blank lines (8)</li>\n<li>missing {} brackets after <code>if (pairsNum == 10)</code></li>\n<li>mixed naming styles (<code>pairsNum</code> should be <code>pairs_num</code> or <code>special_chars</code> should\nbe <code>specialChars</code> - I prefer the former)</li>\n<li><code>special_chars</code> is a bad name for the function.</li>\n<li><code>pairsNum</code> is an odd name; <code>n_pairs</code> would be my choice.</li>\n<li>you don't print a final \\n at the end of the program </li>\n<li><p>you don't start a new line after reading a \\n, as required - it appears that you do when you type at the keyboard because entering a \\n causes a new line. But if you redirect input into your program it\ndoes not. Also you don't start a line after each ten, only after the first ten. e.g. if your program executable is called <code>program</code></p>\n\n<pre><code>$ cat x\nabcdefgh\nijklmnop\nqrstuvwxyz\n\n$./program &lt; x\nplease enter a some characters, and ctrl + d to quit\na,97 b,98 c,99 d,100 e,101 f,102 g,103 h,104 \\n i,105 \nj,106 k,107 l,108 m,109 n,110 o,111 p,112 \\n q,113 r,114 s,115 t,116 u,117 v,118 w,119 x,120 y,121 z,122 \\n $ \n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:57:38.970", "Id": "21198", "ParentId": "21174", "Score": "4" } }, { "body": "<h2>Interpretation of the problem specification</h2>\n\n<p>The desired output format is a bit underspecified, but I think you could have done a better job interpreting it. In addition to the bug what @WilliamMorris spotted (where you output a line break after the 10th character, but not after the 20th, 30th, etc.), the output is, frankly, a mess:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>$ ./program &lt; /etc/hosts\nplease enter a some characters, and ctrl + d to quit\n#,35 #,35 \\n #,35 ,32 H,72 o,111 s,115 t,116 ,32 \nD,68 a,97 t,116 a,97 b,98 a,97 s,115 e,101 \\n #,35 \\n #,35 ,32 l,108 o,111 c,99 a,97 l,108 h,104 o,111 s,115 t,116 ,32 i,105 s,115 ,32 u,117 s,115 e,101 d,100 ,32 t,116 o,111 ,32\n</code></pre>\n</blockquote>\n\n<p>Wouldn't this look so much nicer? (It uses 78 characters per line — just right for a standard 80-column terminal.)</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>$ ./cr21174 &lt; /etc/hosts\n # 35 # 35 \\n 10 # 35 32 H 72 o 111 s 115 t 116 32\n D 68 a 97 t 116 a 97 b 98 a 97 s 115 e 101 \\n 10 # 35\n\\n 10 # 35 32 l 108 o 111 c 99 a 97 l 108 h 104 o 111\n s 115 t 116 32 i 105 s 115 32 u 117 s 115 e 101 d 100\n 32 t 116 o 111 32 c 99 o 111 …\n</code></pre>\n \n \n</blockquote>\n\n<p>The specification says that you should treat non-printing characters specially, but other than for newline and tab, it doesn't say exactly how. I would interpret it to mean that you should output some kind of placeholder (preferably one that preserves the nice alignment).</p>\n\n<h2>Prompting</h2>\n\n<p>It is not always appropriate to prompt the user to enter input like that. For one thing, the prompt makes no sense if the program is receiving its standard input via a pipe or redirection. Furthermore, you shouldn't mingle the prompt with the proper output of the program, in case the user wants to capture the printout.</p>\n\n<pre><code>if (isatty(STDIN_FILENO))\n{\n fprintf(stderr, \"please enter a some characters, and ctrl + d to quit\\n\");\n}\n</code></pre>\n\n<p>… where <a href=\"http://linux.die.net/man/3/isatty\" rel=\"nofollow\"><code>isatty(3)</code></a> is declared in <code>&lt;unistd.h&gt;</code>.</p>\n\n<p>I assume that you are targeting a Unix-like environment, since you hard-coded <code>\"ctrl + d\"</code>. If you wanted to include Windows as well, you would need a <a href=\"http://msdn.microsoft.com/en-us/library/f4s0ddew\" rel=\"nofollow\">compatibility shim</a>:</p>\n\n<pre><code>#if defined(_WIN32) || defined(_MSDOS)\n# include &lt;io.h&gt;\n# define isatty(x) _isatty(x)\n# define STDIN_FILENO _fileno(stdin)\n# define EOF_SEQ \"ctrl + z\"\n#else\n# include &lt;unistd.h&gt;\n# define EOF_SEQ \"ctrl + d\"\n#endif\n\n…\n\nif (isatty(STDIN_FILENO))\n{\n fprintf(stderr, \"please enter a some characters, and \" EOF_SEQ\n \" to quit\\n\");\n}\n</code></pre>\n\n<h2>Implementation</h2>\n\n<p><code>special_chars()</code> should not take a <code>char</code> parameter. Your compiler should have warned you that <code>x</code> was uninitialized. (You do compile with warnings enabled, I hope?) On the other hand, what would be a reasonable parameter is the number of pairs per line.</p>\n\n<p>It is customary to put <code>main()</code> at the end of the program, so that you don't have to forward-declare the functions that it needs to call.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n\nvoid special_chars(int pairs_per_line)\n{\n int ch;\n for (int count = 1; (ch = getchar()) != EOF; count++)\n {\n char *delimiter = (count % pairs_per_line == 0) ? \"\\n\" : \" \";\n if (ch &lt; ' ') // Non-printing characters\n {\n char esc;\n switch (ch)\n {\n case '\\n': esc = 'n'; break;\n case '\\t': esc = 't'; break;\n default: esc = '?';\n }\n printf(\"\\\\%c %3d%s\", esc, (int)ch, delimiter);\n }\n else\n {\n printf(\"%2c %3d%s\", ch, (int)ch, delimiter);\n }\n }\n putchar('\\n');\n}\n\nint main(void)\n{\n if (isatty(STDIN_FILENO))\n {\n fprintf(stderr, \"please enter a some characters, and ctrl + d to quit\\n\");\n }\n special_chars(10);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T19:23:04.420", "Id": "74318", "ParentId": "21174", "Score": "2" } } ]
{ "AcceptedAnswerId": "21198", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:36:45.537", "Id": "21174", "Score": "4", "Tags": [ "c", "homework", "formatting" ], "Title": "Print character + the ASCII value, 10 pairs per line" }
21174
<p><a href="http://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow">Description of Kadane's algorithm</a>. Please comment on the efficiency and approach.</p> <pre><code>class Kadane { int sum = 0; int max = 0; public static void main(String[] args) { int[] full = { 1, 2, 3, 4, 5, -6, -77, 3, 14, -10 }; Kadane Kadane = new Kadane(); int max = Kadane.splitArr(full); System.out.println("The maximum value of the seq is " + max); } public int localMax(int[] full, int sublength) { for (int i = sublength; i &gt;= 0; i--) { sum = sum + full[i]; if (sum &gt; max) { max = sum; } } sum = 0; return max; } public int splitArr(int[] full) { int sum_final = 0; int max_final = 0; for (int j = 0; j &lt; full.length; j++) { sum_final = localMax(full, j); if (sum_final &gt; max_final) { max_final = sum_final; } } return max_final; } } </code></pre>
[]
[ { "body": "<p>Ok, let's take a look:</p>\n\n<pre><code>Kadane Kadane = new Kadane();\n</code></pre>\n\n<p>If there is no need for it, I would use static methods and avoid object creation:</p>\n\n<pre><code>public static int localMax(int[] full, int sublength) {...}\npublic static int splitArr(int[] full) {...}\nint max = splitArr(full);\n//(+ next point)\n</code></pre>\n\n<hr>\n\n<pre><code>int sum = 0;\nint max = 0;\n</code></pre>\n\n<p>I do not see the reason why they are class variables? You could use them in the method scope and have 2 benefits:</p>\n\n<ol>\n<li>You do not have any state inside your class, which makes the methods recallable.</li>\n<li><p>You can be sure nobody starts to modify it somewhere.</p>\n\n<pre><code>public int localMax(int[] full, int sublength) {\n final int sum = 0;\n final int max = 0;\n //...\n}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<pre><code>public int splitArr(int[] full)\n</code></pre>\n\n<p>This is a bad name. If someone reads only the method name, it is impossible to figure out what this is doing. You would expect to split an array? Then you would expect to get back one or multiple arrays. But you get an int.<br>\nA better method name could be:</p>\n\n<pre><code>public int getMaximumSumOfAllSubarraysFromArray(final int[] array)\n</code></pre>\n\n<p>(same goes for <code>localMax</code>)</p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<pre><code>if (sum &gt; max) {\n max = sum;\n}\n//...\nif (sum_final &gt; max_final) {\n max_final = sum_final;\n}\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>max = Math.max(max, sum);\nmax_final = Math.max(max_final, sum_final);\n</code></pre>\n\n<p>Which makes the intention directly clear.</p>\n\n<hr>\n\n<p>If we take this line:</p>\n\n<pre><code>sum_final = localMax(full, j);\n</code></pre>\n\n<p>You could inline the function <code>localMax</code>:</p>\n\n<pre><code>public int splitArr(final int[] full) {\n int sum_final = 0;\n int max_final = 0;\n for (int j = 0; j &lt; full.length; j++) {\n int sum = 0;\n for (int i = j; i &gt;= 0; i--) {\n sum = sum + full[i];\n sum_final = Math.max(sum_final, sum);\n }\n max_final = Math.max(max_final, sum_final);\n }\n\n return max_final;\n}\n</code></pre>\n\n<p>Then we look what is happening here:</p>\n\n<ul>\n<li>In the 1. loop iteration, we check calculate the sum from index 0 to index 0</li>\n<li>In the 2. loop iteration, we check calculate the sum from index 1 to index 0</li>\n<li>In the 3. loop iteration, we check calculate the sum from index 2 to index 0</li>\n</ul>\n\n<p>We can see a pattern here. We do not have to do all the calculations from previous sums, we just use the previous result and add the new current element:</p>\n\n<pre><code>int sum = 0;\nfor (int j = 0; j &lt; full.length; j++) {\n sum = sum_final + full[i];\n sum_final = Math.max(0, sum);\n max_final = Math.max(max_final, sum_final);\n}\n</code></pre>\n\n<ol>\n<li>Good thing: We got rid of the O(n^2) complexity back to O(n). </li>\n<li><p>Good thing: we can simplify it even more. The variable sum is not necessary and we can use a <code>foreach</code>:</p>\n\n<pre><code>public int splitArr(final int[] full) {\n int sum_final = 0;\n int max_final = 0;\n for (final int element : full) {\n sum_final = Math.max(0, sum_final + element);\n max_final = Math.max(max_final, sum_final);\n }\n return max_final;\n}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>We can choose some better names for all the variables and if we apply all the mentioned things we could end up with:</p>\n\n<pre><code>public static int getMaximumSumOfAllSubarraysFromArray(final int[] array) {\n int currentMaximum = 0;\n int overallMaximum = 0;\n for (final int arrayItem : array) {\n currentMaximum = Math.max(0, currentMaximum + arrayItem);\n overallMaximum = Math.max(overallMaximum, currentMaximum);\n }\n return overallMaximum;\n}\n</code></pre>\n\n<p>(which is by the way the same algorithm as mentioned from the Wikipedia link, and I think the best one for single thread, typical environments. It could be improved by removing the first Math.max, merging the branches and saving a little part of branching, but this would reduce readability):</p>\n\n<pre><code>public int getMaximumSumOfAllSubarraysFromArray(final int[] array) {\n int currentMaximum = 0;\n int overallMaximum = 0;\n for (final int arrayItem : array) {\n currentMaximum = currentMaximum + arrayItem;\n if (currentMaximum &gt; 0)\n overallMaximum = Math.max(overallMaximum, currentMaximum);\n else\n currentMaximum = 0;\n }\n return overallMaximum;\n}\n</code></pre>\n\n<hr>\n\n<p>One last piece of advice: If you develop such algorithms and refactor them, you should always have some unit tests for this. Better more than less.</p>\n\n<p>I hope you can combine this hints to a full working approach. If not, just mention the flaws in my descriptions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:20:18.623", "Id": "34112", "Score": "0", "body": "Thanks for the detailed code review. I updated the code. I have to learn unit testing. I will post another code review question and get my unit tested code reviewed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:59:56.360", "Id": "34116", "Score": "0", "body": "You are welcome. If you use eclipse, it is very easy to do unit tests with junit. Read some tutorials, this will take less then 5 minutes to create a first test. Try http://www.eclemma.org eclipse plugin for coverage. As always with metrics, it is not all about 100% coverage, but you have some feedback. Design unit tests for different corner case, not different inputs (to make an example here: if you test [1,2,3], then there is no extra value in testing [2,2,3], but for [2,-1,2])." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T17:16:19.530", "Id": "39885", "Score": "0", "body": "Hi tb. Is there a way to contact you privately. I have a quick question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-05T22:30:57.487", "Id": "40012", "Score": "0", "body": "I do not know if there is a way to send private messages on codereview." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:44:51.857", "Id": "21190", "ParentId": "21175", "Score": "4" } } ]
{ "AcceptedAnswerId": "21190", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:40:23.500", "Id": "21175", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Kadane's Algorithm, finding maximum contiguous array" }
21175
<p>I understand that because of JavaScript's single-threaded execution, long loops or recursive calls could make the browser unresponsive while they execute.</p> <p>I thought about simulating recursion using <code>setTimeout</code> with a delay of 0, so as to queue the next call to execute as soon as possible.</p> <p>Here's an example comparing a standard recursive factorial function with an attempt to do the same thing but using <code>setTimeout</code>:</p> <pre><code>function rFactorial(num) { if (num === 0) return 1; else return num * rFactorial( num - 1 ); } function tFactorial(num, callback, acc) { acc = acc || 1; if (num === 0) { callback(acc); } else { setTimeout(function() { tFactorial(num-1, callback, acc*num); }, 0); } } </code></pre> <p>I tested this using the following test:</p> <pre><code>for (var x = 1; x &lt; 20; x += 1) { tFactorial(x, (function(n) { return function(result) { console.log(rFactorial(n) === result) }; })(x)); } </code></pre> <p>This worked for that range of numbers, although for higher numbers the two functions seem to give different results. for example, for 100, <code>sFactorial</code> gives <code>9.332621544394418e+157</code>, while <code>rFactorial</code> gives <code>9.33262154439441e+157</code>.</p> <p>I have two questions:</p> <ol> <li>Is this a good approach? Can anyone suggest any improvements etc?</li> <li>Can anyone shed any light on why the two functions give the same results for lower numbers but different results for higher numbers?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:09:51.067", "Id": "33984", "Score": "0", "body": "It may not be directly because of recursion. It may be how you are passing the values per iteration *plus* the fact that JS is known to mishandle floats." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:12:31.993", "Id": "33985", "Score": "0", "body": "@JosephtheDreamer *\"JS is known to mishandle floats\"* ? What does that mean ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:15:17.100", "Id": "33986", "Score": "1", "body": "You may want to look at this:\n\nhttp://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:20:36.430", "Id": "33987", "Score": "0", "body": "But (correct me if I'm wrong) `acc` is never a floating point number, it is just displayed in scientific notation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:21:24.000", "Id": "33988", "Score": "0", "body": "acc, like all numbers in javascript is a double precision float (IEEE754). And there is no known problem with javascript handling of float." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:29:10.910", "Id": "33991", "Score": "0", "body": "What I mean is, in reply to Dimitry, it doesn't look like an instance of the same type as `0.1 * 0.2` giving `0.020000000000000004`, since none of the numbers being multiplied have any non-zero digits beyond the decimal point (i.e. they are all whole numbers)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:31:03.463", "Id": "33992", "Score": "1", "body": "*JS is known to mishandle floats* is FUD. Get your facts straight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:31:04.823", "Id": "33993", "Score": "0", "body": "Note that it doesn't make sense to compute in javascript integer greater than 2^52 as the size of the mantiss is 52 bits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:47:53.803", "Id": "33997", "Score": "0", "body": "I tested it, and the difference in precision seems to have been caused by the accumulator, not the callback or setTimeout." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:30:55.260", "Id": "34002", "Score": "4", "body": "I was discussing the issue with a clever guy on Stack Overflow, and he found the difference in results is because of differences in the order of multiplication. A simple example: 0.1 * 0.2 * 0.3 yields a different result than 0.3 * 0.2 * 0.1, because intermediate results are different." } ]
[ { "body": "<p>A few observations :</p>\n\n<p>Numbers in javascript are <a href=\"http://en.wikipedia.org/wiki/IEEE_floating_point\" rel=\"nofollow\">IEE754</a> double precision float. All of them. There is no integer type. Which means that only 53 bits are available to describe the integer part. So it doesn't make sense to try to do integer operations on numbers bigger than that. Your numbers are wayyy too big and the results will be undefined. If you want to compute bigger numbers, you'll need to define your own format, you can't use the native numbers of javascript.</p>\n\n<p>Using <code>setTimeout</code> or using a recursion might be amusing solutions but they're not terribly efficient (at least until we have tail call optimization in javascript). You'd better use a simple boring loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:46:42.090", "Id": "33996", "Score": "0", "body": "\"using a recursion might be amusing solutions but they're not terribly effective\". Even if the aim of the exercise is to prevent the interface freezing while a calculation completes (perhaps not applicable to this function, but can happen), rather than to compute the function as fast as possible? Or would it be better just to use a web worker?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:49:21.213", "Id": "33998", "Score": "1", "body": "Your computation won't freeze the computer if you try to compute numbers smaller than 2^52 : factorial grows very fast. If you have long computations (which I hadn't thought was the problem), then yes you might use `setTimeout` or a webworker." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:53:15.303", "Id": "34000", "Score": "0", "body": "I see. I was only using factorial composition as an example of a recursive function. I was trying to find a general tactic for carrying out recursive computations that might take a long time to complete without freezing the page. Factorial was just the first recursive function that came to mind (although once I noticed the bug in my example, I was keen to understand why it was there)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:32:32.373", "Id": "34005", "Score": "2", "body": "@samfrances Breaking out of deep calculation and splitting work through setTimeout is a known technique but it's not too effective any more. In new browsers you should use Web Workers for this sort of thing instead.Like dystroy said it doesn't make sense to try to do integer operations on numbers this big." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:35:14.683", "Id": "21179", "ParentId": "21176", "Score": "3" } } ]
{ "AcceptedAnswerId": "21179", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T14:45:25.713", "Id": "21176", "Score": "3", "Tags": [ "javascript", "recursion", "timeout" ], "Title": "JavaScript \"recursion\" via setTimeout" }
21176
<p>I have two classes with similar first checking codes, but different behaviors. I suppose there is a way to refactor the code, so I don't need to retype it every time. Is it possible to refactor this, or I must retype this code every time?</p> <pre><code># Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: </code></pre> <p>The code is simple. Forget about my way to render the page, is a method over my own <code>PageHandler</code> class that works.</p> <pre><code># Check for actual logged user def checkLoggedUser(): # Get actual logged user user = users.get_current_user() # Don't allow to register for a logged user if user: return True, "You are already logged in." else: return False, None # Get and post for the login page class Login(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage('login.htm') def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Make the login # bla, bla bla... code for login the user. # Get and post for the register page class Register(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage("registerUser.htm") def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Store in vars the form values # bla, bla bla... code for register the user. </code></pre>
[]
[ { "body": "<p>Create a class</p>\n\n<pre><code>class MyPageHandler(custom.PageHandler):\n def veryUserNotLoggedIn(self):\n if users.getCurrentUser():\n self.renderPage(\"customMessage.htm\", custom_msg=msg)\n return False\n else:\n return True\n</code></pre>\n\n<p>Then you can write you class like</p>\n\n<pre><code>class Login(MyPageHandler):\n def get(self):\n if self.verifyUserNotLoggedIn():\n self.renderPage('login.htm')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:35:17.533", "Id": "34031", "Score": "0", "body": "you are a number one! :) 2 refactors, 2 new knowledges for me. Thank you a lot (I'm a little rusty, I come from VB6... but learning a lot now)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:00:58.667", "Id": "21184", "ParentId": "21178", "Score": "1" } } ]
{ "AcceptedAnswerId": "21184", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:20:37.023", "Id": "21178", "Score": "1", "Tags": [ "python", "logging" ], "Title": "Checking for a logged user" }
21178
<p>Does this code look okay?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int case_letters(); int main(void) { case_letters(); return 0; } int case_letters() { int ch; int numOfUpper = 0; int numOfLower = 0; printf("please enter a some characters, and ctrl + d to see result\n"); while ((ch = getchar()) != EOF) { if (isdigit(ch)) { printf("please enter a valid character\n"); continue; } else if (isupper(ch)) { numOfUpper++; } else if (islower(ch)) { numOfLower++; } } return printf("There are %d Uppercase letters, and %d Lowercase letters\n", numOfUpper, numOfLower); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:10:40.473", "Id": "34018", "Score": "1", "body": "There are more characters that upper()/lower() and digit(). See http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_4.html" } ]
[ { "body": "<p>This does not seem to handle if the user enters a special character. ex: <code>* &amp; %</code> etc...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:33:09.797", "Id": "21189", "ParentId": "21182", "Score": "2" } }, { "body": "<ul>\n<li><p>It looks unusual to have newlines between the function statement and body since they're associated with each other. This just adds extra lines and makes the code a little harder to read.</p></li>\n<li><p>If <code>case_letters()</code> is just supposed to print something at the end and not return a value, it should return <code>void</code> (no value), not <code>int</code>. <code>main()</code> isn't doing anything with this function after calling it.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/2454474/what-is-the-difference-between-printf-and-puts-in-c\">Unformatted outputs should use <code>puts()</code> instead of <code>printf()</code></a>.</p></li>\n<li><p>As @Rhs has mentioned, your program doesn't handle special characters. Based on <a href=\"http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_4.html\" rel=\"nofollow noreferrer\">this</a> from @Loki Astari, there are additional types of characters and with accompanying testing functions.</p></li>\n<li><p>According to <a href=\"https://stackoverflow.com/a/1782134/1950231\">this answer</a>, <kbd>CTRL</kbd><kbd>D</kbd> only works on Mac OS and Linux. For Windows, it's <kbd>CTRL</kbd><kbd>Z</kbd>. All of this should be stated in the output in case the user is running this on Windows.</p></li>\n<li><p>Consider making this more modular for increased maintainability:</p>\n\n<ol>\n<li>keep letter counters for final output (in <code>main()</code>)</li>\n<li>collect each character from user</li>\n<li>determine if the character is a letter</li>\n<li>increment either counter if a letter is entered</li>\n</ol>\n\n<p>Here's what I came up with:</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;stdbool.h&gt; // add this library\n#include &lt;stdio.h&gt;\n\nbool valid_char(char ch)\n{\n if (isdigit(ch)) return false;\n\n // include additional non-letter checks...\n\n // if everything checks out:\n return true;\n}\n\nvoid update_counters(char ch, int* numOfUpper, int* numOfLower)\n{\n if (isupper(ch))\n {\n (*numOfUpper)++;\n }\n else if (islower(ch))\n {\n (*numOfLower)++;\n }\n}\n\nvoid get_letters(int* numOfUpper, int* numOfLower)\n{\n puts(\"Please enter some characters\\n\");\n puts(\"Press CTRL+D on Mac OS/Linux or CTRL+Z on Windows to see the results\\n\");\n char ch;\n\n while ((ch = getchar()) != EOF)\n {\n while (!valid_char(ch))\n {\n puts(\"Character must be a letter\\n\");\n ch = getchar();\n }\n\n update_counters(ch, numOfUpper, numOfLower);\n }\n}\n\nint main(void)\n{\n int numOfUpper = 0;\n int numOfLower = 0;\n\n int* upperPtr = &amp;numOfUpper;\n int* lowerPtr = &amp;numOfLower;\n\n get_letters(upperPtr, lowerPtr);\n\n printf(\"There are %d uppercase letters and %d lowercase letters\\n\", numOfUpper, numOfLower);\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T06:13:06.297", "Id": "46989", "ParentId": "21182", "Score": "6" } } ]
{ "AcceptedAnswerId": "21189", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:59:22.143", "Id": "21182", "Score": "4", "Tags": [ "c", "stream" ], "Title": "Ask for stream of character input and print number of uppercase/lowercase characters" }
21182
<p>What I'm trying to accomplish here is to pull a table of open employment positions with AJAX, filter out the garbage code that comes with it, put each <code>&lt;tr&gt;</code> from the response into its correct category <code>&lt;div&gt;</code> according to the type of position. </p> <p>The trick is that there are no ids or class names on the <code>&lt;tr&gt;</code> being pulled making it dificult to establish which belong where. I've come up with this increadibly specific, repetitive, and limited code. Since there are 3 of these requests I have to make and they're all in the same kind of messy template, I ended up using the same code over and over, but just changing the class and variable names each time. </p> <p>I wanted some suggestions that are generic and expandable if at all possible. Are the if statements really necessecary?</p> <p>Also if you have any code or reading materials you would like to recomend so I could learn from for future references.</p> <p><strong>Relevant jQuery</strong></p> <pre><code>var OpenPositions = { setupAjax: function() { $.support.cors = true; $.ajaxSetup({ type: "GET", async: false, error: function () { console.log('Error'); } }); }, {...} classifiedPull: function() { $.ajax({ url: "http://jobs.kent.k12.wa.us/browsejobs.aspx?type=2", dataType: "html", success: function ( response ) { OpenPositions.classifiedFilter(response); } }); }, classifiedFilter: function( response ) { var Classified = { Paraeducator: [], Clerical: [], NonRep: [], Maintenance: [], ClaSubstitute: [], Coaching: [] }, response = $(response).find("table tbody tr td").html(); $(response).find("span:contains(Classified Positions)").remove(); $(response).find("font:contains(Open to all)").parent().parent().remove(); //filter each span title and classify sub items $(response).find("span").parents("tr").each( function() { //Find categories and separate by class var rowtext = $(this).find("span").text(), position = ""; if (rowtext === "Paraeducator") { position = "Paraeducator"; $(this).nextAll("tr").addClass("Paraeducator"); } if (rowtext === "Clerical") { position = "Clerical"; $(this).nextAll("tr").addClass("Clerical"); } if (rowtext === "Non-Rep") { position = "NonRep"; $(this).nextAll("tr").addClass("NonRep"); } if (rowtext === "Maintenance") { position = "Maintenance"; $(this).nextAll("tr").addClass("Maintenance"); } if (rowtext === "Substitute") { position = "ClaSubstitute"; $(this).nextAll("tr").addClass("ClaSubstitute"); } if (rowtext === "Coaching") { position = "Coaching"; $(this).nextAll("tr").addClass("Coaching"); } //Push content into Classified ((position === "Paraeducator") ? $(this).nextUntil(".Clerical").each( function() { Classified.Paraeducator.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : ((position === "Clerical") ? $(this).nextUntil(".NonRep").each( function() { Classified.Clerical.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : ((position === "NonRep") ? $(this).nextUntil(".Maintenance").each( function() { Classified.NonRep.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : ((position === "Maintenance") ? $(this).nextUntil(".ClaSubstitute").each( function() { Classified.Maintenance.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : ((position === "ClaSubstitute") ? $(this).nextUntil(".Coaching").each( function() { Classified.ClaSubstitute.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : ((position === "Coaching") ? $(this).nextAll().each( function() { Classified.Coaching.push( $.trim( "&lt;tr&gt;" + $(this).html() + "&lt;/tr&gt;" ) ); }) : [] ) ) ) ) ) ); }); this.classifiedClean( Classified ); }, classifiedClean: function( Classified ) { //remove title from array Classified.Paraeducator.pop(); Classified.Clerical.pop(); Classified.NonRep.pop(); Classified.Maintenance.pop(); Classified.ClaSubstitute.pop(); Classified.Paraeducator = Classified.Paraeducator.join(""); Classified.Clerical = Classified.Clerical.join(""); Classified.NonRep = Classified.NonRep.join(""); Classified.Maintenance = Classified.Maintenance.join(""); Classified.ClaSubstitute = Classified.ClaSubstitute.join(""); Classified.Coaching = Classified.Coaching.join(""); $.extend(this.positionsJoin, Classified); $.publish('Done/Classified'); } }; </code></pre> <p><strong>Final template where response is inserted</strong></p> <pre><code>&lt;div id="certificated"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#Elementary"&gt;Elementary Certificated&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#MiddleSchool"&gt;Middle School Certificated&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#HighSchool"&gt;High School Certificated&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#K12"&gt;K-12 Certificated&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#Substitute"&gt;Substitute&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#ESA"&gt;Certificated - ESA&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id='Elementary'&gt; &lt;table&gt; {{{Elementary}}} &lt;/table&gt; &lt;/div&gt; &lt;div id='MiddleSchool'&gt; &lt;table&gt; {{{MiddleSchool}}} &lt;/table&gt; &lt;/div&gt; &lt;div id='HighSchool'&gt; &lt;table&gt; {{{HighSchool}}} &lt;/table&gt; &lt;/div&gt; &lt;div id='K12'&gt; &lt;table&gt; {{{K12}}} &lt;/table&gt; &lt;/div&gt; &lt;div id='Substitute'&gt; &lt;table&gt; {{{Substitute}}} &lt;/table&gt; &lt;/div&gt; &lt;div id='ESA'&gt; &lt;table&gt; {{{ESA}}} &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Literal HTML Ajax response</strong></p> <pre><code> &lt;table cellpadding="0" cellspacing="0"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;!-- Body Text --&gt; &lt;span id="isHeadType"&gt;&lt;h2&gt;Certificated Positions&lt;/h2&gt;&lt;/span&gt; &lt;table border="0" cellspacing="0" cellpadding="0" style="MARGIN-TOP: 10px;"&gt; &lt;tr&gt; &lt;td&gt; &lt;font class="HeadTitle"&gt;External Positions: Open to all applicants.&lt;/font&gt;&lt;br&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl1_BargainGroup" class="BodyText"&gt;Elementary Certificated&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3278&amp;type=1&amp;int=External'&gt;Elementary Itinerant General Music Teacher .084 FTE - IS1205&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;Springbrook Elementary School&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule (DOE &amp; Credits)&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; 2:15-3:30&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;10/17/2012&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3628&amp;type=1&amp;int=External'&gt;Instructional Support Team Specialist – ELL - SS1209&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;Student &amp; Family Support Services&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;Salary Schedule (DOE &amp; Credits)&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; TBD&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;1/28/2013&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl2_BargainGroup" class="BodyText"&gt;Middle School Certificated&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3585&amp;type=1&amp;int=External'&gt;Secondary Teachers - 2013SecPool&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;TBD&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule DOE &amp; Credits&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; &lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;1/9/2013&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl3_BargainGroup" class="BodyText"&gt;High School Certificated&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3579&amp;type=1&amp;int=External'&gt;Alternative Teacher- .2 FTE - SO1211&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;iGrad&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule (DOE &amp; Credits)&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; 8:15AM-4:45PM&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;1/9/2013&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3580&amp;type=1&amp;int=External'&gt;Alternative Teacher- .1 FTE - SO1210&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;iGrad&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule (DOE &amp; Credits)&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; 5:15pm-8:45PM&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;1/9/2013&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl4_BargainGroup" class="BodyText"&gt;K-12 Certificated&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=3586&amp;type=1&amp;int=External'&gt;Special Education Teachers - 2013spedpool&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;TBD&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule DOE &amp; Credits&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; &lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;1/9/2013&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl5_BargainGroup" class="BodyText"&gt;Substitute&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=239&amp;type=1&amp;int=External'&gt;Guest Teacher - HRSubTCR&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;All district schools&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;$133.35 full day/$76.20 half day&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; &lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;7/26/2011&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td height="20" nowrap="nowrap"&gt; &lt;i&gt;&lt;span id="ExternalJobs__ctl6_BargainGroup" class="BodyText"&gt;Certificated - ESA&lt;/span&gt;&lt;/i&gt; &lt;br/&gt;&lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=2323&amp;type=1&amp;int=External'&gt;Speech Language Pathologist Intern - SLPIntern&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;Inclusive Education&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;Stipend&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; TBD&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;2/16/2012&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td nowrap="nowrap" style="padding-left:20px;" class="BodyText"&gt; &lt;b&gt;&lt;a href='jobs.aspx?id=2956&amp;type=1&amp;int=External'&gt;Occupational Therapist - 2012-13OTPool&lt;/a&gt;&lt;/b&gt; &lt;br/&gt; &lt;b&gt;Location:&lt;/b&gt;Inclusive Education&lt;br/&gt; &lt;b&gt;Contract:&lt;/b&gt;State Salary Schedule DOE &amp; Credits&lt;br/&gt; &lt;b&gt;Anticipated Hours:&lt;/b&gt; TBD&lt;br /&gt; &lt;b&gt;Posting Date:&lt;/b&gt;&amp;nbsp;9/5/2012&amp;nbsp; &lt;b&gt;Closing date:&lt;/b&gt;&amp;nbsp;Until Filled &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;span id="Message" class="BodyText" style="font-weight:bold;"&gt;&lt;/span&gt; &lt;br/&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[]
[ { "body": "<p>In my opinion, you are trying to solve the wrong issue here. If you want to optimize this entire routine, I have to say you start optimizing at the response.</p>\n\n<p>AJAX is made for a reason, and it was meant to load pages without page loads, or having to wait a lot. The JSON format was also created to aid AJAX and reduce the size of the response, thus faster AJAX.</p>\n\n<p>In your case, you should change your response from the server, from marked-up data to JSON data. An excerpt of the above can be represented in this simple JSON:</p>\n\n<pre><code>[\n {\n \"id\":\"ExternalJobs__ctl1_BargainGroup\",\n \"level\":\"Elementary\",\n \"positions\":[\n {\n \"id\":3278,\n \"position\":\"Elementary Itinerant General Music Teacher .084 FTE - IS1205\",\n \"location\":\"Springbrook Elementary School\",\n \"contract\":\"State Salary Schedule (DOE &amp; Credits)\",\n \"hours\":\"2:15-3:30\",\n \"posted\":\"2012-10-17\",\n \"closing\":\"Until Filled\"\n },{\n \"id\":3628,\n \"position\":\"Instructional Support Team Specialist – ELL - SS1209\",\n \"location\":\"Student &amp; Family Support Services\",\n \"contract\":\"Salary Schedule (DOE &amp; Credits)\",\n \"hours\":\"TBD\",\n \"posted\":\"2013-01-28\",\n \"closing\":\"Until Filled\"\n }\n ]\n },{\n //Middle School Certificated\n },{\n //High School Certificated\n },{\n //and so on...\n }\n]\n</code></pre>\n\n<p>As you can see, tons of markup were removed, thus lightening the load. This also makes it easier to manipulate since you won't be doing pseudo-DOM tasks with jQuery. In this case, the response is already an object to start with. With a little or no manipulation of the return data, depending on how it's structured, you can directly plop it in to the <code>Classified</code> object directly or to the template!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T15:16:48.027", "Id": "34160", "Score": "0", "body": "I would use JSON (JSONP actually for cors) but this content is coming from a 3rd party app which doesn't offer support for that. I could probably convert all the content myself but wouldn't that be almost the same length-wise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:29:10.817", "Id": "34203", "Score": "0", "body": "@JonnySooter what method are you using to get this HTML? If you are using a proxy server to fetch this, it would be better that your proxy do the conversion so that client-side JS processing won't be that heavy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T15:18:43.170", "Id": "34231", "Score": "0", "body": "Should have posted that one earlier. I've updated the code with the ajax setup function. This method and etc. will apply to all three of the requests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T11:14:36.417", "Id": "34278", "Score": "0", "body": "@JonnySooter so CORS is an option here? If so, I'll be updating my answer in a while." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T15:12:34.920", "Id": "34320", "Score": "1", "body": "YES! It is, as you can see in the setup function XD" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T08:47:17.190", "Id": "21217", "ParentId": "21185", "Score": "1" } } ]
{ "AcceptedAnswerId": "21217", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:06:05.940", "Id": "21185", "Score": "3", "Tags": [ "javascript", "jquery", "html", "ajax" ], "Title": "Filtering and Sorting jQuery Ajax response" }
21185
<p>I'm trying to create daily, monthly and weekly SQL Query report to our services time we spent int task and total billing time just want to see if I'm on right track </p> <pre><code>GO --Daily SELECT SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName FROM billingsTimes INNER JOIN aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN Tasks ON billingsTimes.taskID = Tasks.taskID WHERE (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e') AND (CONVERT(DATE, billingsTimes.dateOfService) = '01/29/2013') GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(D, dateOfService) GO --Weekly SELECT SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName,DATEPART(WEEK, dateOfService)AS weekNumber FROM billingsTimes INNER JOIN aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN Tasks ON billingsTimes.taskID = Tasks.taskID WHERE (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e') GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(WEEK, dateOfService), DATEPART(WEEK, dateOfService) GO --Monthly SELECT SUM(billingsTimes.actualTotalTime) AS TotalTime, Tasks.taskName, billableType.billableTypeName,DATEPART(MONTH, dateOfService)AS monthNumber FROM billingsTimes INNER JOIN aspnet_Users ON billingsTimes.userID = aspnet_Users.UserId INNER JOIN billableType ON billingsTimes.billableTypeID = billableType.rank INNER JOIN Tasks ON billingsTimes.taskID = Tasks.taskID WHERE (billingsTimes.taskID = 10045) AND (aspnet_Users.UserId = '178db2a8-be1d-48e0-9ebc-f64f7b1ff63e') GROUP BY billingsTimes.billableTypeID, Tasks.taskName, billableType.billableTypeName,DATEPART(MONTH, dateOfService) GO </code></pre>
[]
[ { "body": "<p>Somewhat hard to judge without any idea of the schema, but here are a few observations:</p>\n\n<ol>\n<li><p>Join condition on billableType table is questionable: why comparing an ID to a rank in <code>INNER JOIN billableType ON billingsTimes.billableTypeID = billableType.rank</code>?</p></li>\n<li><p>Try to limit <code>GROUP BY</code> to the columns that will become sort of 'logical key' of your result set. E.g. it seems the query is limited to a single task at a time (<code>billingTimes.taskID = ###</code>). Use <code>max(taskName) as taskName</code> in your select list and exclude <code>taskName</code> from the group by clause.</p></li>\n<li><p>There's no need for <code>datepart(D, dateOfService)</code> in <code>GROUP BY</code>: the query is already restricted to a single day.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T15:46:24.447", "Id": "35005", "Score": "0", "body": "Hello Pavel, it seems that this is your first answer on Code Review. Thank you! It's an useful answer. I also 1/ edited it a bit to show you how to format code 2/ tried to make your observations clearer. Hope that helps!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T15:06:59.327", "Id": "22779", "ParentId": "21191", "Score": "3" } } ]
{ "AcceptedAnswerId": "22779", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:53:43.770", "Id": "21191", "Score": "0", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Daily, Weekly, Monthly Individual Tech time in task Repoert" }
21191
<p>I wanted an elegant way to implement memoizing. Here is what I came up with:</p> <pre><code>function memoize(fn) { var cache = new WeakMap(); return function() { if (!cache[arguments]) { cache[arguments] = fn.call(this, arguments); } return cache[arguments]; } } </code></pre> <p>It's quite nice, but the WeakMap is not well supported. Is there a better, yet clean way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-19T10:56:48.450", "Id": "204950", "Score": "0", "body": "You should use `fn.apply` instead of `fn.call` if you want to use the original arguments." } ]
[ { "body": "<p>I just thought about this:</p>\n\n<pre><code>function memoize(fn) {\n var cache = {};\n return function() {\n var args = Array.prototype.slice.call(arguments).toString();\n if (!cache[args]) {\n cache[args] = fn.call(this, arguments);\n }\n return cache[args];\n }\n}\n</code></pre>\n\n<p>It's very cross-browser. I can't think of any browser not supporting this.</p>\n\n<p>But it <em>does</em> feel kind of ugly. It's still the best I can think of though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:06:23.373", "Id": "34016", "Score": "0", "body": "This isn't equivalent. There can be collisions. For example, [\"a,b\"] and [\"a\", \"b] (at least my understanding of Array.toString -- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/toString)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:08:39.140", "Id": "34017", "Score": "0", "body": "Indeed. Then I'm lost :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T00:21:29.450", "Id": "108614", "Score": "0", "body": "JSON stringifying would probably be wiser" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T18:01:26.620", "Id": "21193", "ParentId": "21192", "Score": "0" } }, { "body": "<blockquote>\n <p>Is there a better, yet clean way to do this?</p>\n</blockquote>\n\n<p>\"Better\" and \"clean\" are both debatable. There's <em>a</em> way to do it, using JSON serialization.</p>\n\n<p>But speaking to your current code, I'm not sure that maps would the trick. Every call to the function will result in a distinct <code>arguments</code> object (even if the individual arguments are the same), so I think you'd get \"duplicate\" keys. At least I imagine so. I don't have an up-to-date browser on this machine, so I can't test, and I haven't played enough with Map/WeakMap to know off-hand.</p>\n\n<p>Besides, you need to use <code>has()</code> and <code>set()</code>; using <code>[...]</code> will, I believe, just set a regular property (which implies string coercion of the key).</p>\n\n<p>Now, for alternatives, you could do something like what <a href=\"http://addyosmani.com/blog/faster-javascript-memoization/\" rel=\"nofollow\">Addy Osmani's proposes</a> (the entire article is worth a read). The basic idea is to use <code>JSON.stringify()</code> to serialize the arguments in a more robust way than <code>toString</code>.</p>\n\n<p>I'll include it here, as-is:</p>\n\n<blockquote>\n<pre><code>/*\n* memoize.js\n* by @philogb and @addyosmani\n* with further optimizations by @mathias\n* and @DmitryBaranovsk\n* perf tests: http://bit.ly/q3zpG3\n* Released under an MIT license.\n*/\nfunction memoize( fn ) {\n return function () {\n var args = Array.prototype.slice.call(arguments),\n hash = \"\",\n i = args.length;\n currentArg = null;\n while (i--) {\n currentArg = args[i];\n hash += (currentArg === Object(currentArg)) ? \n JSON.stringify(currentArg) : currentArg;\n fn.memoize || (fn.memoize = {});\n }\n return (hash in fn.memoize) ? fn.memoize[hash] : \n fn.memoize[hash] = fn.apply(this, args);\n };\n}\n</code></pre>\n \n <p>Source: <a href=\"http://addyosmani.com/blog/faster-javascript-memoization/\" rel=\"nofollow\">Faster JavaScript Memoization For Improved Application Performance</a></p>\n</blockquote>\n\n<p>It's a pretty neat solution, though obviously not as clean as just using <code>WeakMap</code> (if indeed that would even work).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T00:55:41.537", "Id": "60095", "ParentId": "21192", "Score": "1" } }, { "body": "<p>I use this</p>\n\n<pre><code>function memoizeFirst(fn) {\n const cache = new WeakMap();\n return function(arg) {\n if (!cache.has(arg)) {\n cache.set(arg, fn(arg));\n }\n return cache.get(arg);\n };\n}\n</code></pre>\n\n<p>this function will memoize the result of the function you pass and cache it. The cache will vary on the first argument, and only on the first argument. Do not use this function if you are planning on passing more then one argument to it! Do use this function if you want to pass an object as the first argument.</p>\n\n<p>I use this function for building (temporary) indexes based on an immutable state. Example (the groupBy, where methods come from IxJS):</p>\n\n<pre><code>const getParentObjectIndex = memoizeFirst(state =&gt; state.objectSource &amp;&amp; state.objectSource.\n where(objectItem =&gt; objectItem.parentObject).\n groupBy(objectItem =&gt; objectItem.parentObject).\n reduce(function(map, group) {\n map[group.key] = group.\n orderBy(item =&gt; item.position).\n toArray();\n return map;\n }, {})\n);\n</code></pre>\n\n<p>Because the state is immutable, it will not change. The only way to change the state is to create a new one. So everytime something changes, we have a new state. That makes is an excellent cache key!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-19T11:16:57.490", "Id": "111187", "ParentId": "21192", "Score": "4" } }, { "body": "<p>Here you find a WeakMap solution for multiple arguments: memoize in <a href=\"https://github.com/Dans-labs/dariah/blob/master/client/src/js/lib/utils.js\" rel=\"nofollow noreferrer\">https://github.com/Dans-labs/dariah/blob/master/client/src/js/lib/utils.js</a></p>\n\n<p>For cases where your function deals with large, immutable objects, stringify is useless (it does not improve performance). Then WeakMap is your friend, because you can use the objects themselves as keys, without preventing them to be garbage collected. But you need a trick to generate a key for multiple arguments. The link above points to the solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-08T19:52:59.093", "Id": "165292", "ParentId": "21192", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:57:00.133", "Id": "21192", "Score": "7", "Tags": [ "javascript", "cache", "memoization" ], "Title": "Elegant memoizing" }
21192
<p>My intent is to use Bash functions defined in <code>functions.sh</code> in a C program. I am doing this so that I don't have to rewrite the Bash functionality again in C. I want to use one common library for functions I need. Here is my C code and <code>functions.sh</code>.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;sys/wait.h&gt; #include &lt;stdio.h&gt; void shellCall(char * command) { int status, commandexitcode=0; if(command == NULL) { printf("NULL command string sent\n"); exit(1); } status = system(command); if(status == -1) { printf("Error during call, value %d\n", status); exit(1); } if (WIFEXITED(status)) { commandexitcode = WEXITSTATUS(status); if (commandexitcode != 0) { printf("non zero exit code: %d\n", commandexitcode); exit(1); } } else if (WIFSIGNALED(status)) { printf("killed by signal: %d\n", WTERMSIG(status)); exit(1); } else if (WIFSTOPPED(status)) { printf("stopped by signal: %d\n", WSTOPSIG(status)); exit(1); } else if (WIFCONTINUED(status)) { printf("continued, unexpected..bailing\n"); exit(1); } } int main(int argc,char **argv) { char command[100]; //command int i = 0; for (i = 1 ; i &lt;= 10 ; i++) { sprintf( command, "source $PWD/functions.sh ; i=%d ; myfunc %d", i,i ); shellCall(command); } } </code></pre> <p>Please note that here I have only shown a very simple example of the way I am using functions in functions.sh. In reality functions.sh has many functions, some of which implement decent logic.</p> <hr> <pre><code>#!/bin/sh # functions.sh myfunc() { echo "I received $1" } </code></pre> <p>Question: I need feedback on the following aspects.</p> <ol> <li>Is it a bad programming practice (something that will make experienced and senior developers mad when they see this) to use <code>system()</code> calls to call functions in <code>functions.sh</code> as I have done?</li> <li>What are the reasons (technical and other) for which it is considered a bad programming practice?</li> <li>What changes should I make to my C code so that experienced and senior developers will find it acceptable?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T01:32:58.863", "Id": "34037", "Score": "0", "body": "Could you either post the real `functions.sh`, or remove that from your post (as it is extraneous if it doesn't have the actual code)?" } ]
[ { "body": "<h3>Comments</h3>\n\n<p>Because your question is marked <a href=\"/questions/tagged/clean-code\" class=\"post-tag\" title=\"show questions tagged 'clean-code'\" rel=\"tag\">clean-code</a> and I see that you have commented your declaration of the variable <code>command</code> with the comment <code>command</code>, let me make a note about comments. There are good comments, and bad comments; in my experience, a very high numbers of comments written by many developers are bad. For a thoughtful exposition of comments, see Bob Martin's chapter on them in <em>Clean Code</em> (an invaluable book). In short, if you are going to insert a comment, make sure it actually <em>adds</em> something. Then, make sure you can't add that information into the code itself, by renaming variables, etc. Then, if you can't, carefully craft your comment.</p>\n\n<h3>Functions</h3>\n\n<p>Because you are asking about the general cleanliness of your code, let me advice that you use smaller functions. There are many benefits to small functions, which I will not get into here; many of the best software books discuss this, including Martin's book, mentioned above.</p>\n\n<h3>Magic Numbers</h3>\n\n<p>Replace numbers like <code>-1</code> and <code>10</code> in your code with a constant that has an explicit name explaining these numbers. This increases the readability and maintainability of your code.</p>\n\n<h3>Stdout and Stderr</h3>\n\n<p>In Unix, C and C-based languages, you have three streams attached to your process by default: standard in, standard out, and standard error. Don't write error messages to standard out&mdash;write them to standard error.</p>\n\n<h3>Calling Bash from C</h3>\n\n<p>Consider that calling Bash...</p>\n\n<ul>\n<li>...makes your code much, <strong>much less portable</strong>, by tying it down to a system with Unix utilities&mdash;and more specifically than that, one that has Bash&mdash;and more than that, one that has a version of Bash which supports all the features you decide to use.</li>\n<li>...makes your code <strong>harder to test</strong>\n<ul>\n<li>by creating <strong>external dependencies</strong>. If you are not familiar with the problem of dependencies, try reading up on it. Roy Osherove, in <em>The Art of Unit Testing</em>, and Michael Feathers, in <em>Working Effectively with Legacy Code</em>, both have much discussion of it.</li>\n<li>Bash scripts do not have the debugging tools for than that C has (Valgrind, GDB, IDEs, etc).</li>\n</ul></li>\n<li>...makes your code <strong>harder to read</strong>:\n<ul>\n<li>by <strong>lessening its homogeneity</strong></li>\n<li>by making the user move around move between various source files</li>\n<li>by lessening your IDE's ability to aid you in traversing the code, since some of the calls are embedded in strings as calls to an external</li>\n<li>because Bash is often even harder to read than C</li>\n</ul></li>\n<li>...makes your code <strong>harder to maintain</strong>, because of being harder to test and read.</li>\n<li>...is <strong>unnecessary</strong>, because under the covers Bash is just calling the Unix C API anyway.</li>\n<li>...is <strong>artistically distasteful</strong>&mdash; it smells like a kludge.</li>\n<li>...<strong>adds a failure point</strong> to your code. Just look how many possible error messages you output, and then abort!</li>\n<li>...presumably, this will also be a <strong>performance hit</strong> because of the overhead of running Bash.</li>\n</ul>\n\n<p>I would strongly advise you not to use sys calls unless you are calling a very complex external application that would be difficult to reproduce in your C code in reasonable time and doesn't have a C API (and serious applications are not generally written in Bash) or you are performing an extremely low-level function that there is no C API for. Work for homogeneity&mdash;it's much cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T01:53:37.030", "Id": "34038", "Score": "0", "body": "Anything on the technical drawbacks?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T02:04:21.097", "Id": "34039", "Score": "0", "body": "Testability, portability and failure points (just added) are technological metrics." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T01:44:37.547", "Id": "21210", "ParentId": "21197", "Score": "5" } }, { "body": "<p>I think objections to using <code>system</code> are often about the security holes it opens up. The call is generally frowned on. <code>system</code> spawns a copy of the shell (presumably your default shell) and this shell runs the script, using the search path to find it etc. I imagine it is because of this intermediate process and the possibility for interference with it or the command it runs that the security problems arise, but I'm not the right person to give you details. Perhaps ask on Stack Overflow, without the code example, just a general question about the desirability of <code>system</code> for your purposes.</p>\n\n<p>As for your code, it is a lot better now than when first posted. A few points though:</p>\n\n<ul>\n<li>the parameter to <code>shellCall</code> should be const</li>\n<li><code>commandexitcode</code> is verbose and could be declared closer to it point of use</li>\n<li>possible buffer overflow printing <code>command</code> in <code>main</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T18:35:46.417", "Id": "34080", "Score": "0", "body": "Thanks for talking about the technical aspects. I was looking for some feedback on that front." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:37:52.443", "Id": "21225", "ParentId": "21197", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:55:23.263", "Id": "21197", "Score": "4", "Tags": [ "c", "bash", "linux" ], "Title": "Need some advice and feedback on my C code calling Bash functions" }
21197
<p>For the past few days I've been working on a AES-128 encrypt/decipher class. I needed something very scaled down from <code>Cryptolib</code> so that I didn't have to constantly import the .lib file on all my programming computers (work, home, laptop1, laptop2). I've decided that since I will only every use AES-128 for one my programs (related to NFC desfire stuff), I wanted to make a small and easily portable class.</p> <p>I have the following up for review. I asked a question at Stack Overflow when I was having a issue and one of the members mentioned that I had memory leaks. I'm a C#/Java programmer at heart and C++ is only a few months old in me, so sorry about mistakes like that.</p> <p>I don't have room to put the <code>Galois</code> files. I will, however, just put the mockup of it.</p> <p><strong>Aes128.h</strong></p> <pre><code>#pragma once #include "ByteUtil.h" #include "Galois.h" class AES128 { public: void SetKey(const BYTE* key); void SetIV(const BYTE* iv); void EncryptData(BYTE** outBlock, const BYTE* inBlock, size_t length); void DecryptData(BYTE** outBlock, const BYTE* inBlock, size_t length); private: void EncryptBlock(BYTE* outBlock, const BYTE* inBlock, const BYTE* cipherBlock); void DecryptBlock(BYTE* outBlock, const BYTE* inBlock, const BYTE* cipherBlock); BYTE* Key; BYTE* IV; }; </code></pre> <p><strong>Aes128.cpp</strong></p> <pre><code>#include "stdafx.h" #include "AES128.h" /* Public Methods */ void AES128::SetKey(const BYTE* key) { Key = (BYTE*)malloc(16); memcpy(Key, key, 16); } void AES128::SetIV(const BYTE* iv) { IV = (BYTE*)malloc(16); memcpy(IV, iv, 16); } void AES128::EncryptData(BYTE** outBlock, const BYTE* inBlock, size_t length) { float blockSize = (float)(length/16); blockSize = ceilf(blockSize); size_t newLength = (size_t)(blockSize*16); BYTE* temp = (BYTE*)malloc(newLength); BYTE* padd = (BYTE*)malloc(newLength); memset(temp, 0, newLength); memcpy(padd, inBlock, length); EncryptBlock(temp, padd, IV); for (int i=1; i&lt;blockSize; i++) { EncryptBlock(&amp;temp[i*16], &amp;padd[i*16], &amp;temp[(i-1)*16]); } *outBlock = (BYTE*)malloc(newLength); memcpy((*outBlock), temp, newLength); } void AES128::DecryptData(BYTE** outBlock, const BYTE* inBlock, size_t length) { float blockSize = (float)(length/16); blockSize = ceilf(blockSize); size_t newLength = (size_t)(blockSize*16); BYTE* temp = (BYTE*)malloc(newLength); BYTE* padd = (BYTE*)malloc(newLength); memset(temp, 0, newLength); memcpy(padd, inBlock, length); DecryptBlock(temp, padd, IV); for (int i=1; i&lt;blockSize; i++) { DecryptBlock(&amp;temp[i*16], &amp;padd[i*16], &amp;temp[(i-1)*16]); } *outBlock = (BYTE*)malloc(newLength); memcpy((*outBlock), temp, newLength); } /* Private Methods */ void AES128::EncryptBlock(BYTE* outBlock, const BYTE* inBlock, const BYTE* cipherBlock) { BYTE temp[16] = {0x00}; Galois::XorBlock(temp, inBlock); Galois::XorBlock(temp, cipherBlock); BYTE expandedKey[176] = {0x00}; memcpy(expandedKey, Key, 16); Galois::expand_key(expandedKey); Galois::XorBlock(temp, expandedKey); for(int i=16; i&lt;160; i+=16) { Galois::DoRound(temp, &amp;expandedKey[i]); } Galois::SubBytes(temp); Galois::ShiftRows(temp); Galois::XorBlock(temp, &amp;expandedKey[160]); memcpy(outBlock, temp, 16); } void AES128::DecryptBlock(BYTE* outBlock, const BYTE* inBlock, const BYTE* cipherBlock) { BYTE temp[16] = {0x00}; Galois::XorBlock(temp, inBlock); BYTE expandedKey[176] = {0x00}; BYTE* invExpandedKey; memcpy(expandedKey, Key, 16); Galois::expand_key(expandedKey); Galois::InvertExpandedKey(&amp;invExpandedKey, expandedKey); Galois::XorBlock(temp, invExpandedKey); Galois::InvShiftRows(temp); Galois::InvSubBytes(temp); for(int i=0x10; i&lt;0xA0; i+=0x10) //change i&lt;0xA0 { Galois::InvDoRound(temp, &amp;invExpandedKey[i]); } Galois::XorBlock(temp, &amp;invExpandedKey[160]); Galois::XorBlock(temp, cipherBlock); memcpy(outBlock, temp, 16); } </code></pre> <p><strong>Galois.h</strong></p> <pre><code>class Galois { private: static BYTE gadd(const BYTE a, const BYTE b); static BYTE gmul(const BYTE a, const BYTE b); static BYTE gmul_Inverse(const BYTE in); static void gmul_mix_column(BYTE* row); static void inv_mix_column(BYTE *r); //AES Key Expansion Functions static void RotWord(BYTE* in); static BYTE Rcon(BYTE in); static void schedule_core(BYTE* in, BYTE i); static void expand_key(BYTE* in); static void InvertExpandedKey(BYTE** out, const BYTE* in); static void SubBytes(BYTE* dest); static void InvSubBytes(BYTE* dest); static void ShiftRows(BYTE* dest); static void InvShiftRows(BYTE* dest); static void MixColumns(BYTE* row); static void InvMixColumns(BYTE* row); static void xorRow(BYTE* row1, const BYTE* row2); static void XorBlock(BYTE* block1, const BYTE* block2); static void SubWord(BYTE* in); static void SubBytes(BYTE* dest); static void InvSubWord(BYTE* in); static void InvSubBytes(BYTE* dest); public: static void DoRound(BYTE* dest, const BYTE* roundKey); static void InvDoRound(BYTE* dest, const BYTE* roundKey); }; </code></pre> <p>I plan on refactoring <code>Galois</code> a bit to separate some of the Rijandel methods and then just use the math from <code>Galois</code>. That should clean it up nicely. So how bad is it?</p>
[]
[ { "body": "<p>Before I say anything else, I feel obligated to say that you should use the library. Writing bug-free Crypto code is hard and dangerous. The rule for Crypto code is generally that you shouldn't write it unless you are an expert (and even then, you want a LOT of eyes on it to check it). If this code is going to be used in anything remotely serious, use the library!</p>\n\n<p>With that caveat, there are a few problems with your code.</p>\n\n<h2>Memory Leaks</h2>\n\n<p>You dynamically allocate both:</p>\n\n<pre><code>Key = (BYTE*)malloc(16);\n</code></pre>\n\n<p>and </p>\n\n<pre><code>IV = (BYTE*)malloc(16);\n</code></pre>\n\n<p>Which are both never <code>free</code>d. Firstly, you should prefer <code>new</code> to <code>malloc</code> in C++ code. You also need to remember the rule that whatever you <code>malloc/new</code>, you need to <code>free/delete</code> (unless you're passing a pointer back to the user, in which case it is up to them to do this. This should be infrequent, however). This is generally done in the destructor:</p>\n\n<pre><code>AES128::~AES128()\n{\n if(Key != nullptr)\n free(Key);\n if(IV != nullptr)\n free(IV);\n}\n</code></pre>\n\n<p>With <code>delete</code>, the NULL checks are implicit and therefore redundant.</p>\n\n<p>However, in this case, there's not really any reason to use the free store, you should likely just automatically allocate both of these:</p>\n\n<pre><code>private:\n static const std::size_t k_blockSize = 16;\n BYTE Key[k_blockSize];\n BYTE IV[k_blockSize];\n</code></pre>\n\n<p>You also pass in a <code>BYTE *</code> which you <code>memcpy</code> from, but always only copy 16 bytes, which should be a named constant. I'd also prefer <code>std::copy</code> over <code>memcpy</code>. I'd probably write this like so:</p>\n\n<pre><code>#include &lt;algorithm&gt; //For std::copy\n\nclass AES128\n{\npublic:\n void SetKey(const BYTE* key);\n void SetIV(const BYTE* iv);\n //Other public functions\nprivate:\n //Private functions\n static const std::size_t k_blockSize = 16;\n BYTE Key[k_blockSize];\n BYTE IV[k_blockSize];\n};\n\nvoid AES128::SetKey(const BYTE* key)\n{\n std::copy(key, key + k_blockSize, Key);\n}\n\nvoid AES128::SetIV(const BYTE* iv)\n{\n std::copy(iv, iv + k_blockSize, IV);\n}\n</code></pre>\n\n<h2>Namespaces</h2>\n\n<p>Firstly, your code seems like it won't compile currently. In <code>Aes128.cpp</code>, you're utilizing things like <code>Galois::XorBlock</code> which is marked as <code>private</code>. Perhaps these functions you're using are meant to be <code>public</code>?</p>\n\n<p>Now, while everything in Java and C# must be a class, C++ has no such restriction. There is no reason to make a class with all <code>static</code> members - they should be free functions within a <code>namespace</code> instead. If you want to make them <code>private</code>, you can put them in an unnamed namespace in a <code>.cpp</code> file. So your <code>Galois</code> class can be rewritten like so:</p>\n\n<p>In <code>Galois.h</code>:</p>\n\n<pre><code>namespace Galois\n{\n void DoRound(BYTE* dest, const BYTE* roundKey);\n void InvDoRound(BYTE* dest, const BYTE* roundKey);\n}\n</code></pre>\n\n<p>In your <code>Galois.cpp</code>:</p>\n\n<pre><code>#include \"Galois.h\"\n\nnamespace \n{\n BYTE gadd(const BYTE a, const BYTE b) { ... }\n BYTE gmul(const BYTE a, const BYTE b) { ... }\n BYTE gmul_Inverse(const BYTE in) { ... }\n void gmul_mix_column(BYTE* row) { ... }\n void inv_mix_column(BYTE *r) { ... }\n //AES Key Expansion Functions\n void RotWord(BYTE* in) { ... }\n BYTE Rcon(BYTE in) { ... }\n void schedule_core(BYTE* in, BYTE i) { ... }\n void expand_key(BYTE* in) { ... }\n void InvertExpandedKey(BYTE** out, const BYTE* in) { ... }\n void SubBytes(BYTE* dest) { ... }\n void InvSubBytes(BYTE* dest) { ... }\n void ShiftRows(BYTE* dest) { ... }\n void InvShiftRows(BYTE* dest) { ... }\n\n void MixColumns(BYTE* row) { ... }\n void InvMixColumns(BYTE* row) { ... }\n void xorRow(BYTE* row1, const BYTE* row2) { ... }\n void XorBlock(BYTE* block1, const BYTE* block2) { ... }\n void SubWord(BYTE* in) { ... }\n void SubBytes(BYTE* dest) { ... }\n void InvSubWord(BYTE* in) { ... }\n void InvSubBytes(BYTE* dest) { ... }\n}\n\nvoid Galois::DoRound(BYTE* dest, const BYTE* roundKey) { ... }\nvoid Galois::InvDoRound(BYTE* dest, const BYTE* roundKey) { ... }\n</code></pre>\n\n<p>These are called similarly to how you have them now, for example, <code>Galois::DoRound</code> and so on. Note that the functions within the unnamed namespace in <code>Galois.cpp</code> won't be accessible outside of that file, which is exactly what you have now - as mentioned earlier, I'm not sure if this is what you want, as you're calling them from (non-internal) places. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:38:03.347", "Id": "34062", "Score": "0", "body": "thank you very much for your very thoughtful comments. This will most certainly help me. One thing that still gets me is the use of double pointers. The two places that I had this code in a library, which I was calling from a C# code (dumb idea it was...which i gave up on, and just used the C# to call a `TestLibrary` method in the library which ran over 600+ tests on it from nist.gov) so what I had posted was my attempt to copy it over to where it was going to live. You were very right about the private/public bit (it didn't compile) I'll try out what you have for me. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T04:51:11.430", "Id": "34094", "Score": "0", "body": "+1 for stressing reuse of a library instead of self implementing. As a learning exercise it's fine, but if at all possible use a trusted library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T21:33:43.923", "Id": "34114", "Score": "0", "body": "@JaredPaolin since you are the second one to mention using the library as apposed to making my own it impels me to ask why. if i have unit tests that prove that my method works from 2 different sources (Nist.gov and NXP) then why is it so wrong to make my own? In this case once i fix my memory leaks it will allow me to compile my program as a static library again instead of a shared library ( desired by me and my client). I'm very interested in your reason behind using the library, if you could please elaborate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T01:38:18.860", "Id": "34119", "Score": "2", "body": "@RobertSnyder I'm going to steal some words from Yacoset: \"Never write your own implementation of a well-known cipher.\nEven if the algorithm is a standard like AES, the algorithm is just a mathematical concept, meaning any given implementation could have weaknesses that come from things you never knew about your language, platform, or even the hardware (such as side-channel attacks). Somebody else has figured these things out already, such as the vendor or a dedicated third party.\"" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T04:41:09.407", "Id": "21215", "ParentId": "21200", "Score": "4" } } ]
{ "AcceptedAnswerId": "21215", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T20:17:29.367", "Id": "21200", "Score": "3", "Tags": [ "c++", "cryptography", "portability", "aes" ], "Title": "AES-128 encrypt/decipher class" }
21200
<p>I created a Letterpress solver that will take a string of letters and return a list of valid words that can be constructer with the provided letters. Not all letters need to be used in each word.</p> <p>This works by reading all words into a list named <code>dictionary</code>, transforming that list of words into a map, <code>letter-permutations</code>, keyed on ordered letters (as a list of characters) with values of vectors containing anagrams of the key letters.</p> <p>Then, calling <code>find-words</code> with a string of letters and a lower bound for word length, will find all distinct combinations of those letters with lengths from the lower bound to the size of the input string.</p> <p>The combinations are then <code>map</code>'d over <code>letter-permutations</code> to pull out all valid words that can be made.</p> <pre class="lang-clj prettyprint-override"><code>(def dictionary (clojure.string/split-lines (slurp "words"))) (def letter-permutations (group-by sort dictionary)) (defn get-combinations [letters lower-bound upper-bound] (mapcat #(distinct (combo/combinations letters %)) (range lower-bound (inc upper-bound)))) (defn find-words [letters lower-bound] (mapcat letter-permutations (get-combinations (sort letters) lower-bound (count letters)))) </code></pre> <p>This works extremely well for letter Strings up to 22 characters in length. But with 23 characters and upwards there is a drastic increase in the amount of time taken, when the response will come in bursts of words with long pauses (garbage collection?) between each batch.</p> <p>My testing for the above stats has been with the string "otxtzlsunowayzoyiwqyocetl" (which may of may not be my current board :)), but I've experienced the same same behaviour occurring for other strings as well.</p> <p>I'm happy to hear feedback on all of the code, but particularly for insights to the cause of the bottlenecks and suggestions of how I could improve this.</p> <p>Full source code can be seen on <a href="https://github.com/danmidwood/letterpress-solver/blob/eb47bead422d38717248cb61c6af9640c44f6691/src/letterpress/core.clj" rel="nofollow">Github</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T22:35:29.280", "Id": "62798", "Score": "0", "body": "I wondered about if distinct was lazy too.\nAlso, the dictionary is much smaller why not loop through that and see what can be made?" } ]
[ { "body": "<p>The <code>(distinct (combo/combinations letters %))</code> looks mighty troublesome to me. I don't know what the complexity function is for combinations offhand, but I'm going to guess it's got a factorial in it. Using distinct around it means that you will hold that entire set of combinations in memory. That's one of those things that works well for small numbers, then falls off a cliff. </p>\n\n<p>I also think this is one of those kinds of problems that can benefit significantly from memoization if structured properly. (Although memoization creates a cache in memory, so you might want to build your own with a customized cache to avoid blowing the heap. This is pretty easy with <a href=\"https://github.com/clojure/core.memoize\" rel=\"nofollow\">core.memoize</a>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T22:12:16.380", "Id": "34034", "Score": "0", "body": "The `distinct` usage did bother me, and that was before realising that it keeps all of the combinations in memory. It seemed like a good solution to combinations returning duplicates when a letters occur >1 time in the input. But I'm less sure of that now. Thanks for your input." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:32:49.023", "Id": "21203", "ParentId": "21201", "Score": "3" } } ]
{ "AcceptedAnswerId": "21203", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T20:50:08.400", "Id": "21201", "Score": "2", "Tags": [ "clojure", "combinatorics" ], "Title": "Discovering words from letters in Clojure (Letterpress Solver)" }
21201
<p>I'm learning Node. I'm working on a personal project that uses Node + Express + Node-MySQL + Generic-Pool (for MySQL pooling). I am new to the idea of module.exports and I'm still grokking it.</p> <p>The following code works. However I want to organize my code in a way that is logical and optimal, and MVCish. I am wondering if those of you who have done this before could take a look at the following and let me know if this is the "right" way to structure things. (Yes I know this going to depend a lot on the developer. But at least knowing if there are obvious problems in my approach would be helpful.)</p> <p>My folder structure looks roughly like this:</p> <pre><code>app.js routes/ models/ base/ </code></pre> <p>In my main <strong>app.js</strong> file I have...</p> <pre><code>var express = require( "express" ), mysql = require( "mysql" ), generic_pool = require ( "generic-pool" ), routes = require( "./routes" ); var app = module.exports = express(), pool = generic_pool.Pool({ name: "mysql", create: function( cb ) { var db = mysql.createConnection( require( "./config/db" ) ); db.connect(); cb( null, db ); }, destroy: function( db ) { db.end(); }, }); app.configure(function(){ app.set( "pool", pool ); ... }); routes( app ); app.listen(80, function()); </code></pre> <p>Here is an example route/ file <strong>"stuff.js"</strong></p> <pre><code>module.exports = function( app ){ var model = require( "../models/stuff" ); model.init( app ); app.get( "/stuff", function( req, res ){ model.get( function( result ){ res.json( result ); }); }); }; </code></pre> <p>Here is an example model/ file <strong>"stuff.js"</strong></p> <pre><code>var db; module.exports.init = function( app ){ db = require( "../base/db" ); db.init( app ); }; module.exports.get = function( cb ){ var sql = "SELECT * FROM stuff"; db.do( sql, false, cb ); }; </code></pre> <p>And here is the <strong>base/db</strong> file </p> <pre><code>var pool; module.exports.init = function( app ){ pool = app.get( "pool" ); }; module.exports.do = function( sql, params, cb ){ pool.acquire(function( err, db ){ if (err) { // ... } else { db.query( sql, function( err, result ) { if ( err ) { // ... } else if ( typeof cb === "function" ) { cb( result ); } }); } pool.release( "db" ); }); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T18:38:19.750", "Id": "62929", "Score": "1", "body": "what is the last line of `app.js` supposed to do? It lacks either an identifier to replace `function()`, or the actual body of the function (with the required arguments)" } ]
[ { "body": "<p>Your code looks fine.</p>\n\n<p>However, you are not showing us much to review, definitely come back when there is more to review.</p>\n\n<p>Some minor comments:</p>\n\n<ul>\n<li>Having your db connection config through ./config/db is good</li>\n<li>You probably want to throw an exception if <code>( typeof cb !== \"function\" )</code> instead of silently ignoring that</li>\n<li>The base/db code nests 4 levels of callback, you should look into queue management libraries for node.js</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:09:24.003", "Id": "39889", "ParentId": "21202", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:01:27.497", "Id": "21202", "Score": "7", "Tags": [ "javascript", "beginner", "mvc", "node.js" ], "Title": "node.js + Express code critique" }
21202
<p>How to get rid of that duplicaiton in <code>if</code> conditional?</p> <pre><code>def set_caption(result) if result.respond_to?(:app_name) content_tag(:div, result.type_name, class: 'type-name') + content_tag(:div, result.app_name, class: 'app-name') else content_tag(:div, result.type_name, class: 'type-name') end end </code></pre>
[]
[ { "body": "<p>Just use variables for repeated expressions:</p>\n\n<pre><code>def set_caption(result)\n type_div = content_tag(:div, result.type_name, class: 'type-name') \n if result.respond_to?(:app_name)\n type_div + content_tag(:div, result.app_name, class: 'app-name')\n else\n type_div\n end\nend\n</code></pre>\n\n<p>Note that you can move the conditional further in: <code>type_div + (condition ? app_div : \"\")</code>. Use this style whenever this adds readibility (here I'd say it doesn't).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:44:18.033", "Id": "21226", "ParentId": "21205", "Score": "2" } } ]
{ "AcceptedAnswerId": "21226", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T22:19:00.313", "Id": "21205", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "How to refactor that content_tag adding method?" }
21205
<p>I am writing a JavaScript/HTML driven web application. For the user interface, I am not completely sure that my JavaScript is 'OK'. Mainly, I switch between "modes" by assigning a placeholder variable to a new function, which changes what the onclick event does for items in a table (either open, edit, or move them).</p> <p>Am I breaking any code styles? Is my script hard to follow or understand? Is it unconventional for me to assign <code>bookmarkEventMapping</code> to another function later on in my code, using it as a placeholder? What can I do differently? Can you recommend any material that I could read to write clearer JavaScript?</p> <p>(Please note that this is a WIP)</p> <pre><code>var bookmarkEventMapping = function() {};//placeholder /* ... more JavaScript, which creates &amp;lt;li&amp;gt; elements that all have onclick events, example: element.addEventListener( "click", function(e) { bookmarkEventMapping(e); } ); ... */ function initModeMenu() {//called in &amp;lt;body&amp;gt; onload event var modeNames = ["normal","edit","move"];//the order in HTML menu for(var i = 0; i &amp;lt; 3; i++) {,&lt;!-- note: escaped &amp;lt; in loop --&gt; var node = document.getElementById("modeMenu").children[i]; bookmarkActions[ modeNames[i] ].node = node; node.dataset["action"] = modeNames[i]; node.addEventListener( "click", function() { bookmarkActions.setCurrentMode( this.dataset["action"] ); } ); } bookmarkActions.setCurrentMode("normal"); } var bookmarkActions = { "currentMode":"normal", "setCurrentMode":function(modeName) { var prevMode = bookmarkActions.currentMode; bookmarkActions[ prevMode ].exitMode(); bookmarkActions[ prevMode ].node.classList.remove("selected"); bookmarkEventMapping = bookmarkActions[ modeName ].eventMapping; bookmarkActions[ modeName ].node.classList.add("selected"); bookmarkActions.currentMode = modeName; }, "normal":{ "initMode":function() { }, "exitMode":function() { }, "eventMapping":function(ev) { } }, "edit":{ "initMode":function() { }, "exitMode":function() { }, "eventMapping":function(ev) { if(ev.type == "click") { bookmarkActions.edit.selectBookmark( ev.target ); } }, "selectBookmark":function(itemNode) { itemNode.dataset['bookmarkItemId']; itemNode.classList.add("editing");//.remove later } }, "move":{ "initMode":function() { }, "exitMode":function() { }, "eventMapping":function(ev) { } } }; </code></pre> <p>Below is a relevant snippet of HTML from the <code>&lt;body&gt;</code></p> <pre><code>&lt;menu id="modeMenu"&gt; &lt;li&gt;Normal&lt;/li&gt; &lt;li&gt;Edit&lt;/li&gt; &lt;li&gt;Move&lt;/li&gt; &lt;/menu&gt; </code></pre>
[]
[ { "body": "<p>Readability - the code reads fine. The modes concept is explained well just by reading the code, so I wouldn't worry about that.</p>\n\n<p>Code style - Javascript programmers are used to passing functions around and probably wouldn't bat an eyelid at the idea of assigning different functions to a variable, but it makes more sense to me to always have the same function as the event handler, and call the action for the current mode from within it:</p>\n\n<pre><code>var bookmarkEventMapping = function(e) {\n bookmarkActions[bookmarkActions.currentMode].eventMapping(e);\n};\n</code></pre>\n\n<p>A couple of other things I would do, out of personal preference more than anything:</p>\n\n<ul>\n<li>store the list of modes separately, not in the bookmarkActions object</li>\n<li>refer to the modes using references to the actual objects, as opposed to using the object property names.</li>\n</ul>\n\n<p>If you did store the mode list separately, you could also make things cleaner by making that list the only place where information about the modes is stored and using it to generate the html, instead of having to maintain the html and the code in initModeMenu separately.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T19:08:04.227", "Id": "24773", "ParentId": "21213", "Score": "2" } } ]
{ "AcceptedAnswerId": "24773", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T03:37:25.927", "Id": "21213", "Score": "3", "Tags": [ "javascript", "user-interface" ], "Title": "JavaScript/HTML web application - user interface logic" }
21213
<p>This is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int average_of_let_wor(); int main(void) { double answer; answer = average_of_let_wor(); printf("%.2lf", answer); return 0; } int average_of_let_wor() { double numberOfLetters = 0; double numberOfWords = 0; int userInput; double answer; printf("please enter your input:\n"); while ((userInput = getchar()) != EOF) { if (userInput == ' ' || userInput == '\t' || userInput == '\n') { numberOfWords++; continue; } else numberOfLetters++; } answer = numberOfLetters/numberOfWords; return answer; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:40:21.560", "Id": "34050", "Score": "0", "body": "And your question is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:01:49.287", "Id": "34051", "Score": "0", "body": "Hi, my question was is if this us a proper C code? Thanks for the reply! @BackinaFlash" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:10:58.067", "Id": "34052", "Score": "0", "body": "Why are you storing an integer value to a double type variable? `answer = average_of_let_wor();`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T22:20:38.180", "Id": "34084", "Score": "2", "body": "@BackinaFlash: Welcome to **\"CodeReview\"**. This is a review site. People post code to be reviewed and get tips on improving the code. If you think there is something worth changing the you should post an answer and explain why the change makes the code better (in any definition of better that you like)." } ]
[ { "body": "<p>First of all, be careful with types: to compute an average something, you will need a floating point number. However, the number of letters and words are countable and can therefore use the type <code>unsigned int</code> which are generally faster than floating point numbers.</p>\n\n<p>Moreover, to detect a \"space\" character, you can use the standard function <code>isspace</code> from the header <code>ctype.h</code>.</p>\n\n<p>Also, the variable <code>answer</code> is useless. You can get rid of it and simply return the answer the same line you're computing it.</p>\n\n<p>Therefore, your function <code>average_of_let_wor</code> can be reduced to:</p>\n\n<pre><code>double average_of_let_wor()\n{\n unsigned int numberOfLetters = 0;\n unsigned int numberOfWords = 0;\n int userInput;\n\n printf(\"please enter your input:\\n\");\n while ((userInput = getchar()) != EOF)\n {\n if (isspace(userInput))\n {\n numberOfWords++;\n }\n else\n {\n numberOfLetters++;\n }\n }\n\n return (double)numberOfLetters / (double)numberOfWords;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:02:38.730", "Id": "34054", "Score": "0", "body": "Quick question - this function obviously work perfectly. Something i wanted to understand: the first if block with the isspac() function...lets say my input is 3 times enter(return), isn't numberOfWords suppose to be 3..? again, it works perfectly and this scenario leaves numberOfWords still as 0, but how come? @Morwenn" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:10:14.037", "Id": "34055", "Score": "0", "body": "Reading newline characters is always a problem. I don't know all the subtleties of the mechanism. You should ask the question on stackoverflow.com or check whether the question xas already asked somewhere else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:32:23.087", "Id": "34060", "Score": "0", "body": "why use an unsigned type?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:35:44.240", "Id": "34061", "Score": "0", "body": "@WilliamMorris A number of letters/words can not be negative. The `standard` type to ensure this should be `size_t` btw." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:51:33.610", "Id": "34063", "Score": "0", "body": "Yeah, but I'm never sure that countability and non-negativity are sufficient grounds for unsigned. The above code performs no arithmetic, but unsigned arithmetic can really kick you in the shins at times. Compiler warnings help a lot. I prefer to keep unsigned for things like bitmaps that truly have no sign. But on the other hand, string handling and manipulation tend to be done using size_t, as things like strlen() return it. Not sure there is a clean answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T22:27:35.900", "Id": "34086", "Score": "3", "body": "Have issues with a lot of points: 1) I agree that `unsigned int` is a better choice for counting, but Int's faster than float? I doubt that is true in any measurable way. Even if it was who cares. 2) Though I agree about the use of isspace() it is not as simple as that. You need to explain that it changes the behavior of the code (more characters are space). 3) `the variable answer is useless`: Not true it makes the self documenting. It also helps when debugging as you can examine the result via the variable rather than manually evaluating the expression. Overall a bad attempt at a review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T23:32:42.417", "Id": "34088", "Score": "0", "body": "@LokiAstari thank you for your feedback :) do you know maybe where can i learn how to use my xcode debugger? im only using their comments, but i know there is a powerful debugger to for xcode(with that breakpoint's and everything..) and im not using it. any thoughts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T00:31:36.290", "Id": "34089", "Score": "0", "body": "@Nir: The debugger is built into xcode. I am not sure what you want. When you run the code in the simulator you are using the debugger automatically. Click on the left hand side of any source window to insert a break point (its a blow tag/arrow like thing)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T14:46:24.053", "Id": "34103", "Score": "0", "body": "@Loki Astari: 1) Depends on the architecture, but some (embedded ones) simply don't have a floating point calcul unit. Using integers may be faster and more portable. 2) You're right, I probably forgot about one of the characters, though I think it completes the original intent of the line more than potentially breaking the code. 3) You have a point for the debugger. The self-documentation is still there though: `return` + function name make it clear what it does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T14:15:34.587", "Id": "34156", "Score": "0", "body": "I agree with Loki regarding whether the extra variable is useless or not. To have a variable \"result\" or similar to contain the result of the function makes the code more readable. And it is very important to understand that this extra variable _does not allocate additional memory_. The return value will have to be stored somewhere, for example at an anonymous stack address. Whether you decide to name this address with a variable name or not doesn't matter, it is still allocated. The compiler is smart enough to merge the local variable \"answer\" with the anonymous \"return variable\"." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:44:13.103", "Id": "21230", "ParentId": "21214", "Score": "3" } }, { "body": "<p>Maintainability is an important part of coding.<br>\nI see where you are going with the name of the function. But if you go 80% there you may as well go the whole way. Name the function for what it does (don't chop the words).</p>\n\n<pre><code>int average_of_let_wor();\n\n// Would have preferred\n\nint average_of_letters_and_words();\n</code></pre>\n\n<p>Are you really returning an integer from the function? By your use case above you assign the result to a double. But if you return an int you will truncate the value. ie. you will get 2 rather than 2.5 etc.</p>\n\n<p>Here you assign to double. So I suspect you want to actually return a double.</p>\n\n<pre><code> double answer;\n answer = average_of_let_wor();\n</code></pre>\n\n<p>As pointed out by <code>@Morwenn</code>. Counts are usually integer. Personally I would also make them integer (but this will cause a slight problem below when you calculate the answer (as integer division returns an int so at that point you must coerce the values back to a double)). Thus this is really a 50/50 coin flip on which is the better technique and leaving them as double is quite acceptable.</p>\n\n<pre><code> double numberOfLetters = 0;\n double numberOfWords = 0;\n</code></pre>\n\n<p>The easy way to check for space is <code>isspace()</code>.</p>\n\n<pre><code> if (userInput == ' ' || userInput == '\\t' || userInput == '\\n')\n</code></pre>\n\n<p>But these are not the only space characters so be careful. If your specs say only to test for these three then using isspace() may give you different results.</p>\n\n<p>You are forgetting to test if the last character was a space. Thus words separated by double space count as two words (or more (if you use more spaces)). Also do you need to take into account punctuation and other characters?</p>\n\n<pre><code> {\n numberOfWords++;\n continue;\n }\n</code></pre>\n\n<p>Its a good habit to use braces on all nested code blocks.<br>\nThere are some corner cases where you may accidentally modify the code and a subsequent statement is not inside the else branch (and it is hard to spot (say inside a macro). So for maintainability please get into the habit of using <code>{}</code> </p>\n\n<pre><code> numberOfLetters++;\n</code></pre>\n\n<p>Here I totally disagree with <code>Morwenn</code>.</p>\n\n<pre><code> answer = numberOfLetters/numberOfWords;\n return answer;\n</code></pre>\n\n<p>There is nothing wrong with assigning the result to answer. It will make absolutely no difference to the resulting code that is generated and it helps document the code by explaining what you are doing here.</p>\n\n<p>Another added advantage is that when you are debugging, you can hover over the variable <code>answer</code> and see that it has been correctly defined.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T02:43:24.220", "Id": "34092", "Score": "1", "body": "Two small points. For the function name I would suggest `average_letters_per_word()`. About the `answer` variable: I do not agree with the arguments. The `return` clearly indicates and documents, that this is a result/answer. If necessary, the debugger can catch the return value from the function. I agree, that this does not make any difference to the resulting code, if any compiler optimization is done." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T22:41:03.920", "Id": "21242", "ParentId": "21214", "Score": "1" } } ]
{ "AcceptedAnswerId": "21230", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T03:44:58.450", "Id": "21214", "Score": "2", "Tags": [ "c" ], "Title": "Using a function to find the average for number of letters and words" }
21214
<p>Is there any way to simplify this code with loops or anything? I'm a beginner at JavaScript and my code is horrible. Please don't tell me to convert to jQuery or anything.</p> <pre><code> function dragLeftdropLeft1(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topLeft1').style.display = "none"; document.getElementById('topLeft2').style.display = "block"; } function dragLeftdropLeft2(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topLeft2').style.display = "none"; document.getElementById('topLeft3').style.display = "block"; } function dragLeftdropLeft3(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topLeft3').style.display = "none"; document.getElementById('topLeft4').style.display = "block"; } function dragLeftdropLeft4(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topLeft4').style.display = "none"; document.getElementById('topLeft5').style.display = "block"; } function dragLeftdropLeft5(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topLeft5').style.display = "none"; document.getElementById('topLeft1').style.display = "block"; } function dragLeftdropRight1(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topRight1').style.display = "none"; document.getElementById('topRight2').style.display = "block"; } function dragLeftdropRight2(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topRight2').style.display = "none"; document.getElementById('topRight3').style.display = "block"; } function dragLeftdropRight3(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topRight3').style.display = "none"; document.getElementById('topRight4').style.display = "block"; } function dragLeftdropRight4(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topRight4').style.display = "none"; document.getElementById('topRight5').style.display = "block"; } function dragLeftdropRight5(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Left"); document.getElementById('topRight5').style.display = "none"; document.getElementById('topRight1').style.display = "block"; } function dragRightdropLeft1(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topLeft1').style.display = "none"; document.getElementById('topLeft2').style.display = "block"; } function dragRightdropLeft2(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topLeft2').style.display = "none"; document.getElementById('topLeft3').style.display = "block"; } function dragRightdropLeft3(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topLeft3').style.display = "none"; document.getElementById('topLeft4').style.display = "block"; } function dragRightdropLeft4(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topLeft4').style.display = "none"; document.getElementById('topLeft5').style.display = "block"; } function dragRightdropLeft5(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topLeft5').style.display = "none"; document.getElementById('topLeft1').style.display = "block"; } function dragRightdropRight1(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topRight1').style.display = "none"; document.getElementById('topRight2').style.display = "block"; } function dragRightdropRight2(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topRight2').style.display = "none"; document.getElementById('topRight3').style.display = "block"; } function dragRightdropRight3(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topRight3').style.display = "none"; document.getElementById('topRight4').style.display = "block"; } function dragRightdropRight4(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topRight4').style.display = "none"; document.getElementById('topRight5').style.display = "block"; } function dragRightdropRight5(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Right"); document.getElementById('topRight5').style.display = "none"; document.getElementById('topRight1').style.display = "block"; } </code></pre> <p>I am trying to make a chopsticks game using HTML and JavaScript.</p>
[]
[ { "body": "<p>Abstract out the parts that are common to all of your functions. For instance:</p>\n\n<pre><code>function processEvent(evt, hideElem, showElem) {\n evt.preventDefault();\n document.getElementById(hideElem).style.display = \"none\";\n document.getElementById(showElem).style.display = \"block\";\n evt.dataTransfer.getData(\"Left\"); //not sure why you were calling this, but I'll leave it in\n}\n</code></pre>\n\n<p>Then you can implement your other functions like:</p>\n\n<pre><code>function dragLeftdropLeft1(ev) {\n processEvent(ev, 'topLeft1', 'topLeft2');\n}\n\n// and so on...\n</code></pre>\n\n<p>Note that if the nodes you are showing and hiding are adjacent in the DOM and one of them is the source of the event, you could probably rewrite the whole thing to work using a single function that takes advantage of <code>event.target</code> and <code>element.nextSibling</code>.</p>\n\n<p>...or convert to jQuery :p.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T11:07:53.423", "Id": "21221", "ParentId": "21218", "Score": "6" } }, { "body": "<p>It's easier if you set event handlers within javascript rather than inside the html code; this way it is simpler to pass variables to a single event handler. I don't understand why each of your event handlers has <code>var data=ev.dataTransfer.getData</code> but then doesn't do anything with the data; maybe this is something you will use later? And each of the top left and top right images is calling two separate functions when dropped (<code>dragRightdropRight1(event),dragLeftdropRight1(event)</code> etc), but as far as I can see the two functions do the same thing.</p>\n\n<p>Anyway you can simplify as follows, with a single function <code>drop</code> that does something different depending on the name of the box (topLeft, topRight) and the image number (0-4).</p>\n\n<pre><code>var boxes = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'],\n images = {};\n\n// Make a dictionary-like object containing all the image elements\nfor (var i = 0; i &lt; boxes.length; i++) {\n images[boxes[i]] = document.getElementById('box' + (i + 1)).getElementsByTagName('img');\n}\n\n// Set event handlers for the 1st two boxes, topLeft and topRight\nfor (var i = 0; i &lt; 5; i++) {\n images['topLeft'][i].ondrop = getDropFunction(ev, 'topLeft', i);\n images['topRight'][i].ondrop = getDropFunction(ev, 'topRight', i);\n}\n\n// Needed for reasons of variable scope\nfunction getDropFunction(ev, boxName, imageNumber) {\n return function() {\n drop(ev, boxName, imageNumber);\n };\n}\n\n// Deal with the drop event, depending on which box and image was dropped\nfunction drop(ev, boxName, imageNumber) {\n var nextImageNumber = (imageNumber + 1) % 5;\n ev.preventDefault();\n images[boxName][imageNumber].style.display = 'none';\n images[boxName][nextImageNumber].style.display = 'block';\n // as far as I can see this is all your code is doing\n // but you may want to add something that gets the data\n // from the ev and deals with it\n}\n</code></pre>\n\n<p>If you use this kind of solution you can remove the <code>ondrop</code> attributes from the images in the HTML.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:35:57.450", "Id": "21224", "ParentId": "21218", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T08:57:13.913", "Id": "21218", "Score": "5", "Tags": [ "javascript", "html" ], "Title": "Chopsticks game using HTML and JavaScript" }
21218
<p>I've a web form that allows users to create clusters of three sizes: small, medium and large. The form is sending a string of small, medium or large to a message queue, were job dispatcher determines how many jobs (cluster elements) it should build for a given cluster, like that:</p> <pre><code># determine required cluster size if cluster['size'] == 'small': jobs = 3 elif cluster['size'] == 'medium': jobs = 5 elif cluster['size'] == 'large': jobs = 8 else: raise ConfigError() </code></pre> <p>While it works, its very ugly and non flexible way of doing it - in case I'd want to have more gradual sizes, I'd increase number of <code>elif</code>'s. I could send a number instead of string straight from the form, but I dont want to place the application logic in the web app. Is there a nicer and more flexible way of doing something like that? </p>
[]
[ { "body": "<p>You could keep an array of jobs, and the web application would send index instead of word 'small', 'medium', 'large'.</p>\n\n<p>So you could have an array [3, 5, 8] and instead of \"small\" you send 0, instead of \"medium\" you send 1, and instead of \"large\" you send 2. You only need to check if the index received does not exceed the table size. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T10:03:12.957", "Id": "21220", "ParentId": "21219", "Score": "1" } }, { "body": "<p>how about using a dictionary whose keys are the different cluster types i.e. small, medium, large and the value is the actual cluster size i.e. 3,5,8</p>\n\n<p>Then when you get the POST request from the web form you just get the value from the dictionary. If no key exists then it's a validation error and you handle that appropriately.</p>\n\n<p>You can keep the dictionary in a static class so that it can be used throughout your app.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T11:18:20.617", "Id": "21222", "ParentId": "21219", "Score": "0" } }, { "body": "<p>I'd write:</p>\n\n<pre><code>jobs_by_cluster_size = {\"small\": 3, \"medium\": 5, \"large\": 8}\njobs = jobs_by_cluster_size.get(cluster[\"size\"]) or raise_exception(ConfigError())\n</code></pre>\n\n<p><code>raise_exception</code> is just a wrapper over <code>raise</code> (statement) so it can be used in expressions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:16:30.080", "Id": "34058", "Score": "1", "body": "I'm afraid that's not valid python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:25:39.763", "Id": "34059", "Score": "0", "body": "@WinstonEwert: Oops, I had completely forgotten `raise` is an statement in Python and not a function/expression (too much Ruby lately, I am afraid). Fixed (kind of)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:49:52.837", "Id": "21227", "ParentId": "21219", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T09:15:49.903", "Id": "21219", "Score": "2", "Tags": [ "python", "strings", "form" ], "Title": "Flexible multiple string comparision to determine variable value" }
21219
<p>Below is the code for knowing all the prime factors of a number. I think there must be some better way of doing the same thing. Also, please tell me if there are some flaws in my code.</p> <pre><code>def factorize(num): res2 = "%s: "%num res = [] while num != 1: for each in range(2, num + 1): quo, rem = divmod(num, each) if not rem: res.append(each) break num = quo pfs = set(res) for each in pfs: power = res.count(each) if power == 1: res2 += str(each) + " " else: res2 += str(each) + '^' + str(power) + " " return res2 </code></pre>
[]
[ { "body": "<pre><code>def factorize(num):\n res2 = \"%s: \"%num\n</code></pre>\n\n<p>You'd be much better off to put the string stuff in a seperate function. Just have this function return the list of factors, i.e. <code>res</code> and have a second function take <code>res</code> as a parameter and return the string. That'd make your logic simpler for each function.</p>\n\n<pre><code> res = []\n</code></pre>\n\n<p>Don't needlessly abbreviate. It doesn't save you any serious amount of typing time and makes it harder to follow your code.</p>\n\n<pre><code> while num != 1:\n for each in range(2, num + 1):\n</code></pre>\n\n<p>To be faster here, you'll want recompute the prime factors of the numbers. You can use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a>. Just keep track of the prime factors found, and you'll just be able to look them up.</p>\n\n<pre><code> quo, rem = divmod(num, each)\n if not rem:\n res.append(each)\n break\n num = quo\n</code></pre>\n\n<p>Your function dies here if you pass it a zero.</p>\n\n<pre><code> pfs = set(res)\n</code></pre>\n\n<p>Rather than a set, use <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>, it'll let you get the counts at the same time rather then recounting res.</p>\n\n<pre><code> for each in pfs:\n power = res.count(each)\n if power == 1:\n res2 += str(each) + \" \"\n else:\n res2 += str(each) + '^' + str(power) + \" \"\n</code></pre>\n\n<p>String addition is inefficient. I'd suggest using <code>\"{}^{}\".format(each, power)</code>. Also, store each piece in a list and then use <code>\" \".join</code> to make them into a big string at the end.</p>\n\n<pre><code> return res2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:15:06.070", "Id": "21231", "ParentId": "21229", "Score": "6" } } ]
{ "AcceptedAnswerId": "21231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:15:50.493", "Id": "21229", "Score": "2", "Tags": [ "python", "primes" ], "Title": "Code review needed for my Prime factorization code" }
21229
<p>I am writing a program that will deal with formatting the text in a text area. </p> <p>The user will use Ctrl + A, Ctrl + C to copy the entirety of a web page, then paste that text into a text area. The program will take the text area, remove the junk, and output the important information to then be copied and pasted into a different system.</p> <p>The concept is simple, but based on my education in programming I need a little help with the pseudocode to make sure I write this correctly and efficiently. I know this website is about code review and refactoring, so I've waited to post until I had some code written. I have already spent about three weeks on this project and I am moving too slowly. Any help would be greatly appreciated.</p> <p>Here's what I know (or think I know) needs to be done: - The program will use a loop to pass through the text box contents <strong>one time</strong>, extracting the important information and putting it into the appropriate variables - There will be a two dimensional array, or rather, an array of objects. The objects will be the account lines, each with information like account number, device type, phone number, etc. - The system needs to be able to identify certain fields that can be blank. I will give an example:</p> <p>Text that will be in the text box:</p> <p>Account Number - Account Name - Product - Phone - Extension - Equipment - Status - Start Date - Order ID</p> <p>ER4402 - testaccount - Unlimited Product - 1234567890 - 987 - FRZ142 - Active - 12-12-12 - ABC12345 ER4403 - testaccount2 - Unlimited Product - - - - Active - 12-12-12 - ABC12345</p> <p>Notice the second has empty fields. I think they would be /t in the text box.</p> <p>Edit: I pressed enter too soon... writing more info now</p> <p>Here are the objects I've made</p> <pre><code>// Customer "class" var customer = { name: "", phone: "", compName: "", email: "", getInfo: function () { return "Details: " + this.name + ", " + this.phone + ", " + this.compName + ", " + this.email; } } // Account lines "class" var account = { checked: 0, number: "", ipbx: "", product: "", phoneNumb: "", ext: "", equip: "", status: "", startDate: "", order: "", getInfo: function () { return "Details: " + this.number + ", " + this.ipbx + ", " + this.product + ", " + this.phoneNumb + ", " + this.ext + ", " + this.equip + ", " + this.status + ", " + this.startDate + ", " + this.order; } } </code></pre> <p>The code:</p> <pre><code>// Parse the input box into an array var inputArr = document.getElementById("inputBox").value.split(/[ ]/); var contNameBool = new Boolean(); var compNameBool = new Boolean(); var emailBool = new Boolean(); var accountsBool = new Boolean(); var accountLinesArray = new Array(); var marker = 1; var arrayNumb = 0; for(i = 0; i &lt; inputArr.length; i++) { switch(inputArr[i]) { case "Name": if(inputArr[i - 1] == "Summary") { contNameBool = true; break; } break; case "Details": if(contNameBool == true) { contNameBool = false; break; } else if(contNameBool == false &amp;&amp; compNameBool == true) { compNameBool = false; break; } break; case "Customer": if(inputArr[i - 1] == "Details") { contNameBool = false; compNameBool = true; break; } break; case "Address": if(inputArr[i - 1] == "Profile") { compNameBool = false; emailBool = true; break; } break; case ("VISA" || "MASTERCARD" || "AMERICAN" || "DISCOVER"): emailBool = false; break; case "Show": if(inputArr[i + 1] == "next" &amp;&amp; inputArr[1 + 2] == "row") { accountLinesArray.length = custDet[i - 1]; break; } break; case "Order": if(inputArr[i + 1] == "ID" &amp;&amp; inputArr[i + 2] == "MRC") { accountsBool = true; break; } break; } if(contNameBool == true &amp;&amp; inputArr[i] != "Name") { if(inputArr[i].search(",") != -1) { var temp = inputArr[i].split(/[,]/); temp.reverse(); if(customer.name == "") { customer.name = temp.join(" "); } else { customer.name = customer.name + " " + temp.join(" "); } } else { if(customer.name == "") { customer.name = inputArr[i]; } else { customer.name = customer.name + " " + inputArr[i]; } } } else if(compNameBool == true) { if (customer.compName == "") { customer.compName = inputArr[i + 1] + " "; } else if(inputArr[i + 1] == "Details") { void(0); } else { customer.compName = customer.compName + inputArr[i + 1] + " "; } } else if(emailBool == true) { if(customer.email == "") { customer.email = inputArr[i + 1]; } else if(inputArr[i + 1] == "VISA" || "MASTERCARD" || "AMERICAN" || "DISCOVER") { void(0); } else { customer.email = customer.email + " " + inputArr[i + 1]; } } else if(accountsBool == true) { if(inputArr[i].replace(/[\t]/)) switch(marker) { case 1: accountLinesArray[arrayNumb] = new account; break; case 2: break; case 3: break; case 4: break; case 5: break; case 6: break; case 7: break; case 8: break; case 9: break; } if (marker == 9) { marker = 1; } else { marker++; } } } /* customer.name = prompt("Error: Could not locate a valid Contact Name. Please input Contact Name."); customer.compName = prompt("Error: Could not locate a valid Company Name. Please input Company Name."); customer.email = prompt("Error: Could not locate a valid Email Address. Please input Email Address."); */ document.getElementById("contactNameOutput").innerHTML = customer.name; // document.getElementById("contactNameOutput").innerHTML = inputArr; document.getElementById("companyNameOutput").innerHTML = customer.compName; document.getElementById("emailAddressOutput").innerHTML = customer.email; </code></pre> <p>}</p> <p>The problem I'm having is figuring out how to get the program to identify when one account line has ended and a new one has begun.</p> <p>I've made a marker to have the program go back to the first part of the array, but I can't wrap my head around how to get it to identify if a field is blank and how to move on to the next field and reach the end of the account line in the right order.</p> <p>I realize I just asked a lot, but I don't know where to go or how to proceed with this. I admit that it's a bit over my head, but due to my frustration and level of completion, I really thought I should post it before I put the project on a hiatus. Any feedback or help would be appreciated.</p> <p>Thank you.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:59:12.377", "Id": "34065", "Score": "0", "body": "I'm sorry, but Code Review is for improving code that works, not how to fix program so that it works. For more information, see the [FAQ]." } ]
[ { "body": "<p>I have done this a lot in php with <a href=\"http://php.net/manual/de/function.preg-match-all.php\" rel=\"nofollow noreferrer\">preg_match_all()</a>. But this should also work in <a href=\"https://stackoverflow.com/questions/520611/how-can-i-match-multiple-occurrences-with-a-regex-in-javascript-similar-to-phps\">javascript</a>.</p>\n\n<p>My first blind guess for a regular expression: (Having some real samples would make this easier ..., furthermore I assume that the dashes are only for the layout and not in the data, and I wrap every part for readability .)</p>\n\n<pre><code>/([A-Z]{2}\\d{4})\\s*\n([a-z0-9]+)\\s*\n(.*?)\\s*\n(\\d+)?\\s*\n(\\d{3})?\\s*\n([A-Z]{3}\\d{3})?\\s*\n(Active|foo|bar)\\s*\n(\\d\\d-\\d\\d-\\d\\d)\\s*\n([A-Z]{3}\\d{5})/\n</code></pre>\n\n<p>If you are not familiar with regular expression: </p>\n\n<ul>\n<li><code>\\s*</code> is any white space</li>\n<li><code>\\d</code> are numbers</li>\n<li><code>{2}</code> is an exact count of 2, </li>\n<li><code>+</code> is one or more characters</li>\n<li><code>-</code> is none or more characters</li>\n<li><code>)?</code> is optional</li>\n<li><code>?)</code> is a lower greedyness</li>\n</ul>\n\n<p>For more details see: <a href=\"http://www.regular-expressions.info/examples.html\" rel=\"nofollow noreferrer\">regular expression</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T17:21:55.880", "Id": "34067", "Score": "0", "body": "Thank you. I will read more on regular expressions. I will post again when I have code that works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T17:25:33.923", "Id": "34068", "Score": "0", "body": "@Mrow Upvote and except the answer before the topic get closed :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T18:30:52.060", "Id": "34079", "Score": "0", "body": "I can't upvote. But I will accept the asnwer. Thank you. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T17:15:36.190", "Id": "21233", "ParentId": "21232", "Score": "1" } } ]
{ "AcceptedAnswerId": "21233", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T16:35:26.957", "Id": "21232", "Score": "-2", "Tags": [ "javascript", "parsing" ], "Title": "Parsing large text area - difficulty extracting info - Javascript" }
21232
<p>Matlab profiler throws this horrible bottleneck which is called 700000 times:</p> <pre><code>for k =1:model.nlf, for r =1:model.nlf, KuyDinvKyu = zeros(model.k,model.k); for q =1:model.nout, KuyDinvKyu = KuyDinvKyu + model.KuyDinv{k,q}*model.Kyu{q,r}; end if (k == r) model.A{k,r} = model.Kuu{k} + KuyDinvKyu; else model.A{k,r} = KuyDinvKyu; end end end </code></pre> <p>Even if the math is correct, there must be a faster way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:50:35.673", "Id": "34069", "Score": "2", "body": "some dimensions and sizes can be useful here. What are `size(model.KuyDinv{k,q})`, `size(model.Kyu{q,r})` and `size(model.Kuu{k})`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:51:29.043", "Id": "34070", "Score": "3", "body": "I also think that a bit of intuition into what this code is trying to compute (very high level motivation) can be of assistance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T18:45:24.773", "Id": "34071", "Score": "2", "body": "Is there a specific reason that all variables are cells?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T19:19:25.110", "Id": "34072", "Score": "0", "body": "As above; this questions is impossible to answer without knowing the dimensions of model.KuyDinv{k,q}. Are these vectors? Scalars?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:00:46.353", "Id": "34073", "Score": "0", "body": "concerning dimensions model.nlf is number of latent forces: up to 20 lf; nout is number of outputs also up to 20." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:03:20.067", "Id": "34074", "Score": "0", "body": "what this is doing: calculating the posterior distribution in multivariate Gaussian Processes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T09:32:15.240", "Id": "34075", "Score": "0", "body": "Why cell arrays? They all seem to be of the same size, so why not store it in a multi-dimensional matrix instead?" } ]
[ { "body": "<p>You will get a speed up by eliminating the if-statements in the inner loop. E.g. by splitting the inner loop via</p>\n\n<pre><code> for r = setdiff(1:model.nlf,k)\n %do the stuff to setup Model.A{k,r}\n end\n\n model.A{k,k} = ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T19:55:32.217", "Id": "34076", "Score": "0", "body": "Thank you for the hint. It has been confirmed and implemented with the second answer below. The profiler has improved from red to pink, a step in the right direction. Many thanks for your help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:30:03.380", "Id": "21235", "ParentId": "21234", "Score": "1" } }, { "body": "<p>Assuming <code>model.KuyDinv{k,q}</code> and <code>model.Kyu{q,r}</code> are a matrices (as the name would imply), there is little you can do. You can move the initialization of <code>KuyDinvKyu</code> outside the loop, and eliminate the branch to compute the diagonals: </p>\n\n<pre><code>% define it once -- saves many calls to 'zeros'\nKuyDinvKyu_0 = zeros(model.k);\n\nfor k = 1:model.nlf\n for r = 1:model.nlf\n\n KuyDinvKyu = KuyDinvKyu_0;\n\n for q = 1:model.nout\n KuyDinvKyu = KuyDinvKyu + model.KuyDinv{k,q}*model.Kyu{q,r};\n end\n\n % removed IF \n model.A{k,r} = KuyDinvKyu;\n\n end\nend\n\n% without IF\nfor c = 1:model.nlf \n model.A{c,c} = model.A{c,c} + model.Kuu{c}; \nend\n</code></pre>\n\n<p>If <code>model.KuyDinv{k,q}</code> and/or <code>model.Kyu{q,r}</code> contain <em>scalars</em>, well then we can optimize this much further for sure. So I need to know the size and type of data that <code>model.Kyu{q,r}</code> and <code>model.KuyDinv{k,q}</code> will contain. </p>\n\n<p>It might also be that your overall data design (e.g., the choice to use <code>cells</code>) is flawed and causes inefficiencies. So it could also be helpful to see some more surrounding code, so I can determine if there is some improvement to be made in that respect. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:04:40.000", "Id": "34077", "Score": "0", "body": "Thanks Rody for this very helpful reply. I implemented your solution and improved the profiler color code for that loop from red to pink. model.KuyDinv and all the others are matrices. I inherited this routine and I would agree that the overall data design using cells is the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:36:19.013", "Id": "34078", "Score": "0", "body": "@user2015897: I think you suggested an edit to my answer, that got rejected -- you should indeed post this as part of the *question* (rather than my *answer*), so that not only I but everyone here can take a look :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T13:26:58.403", "Id": "21236", "ParentId": "21234", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T17:32:27.320", "Id": "21234", "Score": "2", "Tags": [ "statistics", "matlab" ], "Title": "Calculating the posterior distribution in multivariate Gaussian processes" }
21234
<p>I've written a framework in MVC. I call it Midget MVC, as it's so darn small. The reason I wrote it is because I wanted a lightweight and extensible framework to use in projects. It eventually got abandoned due to it's break-ability and my lack of experience in the subject. However, I've got a bigger project I'm working on and need a framework, so I want to start re-writing MMVC. Feel free to view the entire project <a href="https://github.com/Jragon/Midget-MVC" rel="nofollow">here</a>. </p> <p>The main piece of code I want looked over is the router class. After talking a bit on the PHP I discovered that it was indeed breakable. One of the recommendations made was for me not to use <code>global $config</code>. What's the best way to do this? </p> <pre><code>&lt;?php class Route { public function load(){ global $config; if(isset($_SERVER['PATH_INFO'])){ $route = explode('/', substr($_SERVER['PATH_INFO'], 1)); $controller = ucfirst(strtolower($route[0])); $method = isset($route[1]) ? strtolower($route[1]) : 'index'; $path = APPPATH . "controllers/" . $route[0] . ".php"; if(realpath($path)){ require $path; $controller = new $controller; if($method != 'index'){ $variables = array(); $i = 0; foreach($route as $vars){ if ($i &gt;= 2) $variables[] = $route[$i]; $i++; } call_user_func_array(array($controller, $method), $variables); }else{ $controller-&gt;index(); } } }else{ $controller = $config['deafult_controller']; require APPPATH . "controllers/" . $controller . ".php"; $controller = ucfirst($controller); $controller = new $controller; $method = 'index'; $controller-&gt;$method(); } } } </code></pre> <p>The second thing I want help with is the load class. Is there a better way to load models into the controller? Loading library files was quite difficult; you have to load it in each file. If you load the library in the controller, you'll have to load it again in the model if you want to access it. What's the best way to do this?</p> <p> <pre><code>class Load{ function __construct($controller){ $this-&gt;controller = $controller; } // loads a specified model public function model($model){ $model = strtolower($model); if(file_exists(APPPATH . "models/$model.php")){ require(APPPATH . "models/$model.php"); $modelclass = ucfirst($model . '_Model'); // call function to include it in the controller $this-&gt;controller-&gt;$model = new $modelclass; } } // loads a veiw public function view($view, $data = NULL){ // asign filepath $path = APPPATH . "views/" . $view . ".php"; // asign variables if $data is set if($data != NULL) foreach($data as $var =&gt; $value) $$var = $value; if(file_exists($path)){ ob_start(); require($path); print(ob_get_clean()); }else return false; } public function library($library){ $library = strtolower($library); if(file_exists(LIBRARY . "$library.php")){ require(LIBRARY . "$library.php"); $libraryclass = ucfirst($library); $this-&gt;controller-&gt;$library = new $libraryclass; } } } </code></pre> <p>And finally, how secure is the entire thing. What security flaws can you see? Are there any major points I should improve upon.</p>
[]
[ { "body": "<p>Nice initiative on a lightweight MVC framework!</p>\n\n<p><em><strong>Note</em></strong> wanted to add more reference links, but it won't allow me to do more thanb 2</p>\n\n<h2>Config</h2>\n\n<ul>\n<li>Pass the default controller setting to the function </li>\n</ul>\n\n<p><em>or</em> </p>\n\n<ul>\n<li>Pass all routing related settings to the __constructor. and use them as class attributes</li>\n</ul>\n\n<h2>Loader class</h2>\n\n<p>The setup isn't all that bad. Nice and lightweight. A few things, i would do different;</p>\n\n<ul>\n<li>Seperations of conserns (One of the <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a> principles). Let the loader just load an return the instances.\n<ul>\n<li>Don't bind the loaded elements directly to controller in you class, so in future you could also use it for different cases then just the controller class.</li>\n<li>Don't render the views in a loader. Make a render class or such. If you way of rendering changes, you would have to change the loader. Which ultimately don't make sense.</li>\n</ul></li>\n<li><p>Make APP_PATH and LIBRARY settable within the loader, and call them differently</p>\n\n<ul>\n<li>A loader class attribute for each load path </li>\n<li>Default the attributes to APP_PATH and LIBRARY</li>\n<li>Getter and Setter for load paths</li>\n<li>Now you would be able to integrate different paths / modules etc. Making it more flexible</li>\n</ul></li>\n<li><p>Autoloader for library classes</p>\n\n<ul>\n<li>By registering the loader as <a href=\"http://php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow\">php autoloader</a> you can just instantiate a class. </li>\n<li>If not yet loaded into mem, it will be sent to the autoloader. </li>\n<li>There you resolve the path it should be on and instantiate.</li>\n</ul></li>\n</ul>\n\n<h2>Security</h2>\n\n<p>The big thing in this form of autoloading is the concern for input. Make sure all input is either given by the application itself or validate it.</p>\n\n<ul>\n<li>Validate user strings that will be autoloaded (eg. controller names)</li>\n<li>You can do this by first doing a realpath() check on the computed path. And make sure the realpath() is within the locations you would expect.</li>\n<li>This prevenst users from entering stuff like '......\\uploads\\mayhackscript' which would be executed otherwise.</li>\n</ul>\n\n<p>This <strong>is a real danger</strong>.</p>\n\n<h2>General remarks</h2>\n\n<p>Take a look at te following;</p>\n\n<ul>\n<li>SOLID principles</li>\n<li>PSR-2 coding standards; note, it extends PSR-1 which extends PSR-0</li>\n</ul>\n\n<p>Good luck on your project! </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T13:35:33.647", "Id": "34154", "Score": "0", "body": "PSR-0 is an autoloader interoperability standard. PSR-1 is a basic coding standard. PSR-2 is a coding style guide." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T11:06:00.813", "Id": "21248", "ParentId": "21237", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T19:22:54.047", "Id": "21237", "Score": "3", "Tags": [ "php", "mvc", "pdo", "url-routing" ], "Title": "Breakable MVC framework written in PHP" }
21237
<pre><code>def divisible?(n) if n % 1 == 0 &amp;&amp; n % 2 == 0 &amp;&amp; n % 3 == 0 &amp;&amp; n % 4 == 0 &amp;&amp; n % 5 == 0 &amp;&amp; n % 6 == 0 &amp;&amp; n % 7 == 0 &amp;&amp; n % 8 == 0 &amp;&amp; n % 9 == 0 &amp;&amp; n % 10 == 0 &amp;&amp; n % 11 == 0 &amp;&amp; n % 12 == 0 &amp;&amp; n % 13 == 0 &amp;&amp; n % 14 == 0 &amp;&amp; n % 15 == 0 &amp;&amp; n % 16 == 0 &amp;&amp; n % 17 == 0 &amp;&amp; n % 18 == 0 &amp;&amp; n % 19 == 0 &amp;&amp; n % 20 == 0 return true else return false end end </code></pre>
[]
[ { "body": "<p>Ruby refactor: use <a href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-all-3F\" rel=\"nofollow\">Enumerable.all?</a>:</p>\n\n<pre><code>def divisible?(n)\n (1..20).all? { |x| n % x == 0 }\nend\n</code></pre>\n\n<p>Mathematical refactor:calculate the least common multiple of the integers in the range (<a href=\"http://www.ruby-doc.org/core-1.9.3/Integer.html#method-i-lcm\" rel=\"nofollow\">Integer#lcm</a> is available from Ruby 1.9):</p>\n\n<pre><code>def divisible?(n)\n n % (1..20).reduce(:lcm) == 0\nend\n</code></pre>\n\n<p>This second snippet is, of course, more efficient once you pre-calculate <code>(1..20).reduce(:lcm)</code> only once and store it somewhere.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:01:48.733", "Id": "34201", "Score": "0", "body": "Would the first example benefit from 20..1 rather than 1..20? Less values of n are divisible by the higher divisors, leading to faster exit. Checking for factors seems like a case where premature optimisation is reasonable. (I don't know Ruby, maybe 1..20 is not equivalent to the big series of ifs in the question?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:14:27.383", "Id": "34202", "Score": "0", "body": "@Sean: yeah, good point, you could write `(1..20).reverse_each.all? ...`. Anyway, one you've decided to do it in a mathematically sound way you might as well go for the second snippet, which is simple enough to understand and much faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T21:07:35.307", "Id": "21240", "ParentId": "21238", "Score": "15" } }, { "body": "<p>Note that you're doing this, which is a pretty egrigious use of if/else:</p>\n\n<pre><code>if boolean\n return true\nelse\n return false\nend\n</code></pre>\n\n<p>If the branches of your if/else are <code>return true</code> and <code>return false</code>, you should just return the condition you're testing! In Ruby, you don't even need <code>return</code>, just let the condition \"fall off\" the end of the method.</p>\n\n<p>Ignoring the ability to clean up your condition itself, a first pass at cleaning up your function could be:</p>\n\n<pre><code>def divisible?(n)\n n % 1 == 0 &amp;&amp;\n n % 2 == 0 &amp;&amp;\n n % 3 == 0 &amp;&amp;\n n % 4 == 0 &amp;&amp;\n n % 5 == 0 &amp;&amp;\n n % 6 == 0 &amp;&amp;\n n % 7 == 0 &amp;&amp;\n n % 8 == 0 &amp;&amp;\n n % 9 == 0 &amp;&amp;\n n % 10 == 0 &amp;&amp;\n n % 11 == 0 &amp;&amp;\n n % 12 == 0 &amp;&amp;\n n % 13 == 0 &amp;&amp;\n n % 14 == 0 &amp;&amp;\n n % 15 == 0 &amp;&amp;\n n % 16 == 0 &amp;&amp;\n n % 17 == 0 &amp;&amp;\n n % 18 == 0 &amp;&amp;\n n % 19 == 0 &amp;&amp;\n n % 20 == 0\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T23:06:47.963", "Id": "21599", "ParentId": "21238", "Score": "2" } } ]
{ "AcceptedAnswerId": "21240", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T21:05:54.407", "Id": "21238", "Score": "6", "Tags": [ "ruby", "mathematics" ], "Title": "Simplify test for divisibility by all numbers 1…20" }
21238
<p>I put this together and it seems to work.</p> <p>1channel.py -breakingbad 1</p> <p>The Output (1-10): </p> <pre><code>(1) - Currently 3.80/5 (2) - Currently 3.50/5 </code></pre> <p>(1 opens the link in browser)</p> <p>If anyone has any suggestions or wants to improve it:</p> <pre><code>from bs4 import BeautifulSoup import urllib2, sys, webbrowser def Work(tvshow): print "\n[*] Working...\n" try: f = urllib2.urlopen(tvshow) html = f.read() soup = BeautifulSoup(html) for table in soup.findAll('table',{"width":"100%"}): for a in table.findAll('a',{"target":"_blank"}): for li in table.findAll('li',{"class":"current-rating"}): if a.text=="Version 2": print "(1) - %s\n" % (li.text) link1 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 3": print "(2) - %s\n" % (li.text) link2 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 4": print "(3) - %s\n" % (li.text) link3 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 5": print "(4) - %s\n" % (li.text) link4 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 6": print "(5) - %s\n" % (li.text) link5 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 7": print "(6) - %s\n" % (li.text) link6 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 8": print "(7) - %s\n" % (li.text) link7 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 9": print "(8) - %s\n" % (li.text) link8 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 10": print "(9) - %s\n" % (li.text) link9 = "http://www.1channel.ch" + a['href'] elif a.text=="Version 11": print "(10) - %s\n" % (li.text) link10 = "http://www.1channel.ch" + a['href'] user = raw_input("&gt;&gt;&gt; ") if user == '1': webbrowser.open(link1) elif user == '2': webbrowser.open(link2) elif user == '3': webbrowser.open(link3) elif user == '4': webbrowser.open(link4) elif user == '5': webbrowser.open(link5) elif user == '6': webbrowser.open(link6) elif user == '7': webbrowser.open(link7) elif user == '8': webbrowser.open(link8) elif user == '9': webbrowser.open(link9) elif user == '10': webbrowser.open(link10) else: exit(0) except urllib2.HTTPError: print "- HTTP Error!" except urllib2.URLError: print "- Connection Faliure!" except UnboundLocalError: print "Episode does not exist!" def Main(): if len(sys.argv) !=3: print "1channel.py -show episode#" sys.exit() elif sys.argv[1] == '-breakingbad': tvshow = 'http://www.1channel.ch/tv-4128-Breaking-Bad/season-4-episode-' + sys.argv[2] elif sys.argv[1] == '-walkingdead': tvshow = 'http://www.1channel.ch/tv-2490619-The-Walking-Dead/season-3-episode-' + sys.argv[2] elif sys.argv[1] == '-poi': tvshow = 'http://www.1channel.ch/tv-2727923-Person-of-Interest/season-2-episode-' + sys.argv[2] else: sys.exit() Work(tvshow) if __name__ == '__main__': Main() </code></pre>
[]
[ { "body": "<p>Here's what I would start with:</p>\n\n<pre><code>import sys\nimport re\nimport urllib2\nimport webbrowser\n\nfrom bs4 import BeautifulSoup\n\ndef get_episodes(url):\n print '[*] Working...'\n\n soup = BeautifulSoup(urllib2.urlopen(url))\n links = {}\n\n for table in soup.find_all('table', width='100%'):\n for a in table.find_all('a', target='_blank'):\n for li in table.find_all('li', class_='current-rating'):\n match = re.search(r'Version (\\d+)', a.get_text())\n\n if match:\n number = match.group(1)\n links[number] = 'http://www.1channel.ch' + a['href']\n\n print '({}) - {}\\n'.format(number, li.get_text())\n\n return links\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print '1channel.py -show episode#'\n sys.exit()\n elif sys.argv[1] == '-breakingbad':\n url = 'tv-4128-Breaking-Bad/season-4-episode-'\n elif sys.argv[1] == '-walkingdead':\n url = 'tv-2490619-The-Walking-Dead/season-3-episode-'\n elif sys.argv[1] == '-poi':\n url = 'tv-2727923-Person-of-Interest/season-2-episode-'\n else:\n sys.exit()\n\n try:\n episodes = get_episodes('http://www.1channel.ch/' + url + sys.argv[2])\n except urllib2.HTTPError:\n print '- HTTP Error!'\n sys.exit(0)\n except urllib2.URLError:\n print '- Connection Faliure!'\n sys.exit(0)\n\n number = int(raw_input('&gt;&gt;&gt; '))\n\n if number in episodes:\n webbrowser.open(episodes[number])\n else:\n print 'Episode does not exist!'\n sys.exit(0)\n</code></pre>\n\n<ul>\n<li>Keep functions simple and (generally) single-purpose. Have them do one simple task.</li>\n<li>Keep your code <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>. If you catch yourself writing the same code over and over, make a function for the general case and just fill in the variables.</li>\n<li>BeautifulSoup4 uses underscores instead of camel case, so <code>findAll</code> becomes <code>find_all</code>.</li>\n</ul>\n\n<p>I haven't tested this code either, but it should work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T22:31:48.847", "Id": "34087", "Score": "0", "body": "Wow thanks! there is a problem with raw_input have any ideas?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T01:38:53.050", "Id": "34090", "Score": "0", "body": "`int(raw_input(...))` expects a number. Are you typing one in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T03:17:42.323", "Id": "34093", "Score": "0", "body": "Yeah, it goes straight to the else:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T20:45:19.910", "Id": "34109", "Score": "0", "body": "Changed it to number = raw_input(...) and that works. Not sure why int(raw_input(...)) doesn't..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T20:46:14.333", "Id": "34110", "Score": "0", "body": "@Joe_Bonanno: Oh, whoops. I never converted `number` to an `int`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T21:26:03.170", "Id": "21241", "ParentId": "21239", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T21:06:03.737", "Id": "21239", "Score": "4", "Tags": [ "python", "beginner", "web-scraping", "beautifulsoup", "webdriver" ], "Title": "Opening TV episodes in a web browser" }
21239
<p>My question is really simple. Does this code cause memoryleaks? If so, where/how/why?</p> <pre><code>HDC hDC, memDC = 0; HBITMAP hBMP = 0; HBITMAP hOldBMP = 0; PAINTSTRUCT PS; HBRUSH hb212121, hb141414, hb070707, hb000, hbF7F7F7, hb989898, hb707070, hb494949, hb984921 = 0; HPEN hp353535 = 0; case WM_PAINT: hDC = BeginPaint(hWnd, &amp;PS); memDC = CreateCompatibleDC(hDC); hBMP = CreateCompatibleBitmap(hDC, 450, 450); SelectObject(memDC, hBMP); hb212121 = CreateSolidBrush(RGB(33, 33, 33)); FillRect(memDC, &amp;rMainClntNoBorder, hb212121); hb494949 = CreateSolidBrush(RGB(73, 73, 73)); hb984921 = CreateSolidBrush(RGB(152, 73, 33)); hb000 = CreateSolidBrush(RGB(0, 0, 0)); switch(tiles) { setTileRect(); case 1: FillRect(memDC, &amp;rTile, hb494949); break; case 2: FillRect(memDC, &amp;rTile, hb984921); break; case 7: FillRect(memDC, &amp;rTile, hb000); break; } SelectObject(memDC, hOldBMP); DeleteObject(hBMP); DeleteObject(hb984921); DeleteObject(hb494949); DeleteObject(hb212121); DeleteObject(hb000); hp353535 = CreatePen(PS_SOLID, 1, RGB(53, 53, 53)); SelectObject(memDC, hp353535); GetClientRect(hWnd, &amp;rClnt); MoveToEx(memDC, rClnt.left, rClnt.bottom - 1, 0); LineTo(memDC, rClnt.left, rClnt.top); LineTo(memDC, rClnt.right, rClnt.top); DeleteObject(hp353535); BitBlt(hDC, 0, 0, rMainClntNoBorder.right, rMainClntNoBorder.bottom, memDC, 0, 0, SRCCOPY); DeleteDC(memDC); EndPaint(hWnd, &amp;PS); break; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T06:10:43.337", "Id": "34095", "Score": "0", "body": "Have you seen anything to suggest that this code *does* cause a memory leak?" } ]
[ { "body": "<ul>\n<li><p>you select the pen in, but don't select out before delete.</p>\n\n<pre><code>SelectObject(memDC, hp353535);\n// snip\nDeleteObject(hp353535)\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>hOldPen = SelectObject(memDC, hp353535);\n// snip\nSelectObject( memDC, hOldPen );\nDeleteObject(hp353535)\n</code></pre></li>\n<li><p><code>SelectObject(memDC, hBMP);</code> should really be <code>hOldBMP = SelectObject(memDC, hBMP);</code></p></li>\n</ul>\n\n<p>For some other comments:</p>\n\n<ul>\n<li><p>I recommend that you split the WM_PAINT (and all other messages) processing into its own function. It'll be easier to read/debug.</p></li>\n<li><p>Are <code>rMainClntNoBorder</code> (and <code>rTile</code>, <code>rClnt</code>) globals, or declared and initialised before the code supplied?</p></li>\n<li><p>Only declare one variable per line. It's easier to read and find where it's declared rather than searching. It also avoids an issue with pointers that you may come across.</p></li>\n<li><p>Use proper names for the brushes if you can - hbDarkOrange (or even hbCurrentActiveTile) means more than hb984921.</p></li>\n<li><p>Unless you have hundreds of colours, it may be better to create them at the start of the program and delete them at the end, and store their values in a struct in the 'user-area' of the window structure - You may want to avoid creating and deleting them continually.</p></li>\n<li><p>If you don't do the above, keep the creation and deletion as close together as possible.</p>\n\n<pre><code>hbDarkGrey = CreateSolidBrush(RGB(33, 33, 33));\nFillRect(memDC, &amp;rMainClntNoBorder, hbDarkGrey);\nDeleteObject( hbDarkGrey );\n</code></pre></li>\n<li><p>Similarly, your switch statement could be simplified. Rather than creating three brushes and using one, just pick the one you want.</p>\n\n<pre><code>setTileRect(); // implies that rTile is a global??\nswitch(tiles)\n{\n case 1:\n tile_colour = RGB( 73, 73, 73 );\n break;\n case 2:\n tile_colour = RGB( 152, 73, 33 );\n break;\n case 7: // allow fallthrough\n default: // you need a default!!\n tile_colour = RGB( 0, 0, 0 );\n break;\n}\nhbTile = CreateSolidBrush( tile_colour );\nFillRect( memDC, &amp;rTile, hbTile );\nDeleteObject( hbTile );\n</code></pre></li>\n<li><p>Instead of 1 and 2 etc in the case statement, create some meaningful constants for them with <code>enum</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T14:22:28.080", "Id": "34102", "Score": "0", "body": "An excellent answer, I'll be sure to use these tips. I'll probably have some questions later on, so I'll post comments then. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T09:41:54.677", "Id": "21246", "ParentId": "21243", "Score": "3" } } ]
{ "AcceptedAnswerId": "21246", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T04:19:53.813", "Id": "21243", "Score": "2", "Tags": [ "c++", "memory-management", "windows" ], "Title": "Would this code cause memoryleaks?" }
21243
<p>I'm working on my first web app and would like some feedback on the code I have completed. I asked for a similar code review a few weeks ago but I have since improved my structure and added some user adjustable settings.</p> <p>The app is a simple math quiz (addition, subtraction, multiplication, &amp; division questions) where users can adjust several settings based on their needs. I did my best to make it object-oriented and am curious. How could I improve it?</p> <p>I purchased a few HTML5 books from Amazon and read through them but like most resources (including Mozilla Developer Network) they did a great job of explaining everything but did not really show any examples of how to structure a complete web app with settings, etc.</p> <p>My approach to structuring was to create a div for each "frame". A "frame" for the title screen, about screen, settings screen, quiz screen, and results screen. Only one "frame" is ever shown at a time and each "frame" has its own code area. Is this a good structure or could it be improved? Could I improve the way I load the current settings and update the settings when they're saved?</p> <p>The code below includes the complete app structure, an about screen, and a settings screen that can be adjusted and saved by the user (for the session only, adding storage later).</p> <p><a href="http://jsfiddle.net/Xfyju/2/" rel="nofollow">Fiddle</a></p> <pre><code>&lt;div id="frameHome"&gt; &lt;div align="center"&gt; &lt;p&gt;&lt;strong&gt;Math Quiz App&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="button" id="buttonPlay" value="Play"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="button" id="buttonSettings" value="Settings"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="button" id="buttonAbout" value="About"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="frameAbout"&gt; &lt;div align="center"&gt; &lt;p&gt;&lt;strong&gt;About&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Math Quiz App&lt;br /&gt; Version 1.0&lt;/p&gt; &lt;p&gt;&lt;input type="button" id="buttonOK" value="OK"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="frameSettings"&gt; &lt;div align="center"&gt; &lt;p&gt;&lt;strong&gt;Settings&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Operators: &lt;input type="checkbox" name="checkboxOperators" id="add" /&gt; Addition &lt;input type="checkbox" name="checkboxOperators" id="sub" /&gt; Subtraction &lt;input type="checkbox" name="checkboxOperators" id="mul" /&gt; Multiplication &lt;input type="checkbox" name="checkboxOperators" id="div" /&gt; Division &lt;/p&gt; &lt;p&gt;Number of questions: &lt;input type="button" id="buttonQuesMinus" value="&amp;lt;"&gt; &lt;span id="divQues"&gt;10&lt;/span&gt; &lt;input type="button" id="buttonQuesPlus" value="&amp;gt;"&gt; &lt;/p&gt; &lt;p&gt;Answer style: &lt;input type="radio" name="radioAnswerStyle" id="fillBlank" /&gt; Fill in the Blank &lt;input type="radio" name="radioAnswerStyle" id="multipleChoice" /&gt; Multiple Choice &lt;/p&gt; &lt;p&gt;Timer: &lt;input type="radio" name="radioTimer" id="off" /&gt; Off &lt;input type="radio" name="radioTimer" id="countdown" /&gt; Countdown &lt;input type="radio" name="radioTimer" id="elapsed" /&gt; Elapsed &lt;/p&gt; &lt;p&gt;Time: &lt;input type="button" id="buttonTimeMinus" value="&amp;lt;"&gt; &lt;span id="divTime"&gt;2:00&lt;/span&gt; &lt;input type="button" id="buttonTimePlus" value="&amp;gt;"&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="button" id="buttonCancel" value="Cancel"&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="button" id="buttonSave" value="Save"&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="frameQuiz"&gt; Quiz &lt;/div&gt; &lt;div id="frameResults"&gt; Results &lt;/div&gt; &lt;script&gt; // Variables // Settings var operators = ["add", "sub", "mul", "div"]; // add, sub, mul, AND div var totalQuestions = 10; // 5 TO 100 var timerStyle = "countdown"; // off OR countdown OR elapsed var countdownTime = 120; // 30 TO 3600 var answerStyle = "multipleChoice"; // multipleChoice OR fillBlank // Frames var frameHome = document.getElementById("frameHome"); var frameAbout = document.getElementById("frameAbout"); var frameSettings = document.getElementById("frameSettings"); var frameQuiz = document.getElementById("frameQuiz"); var frameResults = document.getElementById("frameResults"); var frames = [frameHome, frameAbout, frameSettings, frameQuiz, frameResults]; // Displays frame and hides all other frames function gotoFrame(frameID) { for (var i = 0; i &lt; frames.length; i++) { if (frameID == frames[i].id) { // Show frame frames[i].style.display = "block"; } else { // Hide frame frames[i].style.display = "none"; } } frameCode(frameID); } // Code for each frame, code runs when frame is displayed function frameCode(frameID) { switch (frameID) { case "frameHome": buttonPlay.onclick = function () { gotoFrame("frameQuiz"); }; buttonSettings.onclick = function () { gotoFrame("frameSettings"); }; buttonAbout.onclick = function () { gotoFrame("frameAbout"); }; break; case "frameAbout": buttonOK.onclick = function () { gotoFrame("frameHome"); }; break; case "frameSettings": // Operators ---------- // Get element var checkboxOperators = document.getElementsByName("checkboxOperators"); // Uncheck all for (var i = 0; i &lt; checkboxOperators.length; i++) { document.getElementById(checkboxOperators[i].id).checked = false; } // Check operators based on operators array for (var i = 0; i &lt; operators.length; i++) { document.getElementById(operators[i]).checked = true; } // ------------------------------ // Number of questions ---------- var tempTotalQuestions = totalQuestions; divQues.innerHTML = tempTotalQuestions; // Questions minus buttonQuesMinus.onclick = function() { if (tempTotalQuestions &gt; 5) { tempTotalQuestions -= 5; } divQues.innerHTML = tempTotalQuestions; }; // Questions plus buttonQuesPlus.onclick = function() { if (tempTotalQuestions &lt; 100) { tempTotalQuestions += 5; } divQues.innerHTML = tempTotalQuestions; }; // ------------------------------ // Answer style ---------- document.getElementById(answerStyle).checked = true; // ------------------------------ // Timer style ---------- document.getElementById(timerStyle).checked = true; // ------------------------------ // Countdown time ---------- var tempCountdownTime = countdownTime; divTime.innerHTML = formatTime(tempCountdownTime); // Time minus buttonTimeMinus.onclick = function() { if (tempCountdownTime &gt; 30) { tempCountdownTime -= 30; } divTime.innerHTML = formatTime(tempCountdownTime); }; // Time plus buttonTimePlus.onclick = function() { if (tempCountdownTime &lt; 3600) { tempCountdownTime += 30; } divTime.innerHTML = formatTime(tempCountdownTime); }; // ------------------------------ // Cancel button ---------- buttonCancel.onclick = function () { gotoFrame("frameHome"); }; // ------------------------------ // Save button ---------- buttonSave.onclick = function () { // Save updated settings // Operators // Empty array operators.length = 0; for (var i = 0; i &lt; checkboxOperators.length; i++) { if (document.getElementById(checkboxOperators[i].id).checked == true) { operators.push(checkboxOperators[i].id); } } // Number of questions totalQuestions = tempTotalQuestions; // Answer style var radioAnswerStyle = document.getElementsByName("radioAnswerStyle"); for (var i = 0; i &lt; radioAnswerStyle.length; i++) { if (radioAnswerStyle[i].checked) { answerStyle = radioAnswerStyle[i].id; } } // Timer style var radioTimer = document.getElementsByName("radioTimer"); for (var i = 0; i &lt; radioTimer.length; i++) { if (radioTimer[i].checked) { timerStyle = radioTimer[i].id; } } // Countdown time countdownTime = tempCountdownTime; gotoFrame("frameHome"); }; // ------------------------------ break; case "frameQuiz": break; case "frameResults": break; } } // Format time // Formats time as minutes and seconds (0:00) function formatTime(time) { var minutes = Math.floor(time / 60); var seconds = time - (minutes * 60); // Add 0 in front of seconds less than 10 if (seconds &lt; 10) { seconds = "0" + seconds; } return minutes + ":" + seconds; } // Go to home frame when app opens gotoFrame("frameHome"); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>If you introduced a client-side MVVM framework, I think you would get the modularization that you are looking for. I have worked with, and really enjoy, <a href=\"http://knockoutjs.com/\" rel=\"nofollow\">knockout</a>. Each frame could have it's own viewmodel, and you could create a single viewmodel that controls the flow logic between them.</p>\n\n<p>For example, your settings frame would be built off of a <code>SettingsViewModel</code> that would hold all of the JavaScript, and perhaps contain a method on it that would return <code>currentSettings</code> to be used in other frames. Additionally, you can test the behavior of this view model independent of the representation of it (the HTML). Overall, this leads to a cleaner separation of concerns (application logic and presentation).</p>\n\n<p>Here's a <a href=\"http://jsfiddle.net/fingers/W973t/5/\" rel=\"nofollow\">fiddle</a> of a subset of the settings frame.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T22:20:07.810", "Id": "21258", "ParentId": "21244", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T07:24:18.353", "Id": "21244", "Score": "2", "Tags": [ "javascript", "html5", "quiz" ], "Title": "Simple four-function math quiz" }
21244
<p>I'm brand new to AngularJS. I would like advice as to whether I'm approaching the design of a simple login section of an app built with Angular correctly.</p> <p>The app consists of two view partials: <em>login.html</em> and <em>user-admin.html</em>. Of what I have so far, the user types their username into the login page. A controller checks if that username is listed in <em>users.json</em> file, if so then login is successful and the <em>user-admin.html</em> partial replaces <em>login.html</em>.</p> <p>I feel that the controller which checks the typed username against the usernames in <em>users.json</em> could be written better. Is there a more efficient way than using the 'for' statement?</p> <p>To develop this further I will want to add some way of preventing a logged in user seeing the login page and a non-logged in user seeing the admin page. My initial thought is to use cookies. But would the 'Angular' way be to create a service that perpetuates the logged in status between views? If that is the best way to implement it, what would that service look like?</p> <h2>app.js</h2> <pre><code>angular.module('userApp', ["ngResource"]). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/login', {templateUrl: 'partials/login.html', controller: LoginCtrl}). when('/loggedin', {templateUrl: 'partials/user-admin.html', controller: UserCtrl}). otherwise({redirectTo: '/login'}); }],[ '$locationProvider', function($locationProvider) { $locationProvider.html5Mode = true; }]). factory("User", function($resource) { return $resource("users/:userId.json", {}, { query: {method: "GET", params: {userId: "users"}, isArray: true} }); }); </code></pre> <h2>controllers.js</h2> <pre><code>function LoginCtrl($scope, $route, $routeParams, $location, User) { $scope.users = User.query(); $scope.loginUser = function() { var loggedin = false; var totalUsers = $scope.users.length; var usernameTyped = $scope.userUsername; for( i=0; i &lt; totalUsers; i++ ) { if( $scope.users[i].name === usernameTyped ) { loggedin = true; break; } } if( loggedin === true ) { alert("login successful"); $location.path("/loggedin"); } else { alert("username does not exist") } } } function UserCtrl($scope, $route, $routeParams, $location) { $scope.logoutUser = function() { $location.path("/login"); } } </code></pre> <h2>users.json</h2> <pre><code>[ { "userId": 1, "name": "Tommy", "password": "123456", "log": { "registration": "2012.12.14", "lastLog": "2013.01.15" } }, { "userId": 2, "name": "Anne", "password": "123456", "log": { "registration": "2012.12.24", "lastLog": "2012.12.29" } }, { "userId": 3, "name": "Miles", "password": "abc", "log": { "registration": "2013.02.01", "lastLog": "2013.02.01" } } ] </code></pre> <h2>login.html</h2> <pre><code>&lt;h1&gt;Login&lt;/h1&gt; &lt;section&gt; &lt;form ng-submit="loginUser();"&gt; &lt;label for"userUsername"&gt;Username&lt;/label&gt;&lt;input type="text" id="userUsername" ng-model="userUsername"&gt; &lt;input type="submit" value="Login"&gt; &lt;/form&gt; &lt;/section&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T13:19:37.030", "Id": "43497", "Score": "1", "body": "do you have a working example fo this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T17:43:53.160", "Id": "43513", "Score": "0", "body": "No unfortunately I don't. I didn't get much further with this project and hasn't been worked on for a while." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T06:52:24.443", "Id": "86689", "Score": "0", "body": "change line: for( i=0; i < totalUsers; i++ ) TO for(var i=0; i < totalUsers; i++ )" } ]
[ { "body": "<p>There is much wrong with your code..</p>\n\n<ul>\n<li>You are iterating over every record to find a username, what happens if you have lots of users ?</li>\n<li>You are not verifying the password !?</li>\n<li>It seems like you are exposing the REST services with all the user id's and passwords !?</li>\n<li>It seems that if the user knows the <code>/loggedin</code> URL, then the user can skip logging in since you do not validate <code>loggedIn</code> anywhere. Even worse, <code>loggedIn</code> is a variable local to LoginCtrl.</li>\n</ul>\n\n<p>It is good to try and write everything yourself, it brings valuable experience. But please, use this only for throwaway websites.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T15:50:10.250", "Id": "39225", "ParentId": "21245", "Score": "6" } }, { "body": "<p>You could also create an HTTP call to a PHP <code>$http.post();</code> to make your call in a secure php file and getting a query to spit back a <code>json_encoded();</code> response. I liked the example above. I will be using it along with some ngCookies to keep the session open that way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-21T20:08:23.523", "Id": "47827", "ParentId": "21245", "Score": "2" } }, { "body": "<p>There are lots of mistake with your code:</p>\n\n<ol>\n<li>The database seems to be limited</li>\n<li>Your code is not authenticating the username and password</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-19T07:19:46.580", "Id": "153005", "ParentId": "21245", "Score": "-2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T08:24:11.457", "Id": "21245", "Score": "3", "Tags": [ "javascript", "mvc", "angular.js" ], "Title": "Creating a simple login with AngularJS" }
21245
<p>I would really like some advice from any DB gurus who have a few minutes free. After doing some reading and playing with sqlfiddle over the weekend I have constructed this PostgreSQL schema and it is the first proper one I've ever done, so I am sure I've made some poor choices.</p> <p>This is what I've got for a "job" and "advert" site:</p> <pre><code>-- -- Application Database Structure -- -- Company Table CREATE TABLE company ( id SERIAL PRIMARY KEY, name varchar(60) NOT NULL ); -- Country Table CREATE TABLE country ( id SERIAL PRIMARY KEY, name varchar(255) NOT NULL ); -- Location Table CREATE TABLE location ( id SERIAL PRIMARY KEY, name varchar(255) NOT NULL, country_id integer NOT NULL REFERENCES country (id), coordinate varchar(255) NOT NULL ); -- Source Table CREATE TABLE source ( id SERIAL PRIMARY KEY, name varchar(60) NOT NULL ); -- Payment Method Table CREATE TABLE payment_method ( id SERIAL PRIMARY KEY, name varchar(60) NOT NULL ); -- Payment Table CREATE TABLE payment ( -- Generic id SERIAL PRIMARY KEY, ip varchar(255), email varchar(255) NOT NULL, amount varchar(255), payment_method_id integer NOT NULL REFERENCES payment_method (id), -- Credit Card card_name varchar(255), card_expiration varchar(255), -- Paypal paypal_email varchar(255), paypal_transactionid varchar(255) ); -- Job Table CREATE TABLE job ( -- Identification id SERIAL PRIMARY KEY, solrid varchar (10), -- Job Information title varchar(60) NOT NULL, description varchar(255) NOT NULL, truncated_description varchar(255) NOT NULL, keyword_description varchar(255) NOT NULL, how_to_apply varchar(255) NOT NULL, website_url varchar(255) NOT NULL, logo_url varchar(255), page_url varchar(255) NOT NULL, -- Dates date timestamp NOT NULL, expires timestamp NOT NULL, -- Linked Tables company_id integer NOT NULL REFERENCES company (id), source_id integer NOT NULL REFERENCES source (id), location_id integer NOT NULL REFERENCES location (id), payment_id integer NOT NULL REFERENCES payment (id), -- Status Flags active boolean DEFAULT FALSE, premium boolean DEFAULT FALSE, indexed boolean DEFAULT FALSE, error boolean DEFAULT FALSE, -- Email Flags email_reminder boolean DEFAULT FALSE, email_confirmation boolean DEFAULT FALSE ); -- Advert Table CREATE TABLE advert ( -- Identification id SERIAL PRIMARY KEY, -- Content title varchar(60) NOT NULL, description varchar(255) NOT NULL, page_url varchar(255) NOT NULL, -- Dates date timestamp NOT NULL, expires timestamp NOT NULL, -- Email Flags email_reminder boolean DEFAULT FALSE, email_confirmation boolean DEFAULT FALSE -- Linked Tables source_id integer NOT NULL REFERENCES source (id), payment_id integer NOT NULL REFERENCES payment (id), -- Status Flag active boolean DEFAULT FALSE, error boolean DEFAULT FALSE ); </code></pre> <p>Could anyone give me some guidance / possible improvements before I start building my site about this DB?</p>
[]
[ { "body": "<p>This seems pretty good to me (disclaimer : I am NOT a Database guru).</p>\n\n<ul>\n<li><p>for payment.amount, it would be worth using something more relevant than varchar. You can have a look at the DO question <a href=\"https://stackoverflow.com/questions/628637/best-data-type-for-currency\">Best Data Type For Currency</a>.</p></li>\n<li><p>it might be worth having some kind of inheritance for the different payment methods (credit card, paypal, etc). You could use <a href=\"http://www.martinfowler.com/eaaCatalog/concreteTableInheritance.html\" rel=\"nofollow noreferrer\">Concrete Table Inheritance</a>. Doing so, you might also be able to get rid of the payment_method table.</p></li>\n<li><p>I'm not too sure what you are planning to store in location.coordinate so I cannot really advise.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T20:44:23.183", "Id": "21254", "ParentId": "21247", "Score": "1" } }, { "body": "<p>Hmmm.....</p>\n\n<pre><code>--\n-- Application Database Structure\n--\n\n-- Company Table\nCREATE TABLE company (\n id SERIAL PRIMARY KEY,\n name varchar(60) NOT NULL\n);\n</code></pre>\n\n<p>This probably works, for now. I'm assuming the column can handle weird characters, things like Chinese characters, if appropriate. Please note that international business gets a little strange, in terms of things like subsidiaries, and companies doing business in foreign countries (not sure if important).</p>\n\n<pre><code>-- Country Table\nCREATE TABLE country (\n id SERIAL PRIMARY KEY,\n name varchar(255) NOT NULL\n);\n</code></pre>\n\n<p>You're going to want to add a 'localization' table, in addition to refactoring this. Something along these lines:</p>\n\n<pre><code>-- Country Table\nCREATE TABLE country (\n id SERIAL PRIMARY KEY,\n Iso3166_1_Alpha_3 char(3) NOT NULL,\n Iso3166_1_Alpha_2 char(2),\n Iso3166_1_Numeric char(3) NOT NULL\n -- This last is comprised of digits, \n -- But not really a number, per se\n);\n\n-- Country Localization table\nCREATE TABLE country_localization (\n country_id INTEGER NOT NULL REFERENCES country (id),\n language_id INTEGER NOT NULL REFERENCES language (id),\n name varchar(100) NOT NULL\n);\n</code></pre>\n\n<p>.... Which means you're going to want a 'language' table (and localization) as well. You can use this as the base pattern - the relevant ISO code standard is ISO 639.</p>\n\n<pre><code>-- Location Table\nCREATE TABLE location (\n id SERIAL PRIMARY KEY,\n name varchar(255) NOT NULL,\n country_id integer NOT NULL REFERENCES country (id),\n coordinate varchar(255) NOT NULL\n);\n</code></pre>\n\n<p>I can't really say if <code>name</code> is appropriate - what are you planning on storing there? Please note that <em>addresses</em> are incredibly varied in international settings. Storing country is likely okay. <code>coordinate</code> is almost certainly wrong; if postgreSQL has a geo extension/module, use the relevant types - otherwise, use a pair of doubles/reals, and store latitude/longitude.</p>\n\n<pre><code>-- Source Table\nCREATE TABLE source (\n id SERIAL PRIMARY KEY,\n name varchar(60) NOT NULL\n);\n</code></pre>\n\n<p>... source of what?</p>\n\n<pre><code>-- Payment Method Table\nCREATE TABLE payment_method (\n id SERIAL PRIMARY KEY,\n name varchar(60) NOT NULL\n);\n</code></pre>\n\n<p>You may need to internationalize this one, as well. I'm assuming this is effectively an Enum (eg, 'VISA', 'MASTERCARD', etc).</p>\n\n<pre><code>-- Payment Table\nCREATE TABLE payment (\n -- Generic\n id SERIAL PRIMARY KEY,\n ip varchar(255), \n email varchar(255) NOT NULL, \n amount varchar(255),\n payment_method_id integer NOT NULL REFERENCES payment_method (id),\n -- Credit Card\n card_name varchar(255),\n card_expiration varchar(255),\n -- Paypal\n paypal_email varchar(255),\n paypal_transactionid varchar(255)\n);\n</code></pre>\n\n<p><code>email</code> suggests that you should have some sort of 'payee' table, either as a person, business or... company. Also, why do you have <em>two</em> emails in the table? Try to avoid storing multiple logical 'entities' in the same table. While I applaud not having a column for 'credit card number', if you're going to be able to track reversals, you're going to have to know what number to reverse (assuming that you accept non-PayPal transactions).<br>\nEven under IPV6, you don't need an ip address <em>that</em> long - the maximum address is 39 characters (including delimiters).\n <code>amount</code> should be either <code>DECIMAL</code> or <code>NUMERIC</code> (at least you didn't make it float/double/real...).<br>\nI'm also nervous about <code>card_expiration</code> being character-based. Really, what you have is an 'expires before business day' column (eg - it's usually expressed as 'expires 07/2012', which is 'active before 2012-08-01'), which probably ought to be stored as a <code>date</code> (probably without time, given the possibility of DST moving, but probably with timezone). Note that is still complicated, because, due to timezones (and ignoring any shifting business themselves do), there are <strong>2</strong> <em>concurrent</em> business (sun-has-come-up) days on the planet happening at once: when any particular bank/payment pre-processor switches is up to them.</p>\n\n<pre><code>-- Job Table\nCREATE TABLE job (\n -- Identification\n id SERIAL PRIMARY KEY,\n solrid varchar (10),\n -- Job Information\n title varchar(60) NOT NULL,\n description varchar(255) NOT NULL,\n truncated_description varchar(255) NOT NULL,\n keyword_description varchar(255) NOT NULL,\n how_to_apply varchar(255) NOT NULL,\n website_url varchar(255) NOT NULL, \n logo_url varchar(255),\n page_url varchar(255) NOT NULL,\n -- Dates\n date timestamp NOT NULL,\n expires timestamp NOT NULL, \n -- Linked Tables\n company_id integer NOT NULL REFERENCES company (id),\n source_id integer NOT NULL REFERENCES source (id),\n location_id integer NOT NULL REFERENCES location (id),\n payment_id integer NOT NULL REFERENCES payment (id),\n -- Status Flags\n active boolean DEFAULT FALSE,\n premium boolean DEFAULT FALSE,\n indexed boolean DEFAULT FALSE,\n error boolean DEFAULT FALSE,\n -- Email Flags\n email_reminder boolean DEFAULT FALSE,\n email_confirmation boolean DEFAULT FALSE\n);\n</code></pre>\n\n<p>What's <code>solrid</code>? There's no explanation.<br>\nYou may want to create some sort of <code>website</code> table that you can just fk-reference, including things like the site and logo there.<br>\n<code>truncated_description</code> isn't any shorter than <code>description</code>... is one supposed to be shorter?<br>\nYou are probably going to want a (internationalized?) <code>tag</code> (and <code>job_tag</code>) table, taking the place of <code>keyword_description</code>; split user search terms, get all matching tags, and find the jobs with the highest number of matches (and potentially search the <em>regular</em> description as well).<br>\nWhat date does <code>date</code> represent? <code>postedOn</code>? <code>paidForOn</code>? <code>fufilledOn</code>? Always try to name columns descriptively as to what they logically represent; these will often <em>not</em> include the column type.<br>\n<code>expires</code> probably shouldn't be a timestamp type. If you have it, it should be a date (sans time) type. The reasoning is that it's an imprecise, business-related concept (actual close of business isn't <em>necessarily</em> midnight...). This <em>may</em> apply to <code>date</code> as well, but the name is too ambiguous to be able to tell. Date ranges should also (pretty much always) be upper-bound exclusive (<a href=\"http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have-in-common.aspx\" rel=\"nofollow\">this blog</a> mostly deals with SQL Server-specific problems, but the concepts are equivalent); in light of that, the name should probably be changed to something like <code>activeUntil</code> (or store the duration instead).<br>\nIs <code>active</code> derived information - can I tell just by whether the current (business) day is between <code>date</code> and <code>expires</code>? If so, unless you have an actual performance issue, it's best to <strong>not</strong> store it (ie what happens if <code>active</code> is true after <code>expires</code> is in the past?).</p>\n\n<pre><code>-- Advert Table\nCREATE TABLE advert (\n -- Identification\n id SERIAL PRIMARY KEY,\n -- Content\n title varchar(60) NOT NULL,\n description varchar(255) NOT NULL,\n page_url varchar(255) NOT NULL,\n -- Dates\n date timestamp NOT NULL,\n expires timestamp NOT NULL,\n -- Email Flags \n email_reminder boolean DEFAULT FALSE,\n email_confirmation boolean DEFAULT FALSE\n -- Linked Tables\n source_id integer NOT NULL REFERENCES source (id),\n payment_id integer NOT NULL REFERENCES payment (id), \n -- Status Flag\n active boolean DEFAULT FALSE,\n error boolean DEFAULT FALSE\n);\n</code></pre>\n\n<p>See previous remarks about <code>date</code>, <code>expires</code> and <code>active</code>.<br>\nHmm, you may want some sort of 'reminder' and 'confirmation' table sets.</p>\n\n<p>All I can think of at the moment. Providing expected (example) data contents may also help us critique your efforts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T22:04:19.307", "Id": "21316", "ParentId": "21247", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T10:57:35.007", "Id": "21247", "Score": "2", "Tags": [ "sql", "database", "finance", "postgresql", "web-services" ], "Title": "Payment application database" }
21247
<p>My conditional code here seems repetitive and long. Is there a better approach? I want to test for a string value in a <code>NSDictionary</code> object and then depending upon the value prefix a <code>UILabel</code> with $, £, ¥ currency symbols.</p> <p>I've just shown 2 examples below. I have more currencies and the code is very long.</p> <pre><code>if ([[item objectForKey:@"currency"] isEqualToString:@"EUR"]) { NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]]; NSString *priceStringFix = [priceConvertToStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""]; priceLabelText.text = priceStringFix; [imgView2 addSubview:priceLabelText]; } if ([[item objectForKey:@"currency"] isEqualToString:@"GBP"]) { NSString *priceConvertToStr = [NSString stringWithFormat:@"€%@", [[item objectForKey:@"price"]stringValue]]; NSString *priceStringFix = [priceConvertToStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""]; priceLabelText.text = priceStringFix; [imgView2 addSubview:priceLabelText]; } if ([[item objectForKey:@"currency"] isEqualToString:@"USD"]) { NSString *priceConvertToStr = [NSString stringWithFormat:@"$%@", [[item objectForKey:@"price"]stringValue]]; NSString *priceStringFix = [priceConvertToStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""]; priceLabelText.text = priceStringFix; [imgView2 addSubview:priceLabelText]; } </code></pre>
[]
[ { "body": "<p>I'd create an NSDictionary holding those prefixes and wrap that whole thing into its own method, like so: </p>\n\n<pre><code>-(NSString *) prefixForCurrency:(NSString *)currency{\n NSDictionary *currencyPrefixes = @{@\"EUR\": @\"€\", @\"USD\" : @\"$\", @\"GBP\" : @\"£\", @\"NOK\" : @\"kr.\" };\n NSString *returnString = [currencyPrefixes objectForKey:currency]; \n\n return returnString;\n}\n</code></pre>\n\n<p>Then, instead of your current mass of if-statements you'd have something like the following:</p>\n\n<pre><code>NSString *currency = [item objectForKey:@\"currency\"];\nNSString *currencyPrefix = [self prefixForCurrency: currency];\n\nNSString *price = [item objectForKey:@\"price\"];\nNSString *priceString = [NSString stringWithFormat:@\"%@ %@\", currencyPrefix, price];\n</code></pre>\n\n<p>In case you were wondering: the main reason I wrap the prefixDictionary in its own method is in case you'd for instance prefer to fetch this list from a file later on. Then you can just alter the innards of that one method...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T11:58:12.293", "Id": "21250", "ParentId": "21249", "Score": "4" } } ]
{ "AcceptedAnswerId": "21250", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T11:38:15.483", "Id": "21249", "Score": "3", "Tags": [ "strings", "objective-c", "ios", "hash-map" ], "Title": "Applying a currency symbol based on a tested string value" }
21249
<p>I have to do some encoding and then assign the result to a label. Is there a more optimal (or concise) way to write this?</p> <pre><code>// encoding fix NSString *correctStringTitle = [NSString stringWithCString: [[item objectForKey:@"main_tag"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding: NSUTF8StringEncoding]; cell.titleLabel.text = [correctStringTitle capitalizedString]; </code></pre>
[]
[ { "body": "<p>Here is a marginally more concise solution:</p>\n\n<pre><code>cell.titleLabel.text = [NSString stringWithCString:[[item[@\"main_tag\"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding].capitalizedString;\n</code></pre>\n\n<p>If I had to do this more than once I would consider hiding this complexity in an NSString category like:</p>\n\n<pre><code>@interface NSString(Utils)\n -(NSString)stringWithLatinEncoding;\n@end\n\n@implementation NSString(Utils)\n\n-(NSString)stringWithLatinEncoding\n{\n return [NSString stringWithCString:[self cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];\n}\n\n@end\n</code></pre>\n\n<p>This will simplify your code to:</p>\n\n<pre><code>cell.titleLabel.text = ((NSString*)item[@\"main_tag\"]).stringWithLatinEncoding.capitalizedString;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T20:00:31.193", "Id": "22871", "ParentId": "21251", "Score": "4" } } ]
{ "AcceptedAnswerId": "22871", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T15:00:44.293", "Id": "21251", "Score": "1", "Tags": [ "objective-c", "ios" ], "Title": "Encoding and assigning the result to a label" }
21251
<p>I wrote a program to find the longest common subsequence among several strings. I used a naive algorithm and implementation.</p> <p>The motivation was solving the Rosalind problem at <a href="http://rosalind.info/problems/lcs/" rel="nofollow noreferrer">http://rosalind.info/problems/lcs/</a> . You can find sample input there as well. The Rosalind problem concerns strings as DNA, but I think my code can be treated as a general string operation.</p> <p>The problem asks for any of the common substrings if there is more than one, but I find all of them.</p> <blockquote> <p>A <a href="https://web.archive.org/web/20130102100634/http://rosalind.info/glossary/common-substring/" rel="nofollow noreferrer">common substring</a> of a collection of strings is a <a href="https://web.archive.org/web/20130102100634/http://rosalind.info/glossary/substring/" rel="nofollow noreferrer">substring</a> of every member of the collection. We say that a common substring is a <a href="https://web.archive.org/web/20130102100634/http://rosalind.info/glossary/longest-common-substring/" rel="nofollow noreferrer">longest common substring</a> if a longer common substring of the collection does not exist. For example, CG is a common substring of ACGTACGT and AACCGGTATA, whereas GTA is a longest common substring. Note that multiple longest common substrings may exist.</p> <p><strong>Given</strong>: A collection of <a href="https://web.archive.org/web/20130102100634/http://rosalind.info/glossary/dna-string/" rel="nofollow noreferrer">DNA strings</a> (of length at most 1 <a href="https://web.archive.org/web/20130102100634/http://rosalind.info/glossary/kbp/" rel="nofollow noreferrer">kbp</a> each; ).</p> <p><strong>Return</strong>: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.)</p> <h3>Sample Dataset</h3> <pre><code> GATTACA TAGACCA ATACA </code></pre> <h3>Sample Output</h3> <pre><code> AC </code></pre> </blockquote> <p>How can this code be improved? What obvious problems are there?</p> <pre><code>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; namespace Finding_a_Shared_Motif { class Program { private static void Main() { var input = File.ReadAllLines(&quot;rosalind_lcs.txt&quot;).ToList(); var t = new Stopwatch(); t.Restart(); var lcs = LongestCommonSubstring(input); t.Stop(); File.WriteAllLines(&quot;output.txt&quot;, lcs); Console.WriteLine(&quot;Finished in {0} msec.&quot;, t.ElapsedMilliseconds); Console.ReadLine(); } public static IEnumerable&lt;string&gt; LongestCommonSubstring(List&lt;string&gt; strings) { var lcs = LongestCommonSubstring(strings[0], strings[1]); for (var i = 2; i &lt; strings.Count(); i++) { var new_lcs = new BestStrings(); foreach (var s in lcs) new_lcs.Add(LongestCommonSubstring(s, strings[i])); lcs = new_lcs; } return lcs; } private static BestStrings LongestCommonSubstring(string s1, string s2) { var lcs = new BestStrings(); for (var i = 1 - s2.Length; i &lt; s1.Length; i++) { var substrings = BestSubstringWithAlignment(s1, s2, i); if (substrings.Length == 0) continue; lcs.Add(substrings); } return lcs; } private static BestStrings BestSubstringWithAlignment(string s1, string s2, int offset) { var substrings = new BestStrings(); var substring = &quot;&quot;; for (var i = Math.Max(0, offset); i &lt; s1.Length &amp;&amp; i &lt; s2.Length + offset; i++) { var c1 = s1[i]; var c2 = s2[i - offset]; if (c1 == c2) { substring = substring + c1; } else { substrings.Add(substring); substring = &quot;&quot;; } } substrings.Add(substring); return substrings; } sealed class BestStrings : Collection&lt;string&gt; { public int Length { get { return base[0].Length; } } public BestStrings() { base.Add(&quot;&quot;); } public new void Add(string s) { if (s.Length == 0 || s.Length &lt; Length || Contains(s)) return; if (s.Length &gt; Length) Clear(); base.Add(s); } public void Add(IEnumerable&lt;string&gt; collection) { foreach (var s in collection) Add(s); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T19:29:22.613", "Id": "34193", "Score": "0", "body": "Nothing major for me. Just your one place using new_lcs instead of camel casing. Pretty consistent everywhere else though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T02:00:58.370", "Id": "532295", "Score": "0", "body": "It's not correct!\nChange input to List<string> input = new() { \"abc1edfg\", \"abc2edfg\", \"abc3edfg\", \"abc4edg\", \"abc5edfg\", }; the answer is \"ed\" not \"abc\", because it ignores \"abc\" since beginning." } ]
[ { "body": "<p>Firstly some style.</p>\n\n<p>Short named variables don't help readability at all. <code>c1</code>, <code>c2</code>, <code>s1</code>, <code>s2</code> are a bad idea. I know this is just a challenge and not production code but keeping a consistent style is a good habit.</p>\n\n<p>Secondly I would start by using the <code>string.Contains()</code> method. It will find if a specified substring exists and should help clean up some of the code.</p>\n\n<p>In this train of thought I decided to start with all the possible substrings in the first string and then search the list of all strings.</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; LongestCommonSubstrings(List&lt;string&gt; strings)\n{\n var firstString = strings.FirstOrDefault();\n\n var allSubstrings = new List&lt;string&gt;();\n for(int substringLength = firstString.Length -1; substringLength &gt;0; substringLength--)\n {\n for(int offset = 0; (substringLength + offset) &lt; firstString.Length; offset++)\n {\n string currentSubstring = firstString.Substring(offset,substringLength);\n if (!System.String.IsNullOrWhiteSpace(currentSubstring) &amp;&amp; !allSubstrings.Contains(currentSubstring))\n {\n allSubstrings.Add(currentSubstring);\n }\n }\n }\n\n return allSubstrings.OrderBy(subStr =&gt; subStr).ThenByDescending(subStr =&gt; subStr.Length).Where(subStr =&gt; strings.All(currentString =&gt; currentString.Contains(subStr)));\n}\n</code></pre>\n\n<p>This will also allow us to do a <code>.FirstOrDefault()</code> on the linq and get the largest ( due to the <code>orderby()</code> calls.</p>\n\n<p><em>(To test I used a static list of strings instead of a file:)</em></p>\n\n<pre><code>public static void Run()\n{\n var input = new List&lt;string&gt;{\n \"GATTACA\",\n \"TAGACCA\",\n \"ATACA\",\n };\n\n var t = new Stopwatch();\n t.Restart();\n var lcs = LongestCommonSubstrings(input);\n t.Stop();\n\n Console.WriteLine(\"All Common substrings: \\r\\n{0}\", string.Join(\"\\r\\n\", lcs));\n Console.WriteLine(\"Finished in {0} msec.\", t.ElapsedMilliseconds);\n Console.ReadLine();\n}\n</code></pre>\n\n<p><em>DISCLAIMER: Haven't fully tested the above code. May harm your brain/computer.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T09:54:33.600", "Id": "34220", "Score": "1", "body": "Careful! `OrderByDescending` overrides the effects of `OrderBy` — what you need is `ThenByDescending`. And *please* don't fully qualify `System.String`. I suggest simply using the lower case alias `string` if you feel that `String` alone is too ambiguous." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T23:36:05.670", "Id": "34264", "Score": "0", "body": "@codesparkle oops! Thanks. I really should be more careful I hadn't noticed the orderby/orderbydescending." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T06:00:42.717", "Id": "21327", "ParentId": "21252", "Score": "5" } }, { "body": "<p>I'm not sure if you're interested in better algorithms, but if so <a href=\"http://www.cs.sunysb.edu/~algorith/files/longest-common-substring.shtml\" rel=\"nofollow\">here are some</a>. </p>\n\n<p>In this particular implementation, I would consider changing how you handle substrings. You're currently doing a lot of string concatenation, which can be slow as a new <code>string</code> object is allocated each time. Since you're just tracking substrings anyway, you could instead store the source string, start index and length of each match. That would save you potentially quite a bit of memory, and run faster as well. </p>\n\n<p>If you're really attached to having separate string objects, at the very least figure out the extent of the match and then do a single <code>substring()</code> to extract it, rather than building up the substring one character at a time. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T19:42:13.470", "Id": "21441", "ParentId": "21252", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-03T17:54:40.570", "Id": "21252", "Score": "7", "Tags": [ "c#", "programming-challenge", "strings", "bioinformatics" ], "Title": "Longest common substring" }
21252