body
stringlengths 111
6.48k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
---|---|---|---|---|
<p>I am playing with different ways to do database interaction in PHP, and one of the ideas I have been playing with is connecting to the DB in the constructor and disconnecting in the destructor. This is the code from my <code>Database</code> class.</p>
<pre><code>function __construct()
{
$this->link = mysql_connect($this->server.':'.$this->port, $this->username);
if(!$this->link)
die('Could not connect: '.mysql_error());
if(!mysql_select_db($this->database, $this->link))
die('Could not select database: '.mysql_error());
}
function __destruct()
{
if(mysql_close($this->link))
$this->link = null;
}
</code></pre>
<p>This works well, my only reservation is that if I need to connect several to hit the database several times it will do multiple connections and disconnects. If I do that a lot I can see, maybe, potential problems. Is this a concern or is there a better way to do this? And is my code even up to snuff in general?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T07:49:12.973",
"Id": "496986",
"Score": "0",
"body": "Look at the URL number. This is the first question humanity ever asked here!"
}
] | [
{
"body": "<p>You could use MySQLi (PHP extension) which is class based by default instead of MySQL. It \nis very easy to set up multiple connections. You are, however, required to know the connection you are querying always.</p>\n\n<hr>\n\n<p>Congrats with the first question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:04:27.663",
"Id": "3",
"ParentId": "1",
"Score": "19"
}
},
{
"body": "<p>From your question I infer that you're thinking of having several instances of the DB class. If so I'd suggest abstracting the connection out to another class and holding a reference to the same connection in each DB instance.</p>\n\n<p>You could then set your connection up as a singleton and thus only connect & disconnect once.</p>\n\n<p>Apologies in advance if I've missed anything here - my PHP is far from fluent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:14:45.420",
"Id": "13",
"Score": "0",
"body": "Yes. I will have multiple instances of the database class. I just wasn't sure on a good approach to make for abstracting away the connection, or if I even should."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:58:41.740",
"Id": "49",
"Score": "0",
"body": "The thing is I've been stung in the past by using more than one connection when I could've shared the connection so I'd say \"abstract it unless you can think of a very good reason not to\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:10:07.140",
"Id": "5",
"ParentId": "1",
"Score": "18"
}
},
{
"body": "<p>You might also look into the built-in php command mysql_pconnect(). This differs from mysql_connect in that it opens a persistent connection to the DB the first time it is called, and each subsequent time, it checks to see if an existing connection to that database exists and uses that connection instead. You should then remove the mysql_close command from the destructor, as they will persist between page loads.</p>\n\n<p>The php manual page: <a href=\"http://php.net/manual/en/function.mysql-pconnect.php\">http://php.net/manual/en/function.mysql-pconnect.php</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:19:33.573",
"Id": "19",
"Score": "0",
"body": "I read about that, and it sounds very enticing. However, how do you close the connection? in the docs it says the mysql_close() doesn't work. Do you just rely on mysql server to close it when it has been inactive for so long. I'd like to know that once all the work is done that the connection is closed."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:22:54.403",
"Id": "23",
"Score": "0",
"body": "You don't close the connection explicitly. It eventually gets closed by the php internals after a certain time has elapsed without use. This eliminates all of the overhead involved with repeatedly opening and closing connections, and allows individual page requests to be much faster."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:26:33.283",
"Id": "28",
"Score": "0",
"body": "Okay, i'll do some playing with this too. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:12:43.930",
"Id": "6",
"ParentId": "1",
"Score": "16"
}
},
{
"body": "<p>use an abstraction library like Pear MDB2 for your database connection. </p>\n\n<p>This abstracts all the connection logic away from your code, so should ever change your database (mysql to SQLite,etc) you won't have to change your code. </p>\n\n<p><a href=\"http://pear.php.net/manual/en/package.database.mdb2.php\">http://pear.php.net/manual/en/package.database.mdb2.php</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:42:57.963",
"Id": "38",
"Score": "3",
"body": "The last stable release was in [2007](http://pear.php.net/package/MDB2)... So either it's good to the point where it doesn't need updating (doubt it, since there's a beta in the works), or it's just plain inactive (more likely) There are tons of better abstraction layers (IMHO) that are more actively developed than this..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:46:32.370",
"Id": "39",
"Score": "1",
"body": "i haven't used PHP in a while,so please feel free to add it in this thread or create a new response :) my point is that a much better solution is to abstract the connection/query logic away via a library, more so than a specific library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:32:29.907",
"Id": "19",
"ParentId": "1",
"Score": "13"
}
},
{
"body": "<p>I don't think it makes any difference in regards to connecting to the database within the construction or within a connect method, what i do think you need to change is those die commands.</p>\n\n<p>using die causes the script to halt and send 1 little message to the user, who would think this is rubbish, and never visit your site again :( :(</p>\n\n<p>What you should be doing is catching your errors, and redirecting to a static page where you can show a very nice message to the user, fully apologising for the technical issues your having.</p>\n\n<p>You can also have an box that says, Enter your email address and we will email you when were back on line, you get the idea.</p>\n\n<p>as for the code I would go down the lines of:</p>\n\n<pre><code>class Database\n{\n public function __construct($autoconnect = false)\n {\n //Here you would 'globalize' your config and set it locally as a reference.\n if($autoconnect === true)\n {\n $this->connect();\n }\n }\n\n public function connect()\n {\n if($this->connected() === false)\n {\n $result = $this->driver->sendCommand(\"connect\");\n if($result === true)\n {\n $this->setConnectionState(\"active\");\n $this->setConnectionResource($this->driver->sendCommand(\"get_resource\"));\n }else\n {\n throw new DatabaseConnectionError($this->driver->sendCommand(\"getDriverError\"));\n }\n }\n }\n}\n</code></pre>\n\n<p>This gives you more functionality in the long run as every action is decidable within your APP, nothing is auto fired on default.</p>\n\n<p>you can simple use try,catch blocks to maintain your error reporting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T09:29:26.970",
"Id": "239",
"Score": "0",
"body": "+1 for the use of try/catch. Also I have experienced issues with failures thrown in the constructor: you do not have an instance of the object to implement whatever fallback mechanism would make sense, which in my case was using large parts of code present in the class... Without a valid instance, you cannot call instance methods, and I had to make some static methods, which was less than ideal."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T12:33:19.980",
"Id": "244",
"Score": "0",
"body": "Thanks, But I'me struggling to understand you, Can you please rephrase your comment please."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T17:12:59.320",
"Id": "251",
"Score": "0",
"body": "Sure :) Throwing exceptions is fine as long as you add code to try and catch them. Avoid code that throws exceptions in a constructor though, this could lead to some issues that I have experienced: in case of failure, you have no object created, and you might miss that in your catch block, if you want to reuse behaviors defined for this object. I would rather recommend to create the connection in a regular method, e.g. init() or connect(), called on the object after it has been created, not directly in the constructor."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:31:15.977",
"Id": "41",
"ParentId": "1",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "5",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:02:47.183",
"Id": "1",
"Score": "39",
"Tags": [
"php",
"mysql",
"constructor"
],
"Title": "Database connection in constructor and destructor"
} | 1 |
<p>I'd like suggestions for optimizing this brute force solution to <a href="http://projecteuler.net/index.php?section=problems&id=1">problem 1</a>. The algorithm currently checks every integer between 3 and 1000. I'd like to cut as many unnecessary calls to <code>isMultiple</code> as possible:</p>
<pre><code>'''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
end = 1000
def Solution01():
'''
Solved by brute force
#OPTIMIZE
'''
sum = 0
for i in range(3, end):
if isMultiple(i):
sum += i
print(sum)
def isMultiple(i):
return (i % 3 == 0) or (i % 5 == 0)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:06:48.893",
"Id": "3",
"Score": "1",
"body": "Are you trying to optimize the algorithm or the code itself?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:07:15.663",
"Id": "5",
"Score": "0",
"body": "@JoePhillips: Why not both? ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:08:43.633",
"Id": "6",
"Score": "0",
"body": "@JoePhillips: the algorithm. it currently checks every single integer between 3 and 1000."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:09:03.493",
"Id": "7",
"Score": "0",
"body": "@Zolomon: good point, either type of answer would be helpful."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T18:12:10.890",
"Id": "2889",
"Score": "0",
"body": "Just a note. The detailed explanation for [Richard's Answer](http://codereview.stackexchange.com/questions/2/project-euler-problem-1-in-python/280#280) on Wikipedia may be helpful if you didn't already understand the Math. See [here](http://en.wikipedia.org/wiki/Arithmetic_series#Sum)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:57:29.667",
"Id": "12182",
"Score": "0",
"body": "[Relevant blog post](http://cowbelljs.blogspot.com/2011/12/projecteuler-001.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:30:06.993",
"Id": "12221",
"Score": "0",
"body": "@TryPyPy, you may want to weigh in here: http://meta.codereview.stackexchange.com/questions/429/online-contest-questions"
}
] | [
{
"body": "<p>I think the best way to cut out possible checks is something like this:</p>\n\n<pre><code>valid = set([])\n\nfor i in range(3, end, 3):\n valid.add(i)\n\nfor i in range(5, end, 5):\n valid.add(i)\n\ntotal = sum(valid)\n</code></pre>\n\n<p>There's still a bit of redundancy (numbers which are multiples of both 3 and 5 are checked twice) but it's minimal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:25:31.500",
"Id": "25",
"Score": "0",
"body": "@gddc: nice, I didn't even know you could specify an increment in a range like that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:26:07.760",
"Id": "26",
"Score": "0",
"body": "That's also what I would do now."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:26:24.727",
"Id": "27",
"Score": "0",
"body": "@calavera - range() is a great function ... the optional step as a 3rd parameter can save tons of iterations."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:03:12.310",
"Id": "50",
"Score": "0",
"body": "http://docs.python.org/library/functions.html#range just for good measure"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T19:36:59.043",
"Id": "496",
"Score": "0",
"body": "You could save some memory (if using 2.x) by using the xrange function instead of range, it uses the iterator protocol instead of a full blown list."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T19:38:54.627",
"Id": "497",
"Score": "2",
"body": "Also by using the set.update method you could shed the loop and write someting like: valid.update(xrange(3, end, 3))"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:23:04.670",
"Id": "11",
"ParentId": "2",
"Score": "28"
}
},
{
"body": "<p>g.d.d.c's solution is slightly redundant in that it checks numbers that are multiples of 3 and 5 twice. I was wondering about optimizations to this, so this is slightly longer than a comment, but not really an answer in itself, as it totally relies on g.d.d.c's awesome answer as inspiration.</p>\n\n<p>If you add multiples to the valid list for the multiple \"3\" and then do another pass over the whole list (1-1000) for the multiple \"5\" then you do experience some redundancy.</p>\n\n<p>The order in which you add them:</p>\n\n<pre><code> add 3-multiples first\n add 5 multiples second\n</code></pre>\n\n<p>will matter (albeit slightly) if you want to check if the number exists in the list or not.</p>\n\n<p>That is, if your algorithm is something like</p>\n\n<pre><code>add 3-multiples to the list\n\nadd 5-multiples to the list if they don't collide\n</code></pre>\n\n<p>it will perform slightly worse than</p>\n\n<pre><code>add 5-multiples to the list\n\nadd 3-multiples to the list if they don't collide\n</code></pre>\n\n<p>namely, because there are more 3-multiples than 5-multiples, and so you are doing more \"if they don't collide\" checks.</p>\n\n<p>So, here are some thoughts to keep in mind, in terms of optimization:</p>\n\n<ul>\n<li>It would be best if we could iterate through the list once</li>\n<li>It would be best if we didn't check numbers that weren't multiples of 3 nor 5.</li>\n</ul>\n\n<p>One possible way is to notice the frequency of the multiples. That is, notice that the LCM (least-common multiple) of 3 and 5 is 15: </p>\n\n<pre><code>3 6 9 12 15 18 21 24 27 30\n || ||\n 5 10 15 20 25 30\n</code></pre>\n\n<p>Thus, you should want to, in the optimal case, want to use the frequency representation of multiples of 3 and 5 in the range (1,15) over and over until you reach 1000. (really 1005 which is divided by 15 evenly 67 times).</p>\n\n<p>So, you want, for each iteration of this frequency representation:</p>\n\n<p>the numbers at: 3 5 6 9 10 12 15</p>\n\n<p>Your frequencies occur (I'm sorta making up the vocab for this, so please correct me if there are better math-y words) at starting indexes from <strong>0k + 1 to 67k</strong> (1 to 1005) [technically 66k]</p>\n\n<p>And you want the numbers at positions <em>3, 5, 6, 9, 10, 12, and 15</em> enumerating from the index.</p>\n\n<p>Thus,</p>\n\n<pre><code>for (freq_index = 0; freq_index < 66; ++freq_index) {\n valid.add(15*freq_index + 3);\n valid.add(15*freq_index + 5);\n valid.add(15*freq_index + 6);\n valid.add(15*freq_index + 9);\n valid.add(15*freq_index + 10);\n valid.add(15*freq_index + 12);\n valid.add(15*freq_index + 15); //also the first term of the next indexed range\n}\n</code></pre>\n\n<p>and we have eliminated redundancy</p>\n\n<p>=)</p>\n\n<p><hr>\n<em>Exercise for the astute / determined programmer:</em><br>\nWrite a function that takes three integers as arguments, <em>x y z</em> and, without redundancy, finds all the multiples of <em>x</em> and of <em>y</em> in the range from 1 to <em>z</em>.<br>\n(basically a generalization of what I did above).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:44:11.497",
"Id": "54",
"Score": "0",
"body": "I'll have to check the documentation to be sure, but I believe the `set.add()` method uses a binary lookup to determine whether or not the new element exists already. If that's correct then the order you check the multiples of 3's or 5's won't matter - you have an identical number of binary lookups. If you can implement a solution that rules out double-checks for multiples of both you may net an improvement."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T01:14:51.330",
"Id": "72",
"Score": "1",
"body": "@g.d.d.c: Ah, good point. I was thinking more language-agnostically, since the most primitive implementation wouldn't do it efficiently. An interesting aside about the python <code>.add()</code> function from a google: http://indefinitestudies.org/2009/03/11/dont-use-setadd-in-python/"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T16:46:42.527",
"Id": "146",
"Score": "0",
"body": "@sova - Thanks for the link on the union operator. I hadn't ever encountered that and usually my sets are small enough they wouldn't suffer from the performance penalty, but knowing alternatives is always great."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T22:45:48.320",
"Id": "169",
"Score": "0",
"body": "@g.d.d.c also, the solution above does indeed rule out double-checks for multiples of both, it figures out the minimal frequency at which you can repeat the pattern for digits (up to the LCM of the two digits). Each valid multiple of 3, 5, or both, is \"checked\" (actually, not really checked, just added) only once."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-24T17:57:44.573",
"Id": "1741",
"Score": "0",
"body": "@g.d.d.c python's set is based on a hash table. It is not going to use a binary lookup. Instead it will do a hash table lookup."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-24T18:29:45.833",
"Id": "1744",
"Score": "0",
"body": "@sova, the conclusion in that blog post is wrong. Its actually measuring the overhead of profiling. Profile .add is more expensive then profiling |=, but .add is actually faster."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:23:56.613",
"Id": "24",
"ParentId": "2",
"Score": "8"
}
},
{
"body": "<p>I would do it like this:</p>\n\n<pre><code>total = 0\n\nfor i in range(3, end, 3):\n total += i\n\nfor i in range(5, end, 5):\n if i % 3 != 0: # Only add the number if it hasn't already\n total += i # been added as a multiple of 3\n</code></pre>\n\n<p>The basic approach is the same as g.d.d.c's: iterate all the multiples of 3, then 5. However instead of using a set to remove duplicates, we simply check that the multiples of 5 aren't also multiples of 3. This has the following upsides:</p>\n\n<ol>\n<li>Checking divisibility is less expensive than adding to a set.</li>\n<li>We build the total up incrementally, so we don't need a separate call to sum at the end.</li>\n<li>We got rid of the set, so we only need constant space again.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T15:24:15.257",
"Id": "3594",
"Score": "0",
"body": "do you think it would be faster or slow to allow the repetitive 5's to be added and then substract the 15's? we would lose `end/5` divisibility checks and it costs only `add/15` subtractions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T04:38:14.877",
"Id": "67",
"ParentId": "2",
"Score": "12"
}
},
{
"body": "<p>I would get rid of the <code>for</code> loops and use <code>sum</code> on generator expressions.</p>\n\n<pre><code>def solution_01(n):\n partialsum = sum(xrange(3, n, 3)) \n return partialsum + sum(x for x in xrange(5, n, 5) if x % 3)\n</code></pre>\n\n<p>Note that we're using <code>xrange</code> instead of <code>range</code> for python 2. I have never seen a case where this isn't faster for a <code>for</code> loop or generator expression. Also consuming a generator expression with <code>sum</code> <em>should</em> be faster than adding them up manually in a <code>for</code> loop.</p>\n\n<p>If you wanted to do it with sets, then there's still no need for <code>for</code> loops</p>\n\n<pre><code>def solution_01(n):\n values = set(range(3, n, 3)) | set(range(5, n, 5))\n return sum(values)\n</code></pre>\n\n<p>Here, we're just passing the multiples to the set constructor, taking the union of the two sets and returning their sum. Here, I'm using <code>range</code> instead of <code>xrange</code>. For some reason, I've seen that it's faster when passing to <code>list</code>. I guess it would be faster for <code>set</code> as well. You would probably want to benchmark though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T06:23:09.830",
"Id": "71",
"ParentId": "2",
"Score": "17"
}
},
{
"body": "<p>Using a generator is also possible :</p>\n\n<pre><code>print sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)\n</code></pre>\n\n<p>Note that intent is not really clear here. For shared code, I would prefer something like</p>\n\n<pre><code>def euler001(limit):\n return sum(n for n in range(limit) if n % 3 == 0 or n % 5 == 0)\n\nprint euler001(1000)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T14:37:09.013",
"Id": "275",
"ParentId": "2",
"Score": "8"
}
},
{
"body": "<p>The sum 3+6+9+12+...+999 = 3(1+2+3+...+333) = 3 (n(n+1))/2 for n = 333. And 333 = 1000/3, where \"/\" is integral arithmetic.</p>\n\n<p>Also, note that multiples of 15 are counted twice.</p>\n\n<p>So</p>\n\n<pre><code>def sum_factors_of_n_below_k(k, n):\n m = (k-1) // n\n return n * m * (m+1) // 2\n\ndef solution_01():\n return (sum_factors_of_n_below_k(1000, 3) + \n sum_factors_of_n_below_k(1000, 5) - \n sum_factors_of_n_below_k(1000, 15))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T15:19:22.627",
"Id": "3593",
"Score": "9",
"body": "this is obviously most efficient. i was about to post this as a one liner but i prefer the way you factored it. still, would `sum_multiples_of_n_below_k` be the appropriate name? they are not n's factors, they are its multiples"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-27T15:27:51.710",
"Id": "280",
"ParentId": "2",
"Score": "43"
}
},
{
"body": "<p>Well, this <em>is</em> an answer to a Project Euler question after all, so perhaps the best solution is basically a pencil-paper one.</p>\n\n<pre><code>sum(i for i in range(n + 1)) # sums all numbers from zero to n\n</code></pre>\n\n<p>is a triangular number, the same as</p>\n\n<pre><code>n * (n + 1) / 2\n</code></pre>\n\n<p>This is the triangular function we all know and love. Rather, more formally, </p>\n\n<pre><code>triangle(n) = n * (n + 1) / 2\n</code></pre>\n\n<p>With that in mind, we next note that the sum of the series</p>\n\n<pre><code>3, 6, 9, 12, 15, 18, 21, 24, ...\n</code></pre>\n\n<p>is 3 * the above triangle function. And the sums of</p>\n\n<pre><code>5, 10, 15, 20, 25, 30, 35, ...\n</code></pre>\n\n<p>are 5 * the triangle function. We however have one problem with these current sums, since a number like 15 or 30 would be counted in each triangle number. Not to worry, the inclusion-exclusion principle comes to the rescue! The sum of</p>\n\n<pre><code>15, 30, 45 ,60, 75, 90, 105, ...\n</code></pre>\n\n<p>is 15 * the triangle function. Well, if this so far makes little sense don't worry. Finding the sum of the series from 1 up to n, incrementing by k, is but</p>\n\n<pre><code>triangle_with_increments(n, k = 1) = k * (n/k) * (n/k + 1) / 2\n</code></pre>\n\n<p>with this, and the inclusion-exclusion principle, the final answer is but</p>\n\n<pre><code>triangle_with_increments(100, 5) + triangle_with_increments(100, 3) - triangle_with_increments(100, 15)\n</code></pre>\n\n<p>Wow. Who'da thunk? an n complexity problem suddenly became a constant time one. That's what I call optimization IMHO :P. But in all seriousness, Project Euler asks you to answer problems in really the lowest computational complexity possible. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T01:39:34.380",
"Id": "5978",
"ParentId": "2",
"Score": "15"
}
},
{
"body": "<p>The list comprehension one is an awesome solution, but making use of set is a lot faster:</p>\n\n<pre><code>from __future__ import print_function\n\ndef euler_001(limit):\n s1, s2 = set(range(0, limit, 3)), set(range(0, limit, 5))\n\n return sum(s1.union(s2))\n\nprint(euler_001(1000))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T16:42:50.027",
"Id": "75000",
"ParentId": "2",
"Score": "6"
}
},
{
"body": "<p>I used a slightly simpler method, but essentially did the same thing:</p>\n\n<pre><code>total = 0\n\nfor n in range(3,1000):\n if n % 3 == 0:\n total += n\n elif n % 5 == 0:\n total += n\n\n\nprint total\n</code></pre>\n\n<p>The <code>elif</code> makes sure that you only count any factor/divisor once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-04T00:38:58.953",
"Id": "262984",
"Score": "1",
"body": "(`did the same thing`: The order in which answers are shown is bound to change, and you might be referring to the question: please disambiguate with a quote or a hyperlink (e.g., from the `share`-link at the end of each post).)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T19:15:05.807",
"Id": "140425",
"ParentId": "2",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:04:27.573",
"Id": "2",
"Score": "56",
"Tags": [
"python",
"optimization",
"algorithm",
"programming-challenge"
],
"Title": "Project Euler problem 1 in Python - Multiples of 3 and 5"
} | 2 |
<p>I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write a nice 'main' function, especially since I'm doing small stuff that doesn't need separate classes.</p>
<p>What do you think about the following code? Is the main function necessary, or would you just write everything without functions? Is there a general consent on this in the Python world?</p>
<pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999
def find_multiples():
global numbers
for i in range(0,1000):
if i%3==0 or i%5==0:
numbers.append(i);
numbers = []
if __name__ == '__main__':
find_multiples()
print sum(numbers)
</code></pre>
| [] | [
{
"body": "<p>In most of the Python code I've ever seen, there is normally a main function defined that you call from the condition you put to establish the script was executed and not imported. I believe that's the standard way of doing things in Python, but I don't believe its actually a written rule anywhere, though that is how they do it in <a href=\"http://docs.python.org/library/__main__.html\">their docs as well</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-24T20:20:28.427",
"Id": "12902",
"Score": "8",
"body": "Lets state it clearly, what idiom this is, because all comments above are incorrectly formatted and this idiom is not visible: `if __name__ == \"__main__\":` (as stated on the page Mark Loeser linked to)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:19:20.217",
"Id": "8",
"ParentId": "7",
"Score": "34"
}
},
{
"body": "<p>Here's some superficial review. More for testing the site and some comment formatting than anything, but: do create main functions (helps us benchmarkers a lot) and do think that your module can be imported, so docstrings and local variables help. </p>\n\n<pre><code># Finds...\n###-^ Put this in a docstring\n\ndef find_multiples():\n \"\"\"Finds sum of all multiples of 3 and 5 from 0 to 999 \"\"\"\n###-^ This allows you to \"from x import find_multiples, help(find_multiples)\"\n numbers = []\n###-^ Avoid globals\n for i in xrange(1000):\n###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)\n if not (i % 3) or not (i % 5):\n###-^ Add spaces around operators, simplify\n###-^ the boolean/numeric checks\n numbers.append(i)\n###-^ Remove trailing ;\n return numbers\n\n###-^ Removed global\n\ndef main():\n###-^ Allows calling main many times, e.g. for benchmarking\n numbers = find_multiples()\n print sum(numbers)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T21:57:35.937",
"Id": "166",
"Score": "1",
"body": "`xrange(1000)` would suffice. Which version is more readable is arguable. Otherwise, excellent code review! Chapeau bas!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-08T17:51:51.517",
"Id": "19954",
"Score": "0",
"body": "I would be tempted (although perhaps not for such a small program) to move the print statement out of main, and to keep the main() function strictly for catching exceptions, printing error messages to stderr, and returning error/success codes to the shell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T14:53:40.477",
"Id": "117208",
"Score": "0",
"body": "Another reason for using a 'main function' is that otherwise all variables you declare are global."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:43:12.493",
"Id": "32",
"ParentId": "7",
"Score": "53"
}
},
{
"body": "<p>Usually everything in python is handled the <em>come-on-we-are-all-upgrowns</em> principle. This allows you to choose the way you want things to do. However it's best practice to put the <em>main-function</em> code into a function instead directly into the module.</p>\n\n<p>This makes it possible to import the function from some other module and makes simple scripts instantly programmable.</p>\n\n<p>However avoid the use of globals (what you did with <code>numbers</code>) for return values since this makes it difficult to execute the function a second time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T18:41:30.897",
"Id": "216",
"Score": "0",
"body": "\"...since this makes it difficult to execute the function a second time.\" Do you mean by this that before calling `find_multiples` a second time in a main function I would need to empty `numbers`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-08T09:37:41.567",
"Id": "1214",
"Score": "0",
"body": "@Basil exactly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:26:13.127",
"Id": "83",
"ParentId": "7",
"Score": "13"
}
},
{
"body": "<p>Here's how I would do it:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n\n for i in xrange(min, max):\n if i%3 and i%5:\n continue\n\n yield i\n\nif __name__ == '__main__':\n print sum(find_multiples())\n</code></pre>\n\n<p>This makes find_multiples a generator for the multiples it finds. The multiples no longer need to be stored explicitly, and especially not in a global. </p>\n\n<p>It's also now takes parameters (with default values) so that the caller can specify the range of numbers to search. </p>\n\n<p>And of course, the global \"if\" block now only has to sum on the numbers generated by the function instead of hoping the global variable exists and has remained untouched by anything else that might come up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-26T22:29:00.797",
"Id": "231",
"ParentId": "7",
"Score": "15"
}
},
{
"body": "<p>The UNIX Man's recommendation of using a generator rather than a list is good one. However I would recommend using a generator expressions over <code>yield</code>:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n return (i for i in xrange(min, max) if i%3==0 or i%5==0)\n</code></pre>\n\n<p>This has the same benefits as using <code>yield</code> and the added benefit of being more concise. In contrast to UNIX Man's solution it also uses \"positive\" control flow, i.e. it selects the elements to select, not the ones to skip, and the lack of the <code>continue</code> statement simplifies the control flow¹.</p>\n\n<p>On a more general note, I'd recommend renaming the function <code>find_multiples_of_3_and_5</code> because otherwise the name suggests that you might use it to find multiples of any number. Or even better: you could generalize your function, so that it can find the multiples of any numbers. For this the code could look like this:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n return (i for i in xrange(min, max) if any(i%x==0 for x in factors))\n</code></pre>\n\n<p>However now the generator expression is getting a bit crowded, so we should factor the logic for finding whether a given number is a multiple of any of the factors into its own function:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n def is_multiple(i):\n return any(i%x==0 for x in factors)\n\n return (i for i in xrange(min, max) if is_multiple(i))\n</code></pre>\n\n<hr>\n\n<p>¹ Of course the solution using <code>yield</code> could also be written positively and without <code>continue</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T14:55:39.270",
"Id": "117210",
"Score": "0",
"body": "I like your second version. Perhaps you could make it even more general and succinct by removing the `min`, `max` argument, and just letting it take an iterator argument. That way the remaindin program would be `sum(find_multiples(xrange(1000)))`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-26T22:55:19.263",
"Id": "238",
"ParentId": "7",
"Score": "25"
}
},
{
"body": "<p>Regarding the use of a <code>main()</code> function.</p>\n\n<p>One important reason for using a construct like this:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Is to keep the module importable and in turn much more reusable. I can't really reuse modules that runs all sorts of code when I import them. By having a main() function, as above, I can import the module and reuse relevant parts of it. Perhaps even by running the <code>main()</code> function at my convenience.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T10:22:13.827",
"Id": "267",
"ParentId": "7",
"Score": "6"
}
},
{
"body": "<p>Just in case you're not familiar with the generator technique being used above, here's the same function done in 3 ways, starting with something close to your original, then using a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>, and then using a <a href=\"http://docs.python.org/tutorial/classes.html#generator-expressions\" rel=\"noreferrer\">generator expression</a>:</p>\n\n<pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999 in various ways\n\ndef find_multiples():\n numbers = []\n for i in range(0,1000):\n if i%3 == 0 or i%5 == 0: numbers.append(i)\n return numbers\n\ndef find_multiples_with_list_comprehension():\n return [i for i in range(0,1000) if i%3 == 0 or i%5 == 0]\n\ndef find_multiples_with_generator():\n return (i for i in range(0,1000) if i%3 == 0 or i%5 == 0)\n\nif __name__ == '__main__':\n numbers1 = find_multiples()\n numbers2 = find_multiples_with_list_comprehension()\n numbers3 = list(find_multiples_with_generator())\n print numbers1 == numbers2 == numbers3\n print sum(numbers1)\n</code></pre>\n\n<p><code>find_multiples()</code> is pretty close to what you were doing, but slightly more Pythonic. It avoids the <code>global</code> (icky!) and returns a list.</p>\n\n<p>Generator expressions (contained in parentheses, like a tuple) are more efficient than list comprehensions (contained in square brackets, like a list), but don't actually return a list of values -- they return an object that can be iterated through. </p>\n\n<p>So that's why I called <code>list()</code> on <code>find_multiples_with_generator()</code>, which is actually sort of pointless, since you could also simply do <code>sum(find_multiples_with_generator()</code>, which is your ultimate goal here. I'm just trying to show you that generator expressions and list comprehensions look similar but behave differently. (Something that tripped me up early on.)</p>\n\n<p>The other answers here really solve the problem, I just thought it might be worth seeing these three approaches compared.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T17:38:27.180",
"Id": "299",
"ParentId": "7",
"Score": "6"
}
},
{
"body": "<p>Here is one solution using ifilter. Basically it will do the same as using a generator but since you try to filter out numbers that don't satisfy a function which returns true if the number is divisible by all the factors, maybe it captures better your logic. It may be a bit difficult to understand for someone not accustomed to functional logic.</p>\n\n<pre><code>from itertools import ifilter\n\ndef is_multiple_builder(*factors):\n \"\"\"returns function that check if the number passed in argument is divisible by all factors\"\"\"\n def is_multiple(x):\n return all(x % factor == 0 for factor in factors)\n return is_multiple\n\ndef find_multiples(factors, iterable):\n return ifilter(is_multiple_builder(*factors), iterable)\n</code></pre>\n\n<p>The <code>all(iterable)</code> function returns <code>true</code>, if all elements in the <code>iterable</code> passed as an argument are <code>true</code>.</p>\n\n<pre><code>(x % factor == 0 for factor in factors)\n</code></pre>\n\n<p>will return a generator with true/false for all factor in factors depending if the number is divisible by this factor. I could omit the parentheses around this expression because it is the only argument of <code>all</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T05:59:23.090",
"Id": "10314",
"ParentId": "7",
"Score": "1"
}
},
{
"body": "<p>I would keep it simple. In this particular case I would do:</p>\n\n<pre><code>def my_sum(start, end, *divisors):\n return sum(i for i in xrange(start, end + 1) if any(i % d == 0 for d in divisors))\n\nif __name__ == '__main__':\n print(my_sum(0, 999, 3, 5))\n</code></pre>\n\n<p>Because it is readable enough. Should you need to implement more, then add more functions.</p>\n\n<p>There is also an O(1) version(if the number of divisors is assumed constant), of course.</p>\n\n<p><strong>Note:</strong> In Python 3 there is no <code>xrnage</code> as <code>range</code> is lazy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-28T15:00:00.030",
"Id": "117212",
"Score": "1",
"body": "Nice and clear. Perhaps don't make an `end` argument which is included in the range. It's easier if we just always make ranges exclusive like in `range`. If we do that, we never have to think about what values to pass again :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T19:21:07.970",
"Id": "10325",
"ParentId": "7",
"Score": "3"
}
},
{
"body": "<p>Adding more to @pat answer, a function like the one below has no meaning because you can NOT re-use for similar tasks. (Copied stripping comments and docstring.)</p>\n\n<pre><code>def find_multiples():\n numbers = []\n for i in xrange(1000):\n if not (i % 3) or not (i % 5):\n numbers.append(i)\n return numbers\n</code></pre>\n\n<p>Instead put parametres at the start of your function in order to be able to reuse it. </p>\n\n<pre><code>def find_multiples(a,b,MAX):\n numbers = []\n for i in xrange(MAX):\n if not (i % a) or not (i % b):\n numbers.append(i)\n return numbers\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T13:12:33.337",
"Id": "70802",
"ParentId": "7",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "8",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:16:08.443",
"Id": "7",
"Score": "60",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Using separate functions for Project Euler 1"
} | 7 |
<p>I use <a href="https://codeigniter.com/" rel="nofollow noreferrer">CodeIgniter</a> at work, and one of our model files had a lot of subqueries in it. I originally had to manually write each subquery, and wondered if I could use active records instead.</p>
<p>So, to make my life easier, I made a subquery library for CodeIgniter.</p>
<p>I put it on the <a href="https://github.com/bcit-ci/CodeIgniter/wiki/Subqueries" rel="nofollow noreferrer">CodeIgniter Wiki</a>, but I never really had any one look over it. So, can you tell me if there is anything I should improve in this, or anything I really shouldn't be doing?</p>
<p>P.S. Feel free to use this if you wish.</p>
<p>P.P.S. <code>join_range</code> is a helper method for use with the answer to <a href="https://stackoverflow.com/questions/4155873/mysql-find-in-set-vs-in">this question</a>.</p>
<p>P.P.P.S. The latest version can be found <a href="https://github.com/NTICompass/CodeIgniter-Subqueries" rel="nofollow noreferrer">here</a>.</p>
<pre><code>class Subquery{
var $CI;
var $db;
var $statement;
var $join_type;
var $join_on;
function __construct(){
$this->CI =& get_instance();
$this->db = array();
$this->statement = array();
$this->join_type = array();
$this->join_on = array();
}
/**
* start_subquery - Creates a new database object to be used for the subquery
*
* @param $statement - SQL statement to put subquery into (select, from, join, etc.)
* @param $join_type - JOIN type (only for join statements)
* @param $join_on - JOIN ON clause (only for join statements)
*
* @return A new database object to use for subqueries
*/
function start_subquery($statement, $join_type='', $join_on=1){
$db = $this->CI->load->database('', true);
$this->db[] = $db;
$this->statement[] = $statement;
if(strtolower($statement) == 'join'){
$this->join_type[] = $join_type;
$this->join_on[] = $join_on;
}
return $db;
}
/**
* end_subquery - Closes the database object and writes the subquery
*
* @param $alias - Alias to use in query
*
* @return none
*/
function end_subquery($alias=''){
$db = array_pop($this->db);
$sql = "({$db->_compile_select()})";
$alias = $alias!='' ? "AS $alias" : $alias;
$statement = array_pop($this->statement);
$database = (count($this->db) == 0)
? $this->CI->db: $this->db[count($this->db)-1];
if(strtolower($statement) == 'join'){
$join_type = array_pop($this->join_type);
$join_on = array_pop($this->join_on);
$database->$statement("$sql $alias", $join_on, $join_type);
}
else{
$database->$statement("$sql $alias");
}
}
/**
* join_range - Helper function to CROSS JOIN a list of numbers
*
* @param $start - Range start
* @param $end - Range end
* @param $alias - Alias for number list
* @param $table_name - JOINed tables need an alias(Optional)
*/
function join_range($start, $end, $alias, $table_name='q'){
$range = array();
foreach(range($start, $end) AS $r){
$range[] = "SELECT $r AS $alias";
}
$range[0] = substr($range[0], 7);
$range = implode(' UNION ALL ', $range);
$sub = $this->start_subquery('join', 'inner');
$sub->select($range, false);
$this->end_subquery($table_name);
}
}
</code></pre>
<p><strong>Example Usage</strong></p>
<p>This query:</p>
<pre><code>SELECT `word`, (SELECT `number` FROM (`numbers`) WHERE `numberID` = 2) AS number
FROM (`words`) WHERE `wordID` = 3
</code></pre>
<p>would become:</p>
<pre><code>$this->db->select('word')->from('words')->where('wordID', 3);
$sub = $this->subquery->start_subquery('select');
$sub->select('number')->from('numbers')->where('numberID', 2);
$this->subquery->end_subquery('number');
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:50:27.920",
"Id": "42",
"Score": "1",
"body": "Why is $db an array?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:55:41.490",
"Id": "46",
"Score": "0",
"body": "@Time Machine: `$db` is an array because every time you call `start_subquery` it makes a new database object. This allows subqueries inside subqueries."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:45:43.230",
"Id": "113",
"Score": "0",
"body": "Can you give us an example usage ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T14:29:40.943",
"Id": "137",
"Score": "0",
"body": "@RobertPitt: I've added an example to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-07T16:57:25.660",
"Id": "7907",
"Score": "0",
"body": "If anyone's curious, the latest version of this is here: https://github.com/NTICompass/CodeIgniter-Subqueries"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T02:35:19.013",
"Id": "22573",
"Score": "0",
"body": "nice... anyway, can we do a subquery under the subquery? on the other word, can I have unlimited recursively subqueries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T13:20:26.657",
"Id": "22603",
"Score": "0",
"body": "@zfm: Yes you can! `start_subquery` keeps track of how many times it was called, so when `end_subquery` is called, it knows where to put the subquery. http://pastebin.com/KxfrHb1J"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T03:26:10.343",
"Id": "22623",
"Score": "0",
"body": "@Rocket: from what you wrote on pastebin, it was two subqueries on the same level. Is it possible to have something like `$sub2 = $sub->subquery...` so the result will be something like `SELECT * FROM A WHERE xxx IN (SELECT xxx FROM B WHERE yyy IN (SELECT ... ))`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T06:12:47.473",
"Id": "22624",
"Score": "0",
"body": "@zfm: The pastebin example will actually generate: `SELECT word, (SELECT number FROM (numbers) WHERE numberID = 2 AND ab IN (SELECT test FROM (testing) WHERE a = 12)) AS number FROM (words) WHERE wordID = 3` :-D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T06:15:47.503",
"Id": "22625",
"Score": "0",
"body": "@zfm: When you call `end_subquery` it nests it under the last opened `start_subquery`. So the example on pastebin *will* do what you want. :-D"
}
] | [
{
"body": "<p>I may be missing something here,\nBut to me it seems that you have a class that you pass a pre-built query into?</p>\n\n<p>I am thinking would it not be beneficial to have a subquery built the same way as the top level queries?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:28:14.020",
"Id": "68",
"Score": "0",
"body": "You're not passing in a pre-built query per se. `start_subquery` returns you (a reference to) CodeIgniter's database object. You can then call active query methods on that object. `end_subquery` gets the query from the db object, wraps it in `()` then adds it to the main query."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T09:13:29.730",
"Id": "94",
"Score": "1",
"body": "I see, I like this approach, Much better than Writing them yourself. reading through it properly now I have time, Im not sure there is much different you could do. A+ code, Have you considered putting the code up as an enhancement in the CI issue tracker?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T14:28:42.647",
"Id": "136",
"Score": "0",
"body": "I posted it on the CodeIgniter wiki."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:33:06.807",
"Id": "28",
"ParentId": "12",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "277",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-01-19T21:24:11.093",
"Id": "12",
"Score": "29",
"Tags": [
"php",
"mysql",
"codeigniter"
],
"Title": "CodeIgniter Active Record Subqueries"
} | 12 |
<p>So I've had a problem where I need to compare data in 2 different tables on two different servers. Now, I know MySQL supports <code>CHECKSUM TABLES</code>, but from my testing and understanding, it's not reliable across server instances and versions. </p>
<p>So I created this query:</p>
<pre><code>$part = '@CRC := MD5(CONCAT_WS(\'#\', COALESCE(`'.
implode('`, "#NULL#"), COALESCE(`', $this->_columns).
'`, "#NULL#")))';
$sql1 = "SELECT COUNT(*) AS cnt,
SUM(CONV(SUBSTRING({$part}, 1, 4), 16, 10)) as a1,
SUM(CONV(SUBSTRING(@CRC, 5, 4), 16, 10)) as a2,
SUM(CONV(SUBSTRING(@CRC, 9, 4), 16, 10)) as a3,
SUM(CONV(SUBSTRING(@CRC, 13, 4), 16, 10)) as a4,
SUM(CONV(SUBSTRING(@CRC, 17, 4), 16, 10)) as a5,
SUM(CONV(SUBSTRING(@CRC, 21, 4), 16, 10)) as a6,
SUM(CONV(SUBSTRING(@CRC, 25, 4), 16, 10)) as a7,
SUM(CONV(SUBSTRING(@CRC, 29, 4), 16, 10)) as a8
FROM `dbname`.`tablename`
WHERE `id` >= $min AND `id` <= $max ";
</code></pre>
<p>So basically, it's concatenating each row together (all the columns of each row more specifically) and then MD5ing them. Then it walks 4 hexbits at a time through that MD5 and sums them across all rows (4 hexbits to allow me to do huge tables without needing to worry about overflowing). Then, I just compare the result of this query on both tables to see if everything is the same.</p>
<p>By using this binary search, I am able to rather quickly narrow down where the changes are so that I can port them.</p>
<p>It's actually reasonably efficient, so I'm not too concerned about that. What I am concerned about is if this is even necessary. It's screaming to me "You're doing it wrong", but I can't figure out any cleaner method around it...</p>
<p>What are your thoughts?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:37:10.357",
"Id": "35",
"Score": "1",
"body": "It may be overkill for your problem but have you looked at MYSQL clusters to handle mirroring and distributing of data. It would offer other features that may be useful."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:38:21.553",
"Id": "37",
"Score": "0",
"body": "They need to be syncronized lazily. Basically pushing QC into Production. And the data volume prohibits (or at least makes it expensive) to dump and restore the entire dataset each cycle..."
}
] | [
{
"body": "<p>We use <a href=\"http://www.maatkit.org/doc/mk-table-checksum.html\"><code>mk-table-checksum</code></a>. </p>\n\n<p>It works really great in Master-Slave context where it also allows to sync differences in both directions depending on your choice.</p>\n\n<p>Saidly from what i've seen most people it for replication and i can't provide any copy/pasteable output but if you don't know it it's definitly worth looking into. If you know it i'd like to hear why it doesn't work for you.</p>\n\n<p>To get an overview over many tables you can use something like <code>mk-table-checksum host1 host2 | mk-checksum-filter</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T13:16:41.477",
"Id": "126",
"Score": "0",
"body": "The only issue that I have with that, is that it'll be hard to write a binary search using it. It does have chunk size, but it doesn't seem that I can specify the range of PK as well. So all it would tell me is if they differed. But looking there, the tool [mk-table-sync](http://www.maatkit.org/doc/mk-table-sync.html) would do it. But I need some custom work wrapped around it, so calling an external program is a last resort at best. Thanks though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T02:17:07.157",
"Id": "59",
"ParentId": "16",
"Score": "5"
}
},
{
"body": "<p>Simply run in MySQL <code>CHECKSUM TABLE 'yourtable'</code></p>\n\n<p>Or for PHP solution read\n<a href=\"http://www.softwareprojects.com/resources/programming/t-how-to-check-mysql-replication-databases-are-in-syn-1832.html\" rel=\"nofollow\">How to check MySQL Replication databases are in Sync</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T18:36:20.337",
"Id": "23086",
"ParentId": "16",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:28:43.283",
"Id": "16",
"Score": "9",
"Tags": [
"php",
"mysql",
"sql"
],
"Title": "Comparing data in 2 tables on different servers with CHECKSUM"
} | 16 |
<p>A while back, I reverse-engineered a checksum algorithm from an <a href="http://en.wikipedia.org/wiki/Massively_multiplayer_online_game" rel="noreferrer">MMO</a> used to check the validity of an item that's linked to chat (similar to <a href="http://en.wikipedia.org/wiki/World_of_Warcraft" rel="noreferrer"><em>WoW</em></a>). The idea is that if the checksum is invalid then the game client would ignore the link when clicked. Otherwise clicking on the item link in in-game chat would display the stat and attrib for that item.</p>
<pre><code>ushort16 CreateChecksum(const string &itemlink)
{
stringstream parseitemlink(itemlink);
uint32 hexform[ITEMLINKGROUPCOUNT] = {0};
uint32 hexsum = 0;
//Parse itemLink string into hexform array
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
parseitemlink >> hex >> hexform[i];
//sum all the itemlink group together
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
hexsum += hexform[i];
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
{
uint32 ebx = hexform[i], edi = ebx * i;
//if loop iteration is odd store MSB 2-bytes.
//Otherwise, store working hexgroup as is untouched
if (i & 0x01)
ebx = hexform[i] >> 16; // aka same as dividing hexform[i] by 65,536
// (hexform[i] / 65,536) + (hexform[i] * i) + hexsum -- for odd groups
// hexform[i] + (hexform[i] * i) + hexsum -- for even groups
ebx += edi + hexsum;
hexsum = ebx ^ hexform[i];
}
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
{
// the more familiar high-level form would be
// hexform[i]^2 + hexform[i] * hexsum
uint32 ecx = (hexform[i] + 1) * hexsum,
eax = ecx * hexform[i];
eax >>= 16;
eax += ecx;
hexsum = eax ^ hexform[i];
}
//return the lower 2-bytes of hexsum
//as the final checksum
return hexsum & 0xFFFF;
}//CreateChecksum
</code></pre>
<p>The format of the <code>itemlink</code> is comprised of a group of hexadecimal separated with a space in string format. It's passed into <code>main()</code> as an argument when the program is run.</p>
<p>Here's what an <code>itemlink</code>'s hex string might look like:</p>
<blockquote>
<pre><code>const string EXAMPLELINK = "36c6a 0 3f000a54 d0f1 0 0 0 0 0 0 20d0";
</code></pre>
</blockquote>
<p>Are there any code smells or readability issues in this code segment? Can any part(s) of it be improved?</p>
| [] | [
{
"body": "<p>The only things I can see having problems are your acronym variable names i.e. (eax, ecx, ebx, and edi) don't explain what the variables are storing clearly for someone not experienced with doing checksums.</p>\n\n<p>The other thing I can see for readability issues is your all lowercase variable names which are descriptive (ie parseitemlink) should be camelCased so I can tell the different words (ie parseItemLink). That's the only thing I can think of readability wise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:28:41.897",
"Id": "26",
"ParentId": "22",
"Score": "5"
}
},
{
"body": "<p>If you are using the standard library classes of the same name, I would give the following names the correct namespace qualifier: <code>std::string</code>, <code>std::stringstream</code>, <code>std::hex</code>.</p>\n\n<p>In C++, this works just as well, IMHO it's mildy more idiomatic.</p>\n\n<pre><code>uint32 hexform[ITEMLINKGROUPCOUNT] = {};\n</code></pre>\n\n<p><code>ebx</code>, <code>edi</code>, <code>ecx</code>, <code>eax</code> are not good variable names, if you can give them more meaningful names, then do.</p>\n\n<pre><code> uint32 ecx = (hexform[i] + 1) * hexsum,\n eax = ecx * hexform[i];\n</code></pre>\n\n<p>Personally, I think this is clearer:</p>\n\n<pre><code> uint32 ecx = (hexform[i] + 1) * hexsum;\n uint32 eax = ecx * hexform[i];\n</code></pre>\n\n<p>The comment is really bad because it talks about <code>hexform[i]^2 + hexform[i] * hexsum</code> whereas <code>ecx</code> gets the value <code>hexform[i] * hexsum + hexsum</code> and <code>eax</code> gets the value <code>hexform[i]^2 * hexsum + hexform[i] * hexsum</code>. I think the comment needs a pair of parentheses if the code is doing what you meant.</p>\n\n<p>To be robust, you should check whether the parse worked.</p>\n\n<pre><code>parseitemlink >> hex >> hexform[i];\n</code></pre>\n\n<p>You can trivially combine the first two for loops as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:13:40.510",
"Id": "978",
"Score": "0",
"body": "I guess the variable names come from a C++ 'translation' of an assembler routine. So, if you consider the assembler code as being the 'specification' then the names `eax,ecx` etc would be a good choice."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:17:35.187",
"Id": "979",
"Score": "1",
"body": "re: namespace qualifiers: If this code is going in a header file, I'd agree. But in a .cpp file, I'd personally prefer to see a `using` statement."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T11:23:28.103",
"Id": "1010",
"Score": "2",
"body": "@Roddy: Do you mean a using-declaration or a using-directive? I would be OK with sufficient using-declarations - although for the `std` namespace it seems barely worth it. I think that using-directives are only extremely rarely a good idea."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:35:29.030",
"Id": "30",
"ParentId": "22",
"Score": "10"
}
},
{
"body": "<ul>\n<li><p>Function and variable names in C++ are commonly camelCase or snake_case, while uppercase names are for user-defined types.</p>\n\n<p>If <code>ITEMLINKGROUPCOUNT</code> is a variable or a constant, then it should also follow camelCase or snake_case. All-caps naming is commonly used for macros, and the different words should be separated with underscores.</p></li>\n<li><p><code>uint32</code> is not standard C++ nor is it even C (which is <code>uint32_t</code>). Use <code>std::uint32_t</code> from <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\"><code><cstdint></code></a>. More info about that <a href=\"https://stackoverflow.com/questions/11786113/difference-between-different-integer-types\">here</a> and <a href=\"https://stackoverflow.com/questions/14883896/why-is-stduint32-t-different-from-uint32-t\">here</a>.</p></li>\n<li><p>Instead of this sum loop:</p>\n\n<pre><code>for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)\n hexsum += hexform[i];\n</code></pre>\n\n<p>use <a href=\"http://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> as a more clean and C++-like alternative:</p>\n\n<pre><code>uint32 hexsum = std::accumulate(hexform, hexform+ITEMLINKGROUPCOUNT, 0);\n</code></pre>\n\n<p>On another note, <code>hexsum</code> should be <em>initialized</em> here as this is where it's first used. Always keep variables as close in scope as possible.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T02:04:47.290",
"Id": "46344",
"ParentId": "22",
"Score": "9"
}
},
{
"body": "<p>It seems to me your code currently displays the fact that it was reverse engineered from assembly language a little more than I'd like.</p>\n\n<p>I'd try to rewrite it in a form closer to how you'd normally write C++ instead of basically just translating assembly language into C++ syntax, but retaining most of the assembly language flavor (up to, and still including, using the register names for your variables).</p>\n\n<p>For example, reading the input string and converting from strings to a vector of uint32 could be more like this:</p>\n\n<pre><code>class hex_word {\n uint32 val;\npublic:\n friend std::istream& operator>>(std::istream &is, hex_word &h) { \n return is >> hex >> h;\n }\n operator uint32() { return val; }\n};\n\nstd::vector<uint32> hexform{std::istream_iterator<hex_word>(parseitemlink),\n std::istream_iterator<hex_word>()};\n</code></pre>\n\n<p>The to add those up, you could use <code>std::accumulate</code>:</p>\n\n<pre><code>uint32 hexsum = std::accumulate(hexform, hexform+ITEMLINKGROUPCOUNT, 0);\n</code></pre>\n\n<p>Skipping ahead a little, your last loop could use <code>std::accumulate</code>:</p>\n\n<pre><code>struct f {\n uint32 operator()(uint32 accumulator, uint32 val) {\n uint32 c = (val+1)*accumulator; \n uint32 a = c * val;\n return ((a>>16)+c) ^ accumulator;\n }\n};\n\nreturn std::accumulate(hexform.begin(), hexform.end(), hexsum, f) * 0xffff;\n</code></pre>\n\n<p>I'm not sure this leads to any startling new insights or dramatic simplification of the code, but it still strikes me as rather easier to understand than with all the code mashed together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T03:53:31.883",
"Id": "46351",
"ParentId": "22",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "30",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T22:02:29.033",
"Id": "22",
"Score": "20",
"Tags": [
"c++",
"checksum"
],
"Title": "Custom checksum algorithm"
} | 22 |
<p>I'm generating CSV strings for various 3rd party utilities and this section of code gets repeated in many classes. Is there a better way to generate this string?</p>
<pre><code>public override string CsvString()
{
return (
string.Format("\u0022{0}\u0022,\u0022{1}\u0022,\u0022{2}\u0022,\u0022{3}\u0022,\u0022{4}\u0022,\u0022{5}\u0022,\u0022{6}\u0022,\u0022{7}\u0022,\u0022{8}\u0022,\u0022{9}\u0022,\u0022{10}\u0022,\u0022{11}\u0022,\u0022{12}\u0022,\u0022{13}\u0022",
this.BlockType, // 1, A_NAME
this.Tag, // 2, A_TAG
this.Description, // 3, A_DESC
this.InitialScan, // 4, A_ISCAN
this.AutoManual, // 5, A_SCAN
this.ScanTime, // 6, A_SCANT
this.IoDevice, // 7, A_IODV
this.IoAddress, // 8, A_IOAD
this.InitialAmStatus, // 9, A_IAM
this.AlarmPriority, // 10, A_PRI
this.AlarmEnable, // 11, A_ENAB
this.EnableOutput, // 12, A_EOUT
this.HistDescription, // 13, A_HIST_DESC
this.SecurityArea1 // 14, A_SECURITYAREA1
));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:02:53.407",
"Id": "56",
"Score": "0",
"body": "I would use a StringBuilder if this was for Java. There might be a C# equivalent?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:37:37.547",
"Id": "64",
"Score": "0",
"body": "@Jeremy Heiler, There is :) the exact same structure as well I believe"
}
] | [
{
"body": "<p>Use a <code>StringBuilder</code>:</p>\n\n<pre><code>sbuilder.AppendFormat(\"\\u0022{0}\\u0022,\\u0022{1}\\u0022,\\u0022{2}\\u0022,\\u0022{3}\\u0022,\\u0022{4}\\u0022,\\u0022{5}\\u0022,\\u0022{6}\\u0022,\\u0022{7}\\u0022,\\u0022{8}\\u0022,\\u0022{9}\\u0022,\\u0022{10}\\u0022,\\u0022{11}\\u0022,\\u0022{12}\\u0022,\\u0022{13}\\u0022\",\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n ).AppendLine();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:40:07.167",
"Id": "65",
"Score": "1",
"body": "I wonder if this is what `String.Format` uses under the hood?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T01:36:26.817",
"Id": "76",
"Score": "1",
"body": "Actually string.Format uses StringBuilder inside it (or so Reflector says), so there wouldn't memory/performance benefit in this specific case (one shot formatting of the string)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:10:42.423",
"Id": "39",
"ParentId": "36",
"Score": "10"
}
},
{
"body": "<p>Maybe something like this:</p>\n\n<pre><code>public static string MakeCsvLine(params string[] items)\n{\n return String.Format(\"\\u0022{0}\\u0022\",String.Join(\"\\u0022,\\u0022\",items));\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>On thinking about it might be better to use it to build up a string builder so:</p>\n\n<pre><code>public static void AddCsvLine(StringBuilder sb, params string[] items)\n{\n sb.AppendFormat(\"\\u0022{0}\\u0022\",String.Join(\"\\u0022,\\u0022\",items))\n .AppendLine();\n}\n</code></pre>\n\n<p>This would remove having to have long strings repeated all over the code.\nEdit: Made the funtion return the orginal result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T04:40:23.470",
"Id": "83",
"Score": "1",
"body": "You'd have to join on `\"\\u0022,\\u0022\"` and then also add \"\\u0022\" at the beginning and end to get the same result as the original."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:59:52.940",
"Id": "117",
"Score": "0",
"body": "@sepp2k Your right, I change the code to reflect that"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T03:00:06.093",
"Id": "65",
"ParentId": "36",
"Score": "6"
}
},
{
"body": "<p>I doubt you'll find a way of not listing all those properties without using reflection, but the following helps to eliminate that huge format string which is likely to become the source of bugs.</p>\n\n<pre><code>var properties = new Object[]\n{\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n}.Select(x => String.Format(\"\\u0022{0}\\u0022\", x));\n\nreturn String.Join(\",\", properties);\n</code></pre>\n\n<p>A couple of things to note:</p>\n\n<p>This is hardly an efficient way of doing it, but offers fairly maintainable code. If you have an extra property, just add it to the array.</p>\n\n<p>This will only work in .NET 4.0. In earlier versions, you'll have to call <code>ToArray()</code> after that call to <code>Select</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T15:15:50.553",
"Id": "141",
"Score": "0",
"body": "This is a much cleaner method and addresses the error prone format string. This made my life easier."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T21:30:33.510",
"Id": "520",
"Score": "2",
"body": "If you do `return \"\\u0022\" + String.Join(\"\\u0022,\\u0022\", properties) + \"\\u0022\"`, you can avoid the need for the Select projection altogether."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T07:56:17.143",
"Id": "74",
"ParentId": "36",
"Score": "19"
}
},
{
"body": "<p>As a variant of <a href=\"https://codereview.stackexchange.com/questions/36/is-there-a-better-way-to-build-my-csv-output-than-string-format/74#74\">Alex Humphrey's solution</a>, You could try this for improved performance:</p>\n\n<pre><code>var properties = new Object[]\n{\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n};\n\nvar builder = new StringBuilder(properties.Length * 6);\nforeach (var property in properties)\n{\n builder.Append('\"').Append(property).Append('\"').Append(',');\n}\nbuilder.Remove(builder.Length - 1, 1); // remove the last comma\n\nreturn builder.ToString();\n</code></pre>\n\n<p>But beware that this code is susceptible for failure if any of the properties contains a double quote. You should make sure they are escaped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-10T07:32:57.760",
"Id": "5274",
"ParentId": "36",
"Score": "2"
}
},
{
"body": "<p>in the new versions of C# you can use string interpolation to make it a little easier to code and know where the variables are going to be inserted into the string. all you do is put a $ before the opening quotation mark.</p>\n\n<p>Then the Return becomes this instead</p>\n\n<pre><code>return $\"\\u0022{this.BlockType}\\u0022,\\u0022{this.Tag}\\u0022,\\u0022{this.Description}\\u0022,\\u0022{This.InitialScan}\\u0022,\\u0022{this.AutoManual}\\u0022,\\u0022{this.ScanTime}\\u0022,\\u0022{this.IoDevice}\\u0022,\\u0022{this.IoAddress}\\u0022,\\u0022{this.InitialAmStatus}\\u0022,\\u0022{this.AlarmPriority}\\u0022,\\u0022{this.AlarmEnable}\\u0022,\\u0022{this.EnableOutput}\\u0022,\\u0022{this.HistDescription}\\u0022,\\u0022{this.SecurityArea}\\u0022\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-20T19:37:10.850",
"Id": "150419",
"ParentId": "36",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "74",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T22:56:59.883",
"Id": "36",
"Score": "23",
"Tags": [
"c#",
"csv",
"strings"
],
"Title": "Generating CSV strings for various 3rd party utilities"
} | 36 |
<p>I am currently developing a custom CMS being built on top of Codeigniter and was wondering if you can spot any flaws in my page fetching model code. The page fetching model is not entirely complete but the main functionality for retrieving a page is done, as well as retrieving modules assigned to a page (a module is really just a widget).</p>
<p>Can this model be better in some parts, perhaps in relation to the joins I am doing? although not really joins, but multiple queries to pull out bits of related info the pages like modules and media.</p>
<pre><code><?php
class Mpages extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function fetch_page($page_slug = 'home')
{
$db = $this->db;
$query =
$db
->where('page_status', 1)
->where('page_slug', strtolower($page_slug))
->get('pages')
->result_array();
$page_id = $query[0]['id'];
$query['modules'] =
$db
->select('modules.module_name, modules.module_slug, modules.id moduleid')
->where('page_id', $page_id)
->join('pages_modules lpm', 'moduleid = lpm.module_id')
->order_by('module_order', 'asc')
->get('modules')
->result_array();
/*$query['media'] =
$db
->select('lucifer_media.media_file_name, lucifer_media.media_file_extension, lucifer_media.media_directory')
->join('lucifer_pages_media', 'lucifer_pages_media.page_id = '.$page_id.'')
->get('lucifer_media')
->result_array();*/
if ($query) {
return $query;
} else {
return false;
}
}
public function fetch_navigation()
{
$result = $this->db->order_by("nav_order", "asc")->where('published', 1)->get('navigation')->result_array();
return $result;
}
public function fetch_layout($id)
{
$result = $this->db->where('id', $id)->get('layouts')->result_array();
return $result[0];
}
}
?>
</code></pre>
| [] | [
{
"body": "<p>I don't know Codeigniter so i can't comment on \"is this a propper model\". For my answer i'm just going to assume it is.</p>\n\n<p>It's not much code so i'm going to focus on some details: </p>\n\n<hr>\n\n<pre><code> public function __construct()\n {\n parent::__construct();\n }\n</code></pre>\n\n<p>Those 5 lines do absolutely nothing. I'd remove them. If you need a constructor later, add it later.</p>\n\n<hr>\n\n<pre><code> public function fetch_navigation()\n {\n $result = $this->db->order_by(\"nav_order\", \"asc\")->where('published', 1)->get('navigation')->result_array();\n return $result;\n }\n</code></pre>\n\n<p>This is a pretty hard to read (113 Chars in that line). I'd go for something like this (to say with your formatting from above)</p>\n\n<pre><code> public function fetch_navigation()\n {\n return $this->db\n ->order_by(\"nav_order\", \"asc\")\n ->where('published', 1)\n ->get('navigation')\n ->result_array();\n }\n</code></pre>\n\n<hr>\n\n<pre><code>$db = $this->db;\n</code></pre>\n\n<p>Seems unnecessary to create a local variable, those 6 extra chars shoudn't hurt. I needed to look twice to see where that variable is from and if its local because changes are made to it.</p>\n\n<hr>\n\n<p>So far those are really minor notes.</p>\n\n<h2>Unreachable code ?</h2>\n\n<pre><code>if ($query) {\n return $query;\n} else {\n return false;\n}\n</code></pre>\n\n<p>you are setting <code>$query['modules'] = ...</code> so even if that is null $query will at least contain</p>\n\n<pre><code>array(\"modules\" => null); \n</code></pre>\n\n<p>and that will always be true.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T03:56:21.497",
"Id": "81",
"Score": "0",
"body": "I appreciate you taking the time and effort to post a solution. As for the constructor, you need that to interface with the parent controller of the Codeigniter framework, otherwise I do believe you can't use pre-loaded libraries, models and other things loaded automatically in the core. Valid point about $this->db though. I've always done that, but have also wondered if assigning it to a $db variable was worth the extra effort and convoluted things. Thanks for the modules null tip as well."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T09:16:26.177",
"Id": "95",
"Score": "0",
"body": "Erm, `$db =& $this->db;` would be more beneficial would it not?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:03:55.910",
"Id": "97",
"Score": "0",
"body": "@RobertPitt Doing thats might be even harmful. Objects are passed \"as reference\" anyways and are hurtful php in general. There are only some very special cases where there is -any- benefit in using them"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:05:20.153",
"Id": "98",
"Score": "0",
"body": "@Dwayne If you just leave the lines out the constructor of the parent class will be called by php. The only thing that you shoudn't to is leave it completely empty (thats also why i don't like \"always having an constructor\" someone might leave it blank and break stuff"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:20:23.257",
"Id": "100",
"Score": "0",
"body": "@edorian, I believe that objects are only passed by reference as of PHP 5.2.0, as Codeigniter are sticking with the support of PHP 4 within CI 2.0, I think I was just sticking with the application standards in suggesting that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:24:06.767",
"Id": "102",
"Score": "2",
"body": "@RobertPitt Juding from http://www.php.net/manual/en/language.oop5.references.php this happed with the PHP 5.0 release - I don't have access quick to an really old 5.1.6 to test it but i'm pretty sure :) If not please let me know"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:36:16.800",
"Id": "108",
"Score": "0",
"body": "My apologies, i had got that information from a comment on the php site, so i had taken it was specifically that release, after readong some Zend papers i can see that it was part of the big release in 5.0. +1"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:46:36.930",
"Id": "114",
"Score": "0",
"body": "Great info guys, really insightful stuff. I ditched assigning the $this->db to a $db variable, didn't seem worth it to be honest. I want to keep my code as clean and efficient as possible."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:19:49.443",
"Id": "124",
"Score": "0",
"body": "@Dwayne, Keeping code clean starts here: http://framework.zend.com/manual/en/coding-standard.coding-style.html"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T23:19:30.210",
"Id": "170",
"Score": "0",
"body": "Thanks for the link Robert. I know of the Zend standard of coding style and conventions because I have to use it at work unfortunately. Here is the link to the Codeigniter style documentation, not as long, but still concise: http://codeigniter.com/user_guide/general/styleguide.html"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T02:34:27.033",
"Id": "61",
"ParentId": "48",
"Score": "4"
}
},
{
"body": "<p>aaaah, a CodeIgniter fella :-)</p>\n\n<p>I'm just working on a CI project myself and already implemented some of the <strong>optimization</strong> you could use for your CMS as well... so let's have a look:</p>\n\n<ol>\n<li><p>for as little <strong>overhead</strong> as possible, try implementing <strong>lazy-loading</strong> of your files (libraries, models...)</p></li>\n<li><p>for <strong>caching</strong> purposes, you can use KHCache - a library that allows you to cache parts of the website instead of full page</p></li>\n<li><p>instead of always doing $this->db->..., you can create a <strong>helper function</strong>, for instance \"function _db()\" and then simply do _db()->where...</p></li>\n<li><p>also, you can optionally create a helper function to give you the <strong>results array</strong> automatically, so ->result_array() will not be neccessary anymore: function res() {} ... $query = res(_db()->where...);</p></li>\n</ol>\n\n<hr>\n\n<p>now, for the <strong>code</strong> :-)</p>\n\n<pre><code>$query = \n $db\n ->where('page_status', 1)\n ->where('page_slug', strtolower($page_slug))\n ->get('pages')\n ->result_array();\n\n$page_id = $query[0]['id'];\n</code></pre>\n\n<p>here, you seem to be selecting <strong>all values from DB</strong>, while in need of a single first ID - try limiting number of results or this will create overhead in your database</p>\n\n<pre><code>$db->where...->limit(1);\n</code></pre>\n\n<hr>\n\n<p>the second query could probably use a <strong>LEFT JOIN</strong> instead of a regular JOIN, although I leave it to you to decide (the JOIN approach might not list everything you need)</p>\n\n<pre><code>$db-select...->join('pages_modules lpm', 'moduleid = lpm.module_id', 'left')\n</code></pre>\n\n<hr>\n\n<p>I guess that's all... just remember to put correct <strong>indexes</strong> on your SQL fields and use the <strong>EXPLAIN</strong> statement to check for bottlenecks</p>\n\n<p><em><strong>good luck!</em></strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:43:12.693",
"Id": "457",
"Score": "0",
"body": "and since I can't post links in answers due to low rating, here they are - lazy load: http://codeigniter.com/forums/viewthread/134605/"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:43:47.763",
"Id": "458",
"Score": "0",
"body": "you can find KHCache here: http://codeigniter.com/forums/viewthread/69843/"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:45:12.097",
"Id": "459",
"Score": "0",
"body": "and at last, EXPLAIN statement from MySQL manual: http://dev.mysql.com/doc/refman/5.0/en/explain.html ... I'd be delighted if you accepted this answer if you found it useful, so I can get rid of these link limitations :-D"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T12:15:24.210",
"Id": "667",
"Score": "0",
"body": "instead of a helper function why not `$db =& $this->db` and then do `$db->select()...`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T13:34:10.913",
"Id": "671",
"Score": "0",
"body": "Robert - to save time... _db()->select is quicker and requires only 1 line of code, while as with your solution, you need to write more of the same code every time (which could also change in the future, so you'd need to do extensive search/replaces in all files)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:41:24.583",
"Id": "289",
"ParentId": "48",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:51:36.533",
"Id": "48",
"Score": "7",
"Tags": [
"php",
"codeigniter",
"mvc"
],
"Title": "Critique My Codeigniter Custom CMS Pages Model"
} | 48 |
<p>Here's my <code>bootstrap.php</code> for my PHP/MySQL/Doctrine app. It's my first PHP app so I'm interested in learning from the experience of others how this could be improved - security-wise, performance-wise, or otherwise.</p>
<pre><code>//-------------------------------------------------------------------------
// Define global constants
define('ROOT_PATH', dirname(__FILE__) . '/');
define('URL_BASE', 'http://localhost/myapp/public/');
define('LIB_PATH', 'C:\\wamp\\www\\lib\\');
define('OPENID_PATH', 'C:\\wamp\www\\lib\\lightopenid.git\\openid.php');
//-------------------------------------------------------------------------
// Bootstrap Doctrine.php, register autoloader, specify
// configuration attributes and load models.
require_once(LIB_PATH . 'doctrine12/lib/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
//-------------------------------------------------------------------------
// Define database connection
$dsn = 'mysql:dbname=mydb;host=127.0.0.1';
$user = 'xxx';
$password = 'yyy';
$dbh = new PDO($dsn, $user, $password);
$conn = Doctrine_Manager::connection($dbh);
//-------------------------------------------------------------------------
// Set defaults
$manager->setAttribute(Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS,
array('type' => 'string', 'length' => 255, 'notnull' => true));
$conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
// Don't load a model until it's needed (causes problems when this is on)
//$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
//-------------------------------------------------------------------------
// Import model objects
Doctrine_Core::loadModels(ROOT_PATH . 'app/models/generated'); // have to load base classes first
Doctrine_Core::loadModels(ROOT_PATH . 'app/models');
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T01:30:57.793",
"Id": "73",
"Score": "0",
"body": "How different is this from the default template? Can you link to it?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T03:30:06.800",
"Id": "80",
"Score": "0",
"body": "@TryPyPy: http://www.doctrine-project.org/projects/orm/1.2/docs/manual/getting-started%3Aimplementing%3Abootstrap-file/en"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T23:26:23.510",
"Id": "496526",
"Score": "0",
"body": "@ZoranJankov I have rejected your suggested edit because it does not improve the quality of the title. A title must uniquely describe what the script does -- not what it is & what it is comprised of."
}
] | [
{
"body": "<p>Here are a few lines that might be useful to add if you would like to use these options:</p>\n\n<pre><code>/**\n * Needed for SoftDelete to work\n */\n$manager->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);\n\n/**\n * Tell doctrine to look for custom ___Table classes in the models folder\n */\n$manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, true);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T01:48:02.827",
"Id": "55",
"ParentId": "49",
"Score": "7"
}
},
{
"body": "<p>where you state <strong>Define global constants</strong> your not defining your directories with the correct slashes for the Operating system</p>\n\n<p>You can use <code>/</code> slashes fluently on your application as both unix and windows supports them but if you really want to be on the safe side then you should use <code>DIRECTORY_SEPARATOR</code></p>\n\n<p>As Doctrine 2.0 is only supporting PHP 5.3.0 you can replace <code>dirname(__FILE__)</code> with <code>__DIR__</code></p>\n\n<p>I would also create a constant called <code>DS</code> which would normally be created in a constants file, and should be one of the first included.</p>\n\n<p>I would convert the above to:</p>\n\n<pre><code> define('ROOT_PATH' , __DIR__);\n define('URL_BASE' , 'http://localhost/myapp/public/');\n define('LIB_PATH' , realpath(\"../../path/to/libs\")); //Unix / Windows\n define('OPENID_PATH', realpath(\"../../path/to/openid\"));//Unix / Windows\n</code></pre>\n\n<p>And then change the <code>loadModels</code> accordingly?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T15:10:13.040",
"Id": "675",
"Score": "0",
"body": "Excellent information, thanks! Just one point of clarification - you never stated what the `DS` constant is or where you would use it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T15:50:28.310",
"Id": "676",
"Score": "1",
"body": "sorry, the `DS` Constants is a shortor version for `DIRECTORY_SEPARATOR` and you would then build your paths like so: `LIB_ROOT . DS . \"openid\" . DS . \"openid.class.php\"` to save line space."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T14:48:29.900",
"Id": "414",
"ParentId": "49",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:52:25.113",
"Id": "49",
"Score": "6",
"Tags": [
"php",
"mysql",
"doctrine"
],
"Title": "PHP/Doctrine bootstrap for review"
} | 49 |
<p>I'm making a "guess that tune" game in Visual Basic 6 that is supposed to play each song in a random order:</p>
<pre><code>' from frmGuessGame.frm
Private Sub Swap(ByRef Value1 As Variant, ByRef Value2 As Variant)
Dim Temporary As Variant
Temporary = Value1
Value1 = Value2
Value2 = Temporary
End Sub
Private Sub ShuffleList()
Dim LoopCtr As Integer, SwapWith As Integer
For LoopCtr = LBound(InnerPlaylist) To UBound(InnerPlaylist)
SwapWith = (Rnd * (UBound(InnerPlaylist) - LBound(InnerPlaylist))) + LBound(InnerPlaylist)
Swap InnerPlaylist(LoopCtr), InnerPlaylist(SwapWith)
Next
End Sub
</code></pre>
<p>My initialization function does include the <code>Randomize</code> statement, so it should be a good, even shuffle.</p>
<pre><code>' from mdiMain.frm
Private Sub MDIForm_Load()
'initialize pseudo-random number generator
Randomize
frmMusiguess.Show
frmSplash.Show
End Sub
</code></pre>
<p>I'm not sure, however, that this is the best way to do it. Am I on the right track?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:55:48.870",
"Id": "70",
"Score": "0",
"body": "Aside: [My question from the proposal](http://area51.stackexchange.com/proposals/11464/code-review/25308#25308). I actually wrote this code years ago (2004) before I knew any better."
}
] | [
{
"body": "<p>I would probably do something like this:</p>\n\n<p>I don't know VB so this is pseudo code.</p>\n\n<pre><code>Private Function Shuffle(playlist) as Playlist\n{\n Dim PlayList as NewPlayList\n Dim RandomIndex as Integer\n\n while(playlist has elements)\n {\n RandomIndex = (Random number between lowerbound and upperbound)\n\n remove song at RemoveIndex from playlist\n add removed song to NewPlaylist\n }\n\n return NewPlayList\n}\n</code></pre>\n\n<p>The issue I have with the way you did it is that there is ample opportunity to undo the shuffle. For example, Suppose you are at index 1 and the random number is 2. You swap 1 and 2. Now suppose you are at index 2 and the random number is 1. Now you just undid the shuffle that you preformed in the previous iteration. Also, I don't like the use of the global variable InnerPlaylist. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T02:12:36.947",
"Id": "57",
"ParentId": "50",
"Score": "5"
}
},
{
"body": "<p>No. <strong>Your shuffle will <em>not</em> be random.</strong> You are stepping through each card and swapping it with another random card. This is a common bug found in many shuffling algorithms. </p>\n\n<p>To illustrate why your shuffle is not random, let's assume you are shuffling three songs (1, 2, 3). There are six combinations of three song (123, 132, 213, 231, 321, 312). If your shuffle was random, each of these combinations should appear with equal probability. So if you run your shuffle algorithm 600,000 times, each combination should appear roughly 100,000 times each.</p>\n\n<p>But it doesn't. When you run your shuffle algorithm 600,000 times (as written), you will see results similar to this: </p>\n\n<p><img src=\"https://i.stack.imgur.com/f1Ri6.png\" alt=\"Shuffle results\"></p>\n\n<p>To understand <em>why</em> your implementation produces biased results, read this article on Coding Horror: <a href=\"http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html\" rel=\"noreferrer\">The Danger of Naïveté</a>.</p>\n\n<p>What you want is a <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\"><strong>Fisher-Yates shuffle</strong></a> where you swap the current card with any of the <em>remaining</em> cards (or itself). </p>\n\n<p>Here it is in pseudo code for an in-place shuffle:</p>\n\n<pre><code>To shuffle an array a of n elements:\n for i from n − 1 downto 1 do\n j ← random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n</code></pre>\n\n<p>There are other types of Fisher-Yates shuffles listed here: Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\">Fisher–Yates shuffle</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T15:08:37.003",
"Id": "98",
"ParentId": "50",
"Score": "35"
}
},
{
"body": "<p>For a game with no serious consequences you could just run it a bunch of times and see if it seems satisfying. For something where there are serious consequences to it not being a good enough shuffle I would think that you shouldn't wonder if a shuffle is good enough, you need to have theory that tells you it is good enough (possibly under assumptions you are happy with). Related to this Vol. 2 of The Art of Computer Programming in its first chapter gives lots of information about generating random numbers, AND how to test them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T18:02:08.187",
"Id": "134",
"ParentId": "50",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "98",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T00:54:38.853",
"Id": "50",
"Score": "19",
"Tags": [
"algorithm",
"vb6",
"random",
"shuffle"
],
"Title": "Shuffling algorithm for a \"guess that tune\" game"
} | 50 |
<p>I've implemented a PID controller, but seeing as I'm not an expert in control theory, have I missed any edge cases?</p>
<pre><code>public class PIDController
{
public enum PIDMode
{
Manual,
Auto,
}
public enum PIDAction
{
Indirect,
Direct,
}
public PIDMode Mode { get; set; }
public PIDAction Action { get; set; }
public double Proportional { get; set; }
public double Integral { get; set; }
public double Derivative { get; set; }
public double Minimum { get; set; }
public double Maximum { get; set; }
public double DeltaMinimum { get; set; }
public double DeltaMaximum { get; set; }
private double _ProportionalTerm;
private double _Integrator;
private double _Derivator;
public double Setpoint { get; set; }
private double _Feedback;
public double Feedback
{
get
{
return _Feedback;
}
}
public void Calculate(double Input, long Time)
{
double output;
// Compute the error value
double Error = Setpoint - Input;
if (Mode == PIDMode.Auto)
{
if (Action == PIDAction.Direct)
Error = 0 - Error;
// Compute the proportional component
_ProportionalTerm = 1000.0f * (Error - _Derivator) / (double)Time;
// Compute the integrator component, clamped to min/max delta movement
_Integrator += (float)Error * (float)Time / 1000.0f;
if (_Integrator < DeltaMinimum)
_Integrator = DeltaMinimum;
if (_Integrator > DeltaMaximum)
_Integrator = DeltaMaximum;
// Add the proportional component
output = (Proportional * Error);
// Add the integral component
output += Integral * _Integrator;
// Add the derivative component
output += Derivative * _ProportionalTerm;
// Clamp output to min/max
if (output < Minimum)
output = Minimum;
if (output > Maximum)
output = Maximum;
}
else
{
output = Input;
}
// Store values
_Derivator = Error;
// Returns the result
_Feedback = output;
}
}
</code></pre>
| [] | [
{
"body": "<p>It looks reasonable, but I don't see why you need to make the Proportional term a member of the class, it doesn't need to be saved, at best it might make sense to be able to query it with a get, but a set seems misleading.</p>\n\n<p>I'd be reluctant to allow public setting of the Integral and Derivatives too, querying them might be useful, but letting users of the class set it seems odd.</p>\n\n<p>Forcing the scaling by 1000.0 seems arbitrary and inflexible too, this would make sense to expose as a settable constant in my view.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T19:46:19.540",
"Id": "113",
"ParentId": "72",
"Score": "9"
}
},
{
"body": "<p>Having a time parameter for each iteration of a PID loop would imply that it may safely be run at a variable frequency; while there are occasions when that may be unavoidable, and there are ways of handling such variations safely, I would expect most conditions that would cause the sampling loop time to vary would also create considerable 'noise' in the D term, limiting its usefulness.</p>\n\n<p>One approach I've not seen discussed is replacing the PID loop with an IIR filter. A PID loop is a special case of an IIR filter, but with the second tap's time constant being infinitesimal, and the third tap's time constant being nearly infinite. The difference between the first two taps represents the delta, and the third tap represents the integral. Using more \"realistic\" time constants for the filter taps yields results which differ from a \"pure\" IIR filter, but in ways that are apt to be beneficial. Using a short-but-not-infinitesimal time constant on the second stage allows one to reduce the amount of high-frequency noise. Using a finite time constant on the third term allows one to effectively limit the \"wind-up\". Although going beyond three stages would make it harder to analyze system behavior, it may allow the PID system to better deal with various delay factors in the real-world system being controlled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T05:29:17.930",
"Id": "42974",
"Score": "0",
"body": "I'd be interested if you know of any more discussion on expressing a PID as an IIR."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T14:55:32.790",
"Id": "43011",
"Score": "0",
"body": "@detly: I don't think I've seen such discussions since I wrote the above. If one figures out the frequency response of the integral and derivative terms, and those of the FIR filter described, the PID response matches the limiting case of the FIR as the second-stage time constant approaches zero and the third stage approaches infinity. Given that there's a limit to the frequencies of interest in the D term, and the amount of windup that's desired on the I term, I find it curious that the FIR model isn't used more."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-28T21:29:42.190",
"Id": "386",
"ParentId": "72",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T06:31:36.730",
"Id": "72",
"Score": "13",
"Tags": [
"algorithm",
"c#"
],
"Title": "Implementation of a PID Controller"
} | 72 |
<p>Is this the best way to implement this pattern in C#?</p>
<pre><code>public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-07T02:53:33.217",
"Id": "18504",
"Score": "8",
"body": "[Singleton is an antipattern](http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:00:28.890",
"Id": "25102",
"Score": "0",
"body": "Please watch: [\"Global State and Singletons\"](http://www.youtube.com/watch?v=-FRm3VPhseI)"
}
] | [
{
"body": "<p>I always use this solution if I have to implement a Singleton in C#</p>\n\n<pre><code>public sealed class Logging\n {\n static Logging instance = null;\n static readonly object lockObj = new object();\n\n private Logging()\n {\n }\n\n public static Logging Logger\n {\n get\n {\n lock (lockObj)\n {\n if (instance == null)\n {\n instance = new Logging();\n }\n return instance;\n }\n }\n }\n\n}\n</code></pre>\n\n<p>Compared to your solution this is threadsafe and uses a lazy-creation method. (The object is only instantiated if actually needed)</p>\n\n<p>The eager vs. lazy creation isn't really worth a discussion in this example, but I would whenever possible use the thread-safe implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T00:38:26.337",
"Id": "172",
"Score": "4",
"body": "This is a very bad solution to the problem, it uses a lock on every single access. Which has a very high overhead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T12:03:53.763",
"Id": "8549",
"Score": "0",
"body": "@Martin: The overhead is not that onerous unless you say `Logging.Logger.DoThis()` and `Logging.Logger.DoThat()` every time. Which i'd prefer to avoid that anyway, as (1) it pretty much entrenches the Logging class, making it even more of a pain to swap out for something else later, and (2) `Logging.Logger` will, by the definition of a singleton, always return the same thing, so re-getting it each time is silly. Oh, and (3) it's repetitive, and i hate repetition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T13:41:46.150",
"Id": "8556",
"Score": "0",
"body": "You're using a singleton now, but later you may wish to change your singleton so, for example, it swaps out to a new logger when the file gets full - so I tend to try to avoid caching the singleton. There's no point keeping hundreds of references to something around when you can centralise access in one place easily and efficiently with e.g. double checked locking"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:07:05.410",
"Id": "80",
"ParentId": "79",
"Score": "6"
}
},
{
"body": "<p>I use <a href=\"http://csharpindepth.com/Articles/General/Singleton.aspx\">Jon Skeet's version</a> of a <em>thread safe</em> Singleton with fully lazy instantiation in C#: </p>\n\n<pre><code>public sealed class Singleton\n{\n // Thread safe Singleton with fully lazy instantiation á la Jon Skeet:\n // http://csharpindepth.com/Articles/General/Singleton.aspx\n Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n return Nested.instance;\n }\n }\n\n class Nested\n {\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static Nested()\n {\n }\n\n internal static readonly Singleton instance = new Singleton();\n }\n}\n</code></pre>\n\n<p>It works wonders for me! It's really easy to use, just get the instance from the Instance property like so; <code>SingletonName instance = SingletonName.Instance;</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:55:35.417",
"Id": "115",
"Score": "0",
"body": "Wouldn't GetInstance be more appropriate for what is essentially an accessor? Or is that convention different in C#?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:08:01.097",
"Id": "118",
"Score": "5",
"body": "I think that Instance is sufficient enough, but I suppose YMMV."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T13:24:39.443",
"Id": "128",
"Score": "0",
"body": "Is there some specific benefit from creating a nested class?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T13:40:42.037",
"Id": "131",
"Score": "0",
"body": "@AnnaLear: I believe that Jon Skeet explains it better himself than I can at the moment, check out the link. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T15:55:22.850",
"Id": "143",
"Score": "3",
"body": "The nested class is what makes it lazy. The runtime will not instantiate the Singleton instance until Singleton.Instance is called. That way, if you have other static members or something on Singleton, you can access them without creating the Singleton instance."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T11:37:19.320",
"Id": "182",
"Score": "9",
"body": "I'd like to encourage everyone to read Jon Skeet's article (following the link Zolomon has provided), as it coverts almost all answers in this topic, listing all their pros and cons."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T17:43:24.333",
"Id": "468",
"Score": "2",
"body": "This is also thread safe."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:08:52.170",
"Id": "1154",
"Score": "0",
"body": "That's pretty darn clever. But I had to read Jon's article to actually understand what's going on. But the next guy that maintains your code probably won't get all the trickery just by looking at it. I'd add a comment that links to Jon's article."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T09:21:19.930",
"Id": "1158",
"Score": "0",
"body": "@AngryHacker: That's what I do in my implementations. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T03:54:40.963",
"Id": "6780",
"Score": "1",
"body": "How would you use this in tests - what if you needed to mock it or parts of it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T11:54:43.450",
"Id": "8546",
"Score": "7",
"body": "@Chris: You wouldn't. That's part of why singletons suck -- they're essentially hidden global state, making it nearly impossible to reliably test code that contains or uses them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T15:44:56.653",
"Id": "8567",
"Score": "0",
"body": "@cHao +1 good job on pointing out the suckiness of singletons!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T16:33:22.267",
"Id": "8572",
"Score": "0",
"body": "It's actually not all that bad. Have the singleton class implement an interface and mock that interface. It's not like any version of the class is static, just the one instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T17:56:05.910",
"Id": "8575",
"Score": "1",
"body": "@Jesse: Only problem is, code that uses singletons almost always ends up going to get them itself. There end up being calls to `Singleton.Instance` scattered all over the place. You can't easily mock your way around that. If code expected to be passed a Singleton that it'd use, then sure, you could easily mock it. At which point you have dependency injection, though, and no longer need a singleton."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-31T07:48:49.587",
"Id": "8627",
"Score": "0",
"body": "@cHao Not quite true; some pay-for test products can mock static classes, and Pex can mock static methods: http://research.microsoft.com/en-us/projects/pex/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-26T20:21:45.047",
"Id": "19363",
"Score": "0",
"body": "@ChrisMoschini : Yes, you can Mole it out, Pex it out or even use the old TypeMock isolator but when you need to replace it then.. CTRL-SHIFT-H... :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-09T22:23:48.860",
"Id": "44316",
"Score": "1",
"body": "Try googling \"ambient context\" for some good ideas of how to have your single return an abstract type which has a default concrete value at runtime but which would be easily replaceable for testing."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T10:15:28.753",
"Id": "81",
"ParentId": "79",
"Score": "74"
}
},
{
"body": "<p>I always use this, it allows lazy initialisation of generics, instead of creating a new singleton class for each type of singleton I want. It's also threadsafe but does not use locks on every access.</p>\n\n<pre><code>public static class Singleton<T> where T : class, new()\n{\n private T instance = null;\n\n public T Instance\n {\n get\n {\n if (instance == null)\n Interlocked.CompareExchange(ref instance, new T(), null);\n\n return instance;\n }\n }\n}\n</code></pre>\n\n<p>If you're unfamiliar with the interlocked class, it performs atomic operations in a manner which is often quicker than a lock. Three possible cases:</p>\n\n<p>1) <strong>First access by a single thread</strong>. Probably roughly the same performance as the obvious method using a lock</p>\n\n<p>2) <strong>First access by many threads at the same time</strong>. Many threads might enter the interlocked exchange, in which case several items may get constructed but only 1 will \"win\". So long as your constructor has no global side effects (which is really shouldn't) behaviour will be correct. Performance will be slightly less than a lock, because of multiple allocations, but the overhead is small and this is a very rare case.</p>\n\n<p>3) <strong>Later accesses</strong>. No locking or interlocked operations, this is pretty much optimal and is obviously the majority case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T03:59:44.783",
"Id": "178",
"Score": "0",
"body": "+1 for good solution, but the problem #2 requiring your Constructors to have no side effects has always scared me off this approach."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T13:41:12.393",
"Id": "184",
"Score": "1",
"body": "How often do your constructors have side effects? I've always considered that to be a pretty bad code smell. Especially in multithreaded code!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T15:04:01.323",
"Id": "189",
"Score": "0",
"body": "Additionally, your constructor can have side effects so long as they're threadsafe and do not assume that this is the only instance to be created. Remember, several instances may be created but only one will \"win\", so if you do have side effects they'd better be implemented properly!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T11:58:22.257",
"Id": "8548",
"Score": "0",
"body": "@Martin: Isn't the whole point of singletons that only one instance can be created? It'd seem to me that relying on that assumption is a quite reasonable thing to do..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-28T13:45:44.977",
"Id": "8557",
"Score": "0",
"body": "@cHao true, but as I said before I consider any side effects in a constructor which leak beyond the instance being constructed one of the worst code smells, doubly so in multithreaded code. Assuming we agree on this, there's no way constructing 2 instances can have any external affect on your program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T07:53:23.560",
"Id": "29944",
"Score": "1",
"body": "-1, Not thread safe (constructor could be called several times), thus defeating the purpose of a singleton."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T12:55:00.193",
"Id": "91",
"ParentId": "79",
"Score": "18"
}
},
{
"body": "<p>I use a pattern similar to one already posted, but with the following difference:</p>\n\n<pre><code>public sealed class Logging\n{\n static Logging instance = null;\n static readonly object lockObj = new object();\n\n private Logging()\n {\n }\n\n public static Logging Logger\n {\n get\n {\n **if (instance == null)**\n {\n lock (lockObj)\n {\n if (instance == null)\n {\n instance = new Logging();\n }\n\n }\n }\n return instance;\n }\n }\n</code></pre>\n\n<p>}</p>\n\n<p>The reason being that it avoids calling lock every time, which can help you with performance. So you check for null, then, if it is null, lock it. Then you have to check for null again (because someone may have come in right that second) but then you should be ok. That way, you'll only hit the lock the first time (or two), and blow past it without locking the rest of the time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T10:33:02.550",
"Id": "181",
"Score": "0",
"body": "Great example.I only have to add the name: it is called \"Double-checked Locking\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T13:30:32.933",
"Id": "183",
"Score": "1",
"body": "The return statement needs to be outside of the first if(instance==null) statement. Otherwise it will not return an instance if the instance already exists."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T13:56:15.487",
"Id": "185",
"Score": "0",
"body": "@Dan quite correct, my mistake."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T03:57:08.000",
"Id": "123",
"ParentId": "79",
"Score": "9"
}
},
{
"body": "<p>Dependency Injection containers like Unity support a singleton concept. Unity is from Microsoft (and is open source), but there are <a href=\"http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx\" rel=\"nofollow\">lots of open source DI containers</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-26T23:58:53.863",
"Id": "248",
"ParentId": "79",
"Score": "4"
}
},
{
"body": "<p>If you are using .NET 4.0, you can take advantage of the <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\">System.Lazy</a> class. It ensures the instance is created only once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-22T01:05:56.707",
"Id": "20817",
"Score": "5",
"body": "You should add a code sample since I believe this is by far the best way to implement a singleton with .NET 4.0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T09:30:48.093",
"Id": "60799",
"Score": "0",
"body": "A code sample is available at http://csharpindepth.com/Articles/General/Singleton.aspx (\"sixth version\")"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:07:20.607",
"Id": "282",
"ParentId": "79",
"Score": "12"
}
},
{
"body": "<p>Here's an example from Wikipedia's Double-checked locking page:</p>\n\n<pre><code>public class MySingleton\n{\n private static object myLock = new object();\n private static MySingleton mySingleton = null;\n\n private MySingleton()\n { }\n\n public static MySingleton GetInstance()\n {\n if (mySingleton == null) // check\n {\n lock (myLock)\n {\n if (mySingleton == null) // double check\n {\n MySingleton newSingleton = new MySingleton();\n System.Threading.Thread.MemoryBarrier();\n mySingleton = newSingleton;\n }\n }\n }\n\n return mySingleton;\n }\n}\n</code></pre>\n\n<p>Notice the use of <code>System.Threading.Thread.MemoryBarrier();</code>, unlike GWLlosa's answer. See <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow\">The \"Double-checked locking is broken\" declaration</a> for an explanation. (It is written for Java, but the same principles apply.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T19:22:58.003",
"Id": "318",
"ParentId": "79",
"Score": "4"
}
},
{
"body": "<p>Here's an implementation that uses <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\" rel=\"nofollow\"><code>Lazy<T></code></a>:</p>\n\n<pre><code>public class Foo : IFoo\n{\n private static readonly Lazy<IFoo> __instance\n = new Lazy<IFoo>(valueFactory: () => new Foo(), isThreadSafe: true);\n\n private Foo() { }\n\n public static IFoo Instance { get { return __instance.Value; } }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T12:10:32.517",
"Id": "15476",
"ParentId": "79",
"Score": "4"
}
},
{
"body": "<p>Simple way to I would like to suggest a simple way using volatile keyword , static variable are not thread safe but atomic execution are considered as thread safe. by using volatile we can enforce atomic operation.</p>\n\n<pre><code>public sealed class Singleton\n{\n private static **volatile** readonly Singleton instance = new Singleton();\n public static Singleton Instance { get { return instance; } }\n private Singleton() { }\n}\n</code></pre>\n\n<p>Locking is not the sure way to go , as it is expensive.</p>\n\n<p>I like john skeet way of creating the singleton way of creating the objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T16:21:55.707",
"Id": "19847",
"ParentId": "79",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "81",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T10:02:03.633",
"Id": "79",
"Score": "67",
"Tags": [
"c#",
"singleton"
],
"Title": "Implementing a Singleton pattern in C#"
} | 79 |
<p>I'm listing elements with a <code>foreach</code>, and I would like to enclose items in something tag <code>n</code> by <code>n</code>:</p>
<pre><code>$i = 0;
$open = $done = TRUE;
$n = 3;
$opening = "<div>";
$closing = "</div>";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff");
foreach($names as $name) { /** $condition was not a bool. My fault. */
if($open && !($i % n)) {
print $opening;
$open = FALSE;
$done = !$open;
} elseif(!($i % n)) $done = FALSE;
/** print element. */
print $name;
if(!$open && !($i % n) && !$done) {
print $closing;
$open = TRUE;
$done = !$open;
}
$i++;
}
</code></pre>
<p>Do you think this snippet can be improved? It would be better to have fewer check variables such as <code>$open</code> or <code>$done</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:03:10.900",
"Id": "104",
"Score": "1",
"body": "@albert can you also add what n and the condition is suppose to represent? Does it get it's value from another part of the code?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:11:26.663",
"Id": "105",
"Score": "3",
"body": "Can you provide as working example ? (Without parser errors). From its current state i pretty much have no clue that code is supposed to be doing (or at least it's nothing i think i can improve apon in a meaningfull way) . i, open and done are php variables ? ($ sign ?)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:34:03.900",
"Id": "107",
"Score": "1",
"body": "I am very sorry. I updated the question."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:39:29.277",
"Id": "109",
"Score": "2",
"body": "`} elseif(!(i % n)) done = FALSE;` is not PHP!, `}elseif(!($i % $n)) $done = FALSE;` is, this is a job for StackOverflow before you it can be improved"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:40:29.727",
"Id": "111",
"Score": "1",
"body": "open and close still me the $ signs, saidly i can't edit it myself (and i don't want to put in a question just for that.) Thanks for the edit ! Much clearer now."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:59:21.387",
"Id": "116",
"Score": "0",
"body": "Could you provide more explanation about what this method is meant to do? It might help people trying to improve it.. Are $i and $n magic numbers?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T14:10:00.693",
"Id": "431",
"Score": "0",
"body": "@Alberteddu, Please only submit working code for review. Your code is not going to run because you miss some $'s at the start of some variables."
}
] | [
{
"body": "<p>One problem with your solution is that it won't print the last closing <code></div></code> tag if there are less than <code>$n</code> elements inside the last <code><div></code>.</p>\n\n<p>An approach which fixes that problem and also simplifies the conditional logic for deciding when to print the tags is to chunk the array first using <code>array_chunk</code> and then iterate over the chunks. Now we only need one boolean variable to remember which chunks to surround in tags.</p>\n\n<pre><code>function alternate($names, $n, $opening, $closing) {\n $tag = TRUE;\n foreach(array_chunk($names, $n) as $chunk) {\n if($tag) {\n print $opening;\n }\n foreach($chunk as $name) {\n print $name;\n }\n if($tag) {\n print $closing;\n }\n $tag = !$tag;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:09:07.367",
"Id": "90",
"ParentId": "82",
"Score": "9"
}
},
{
"body": "<p>Alternate solution without the overhead of the array_chunk call. (Don't get me wrong, I love array_chunk and use it for a lot of things, but this isn't one where it's needed.)</p>\n\n<pre><code>$array = getData(...);\n$n = 5; //or whatever you want to chunk into\necho \"<div>\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0) { //every Nth item\n echo \"</div><div>\"; //close old one and open new one\n }\n}\necho \"</div>\"; //always close the last one.\n</code></pre>\n\n<p>Worst case here is you might have an empty <code><div></div></code> block at the end if you had an exact multiple of n.... but that's not really that big a deal 99.999% of the time. :) If it is... then you can catch it like so:</p>\n\n<pre><code>$array = getData(...);\n$num = count($array);\n$n = 5; //or whatever you want to chunk into\necho \"<div>\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 && $lcv < $num) { // every Nth item, unless we're done\n echo \"</div><div>\"; //close old one and open new one\n }\n}\necho \"</div>\"; //always close the last one.\n</code></pre>\n\n<p>(Of course you can use <code>print</code>, <code>echo</code>, or <code>?>...<?</code> tags... whatever you want to actually do all the output, doesn't matter.)</p>\n\n<p>And to be honest, I'd probably add one more case to it:</p>\n\n<pre><code>$array = getData(...);\n$num = count($array);\nif ($num == 0) {\n echo \"<div>No results?</div>\";\n} else {\n $n = 5; //or whatever you want to chunk into\n echo \"<div>\"; //always open one\n $lcv = 1; // loop count variable\n foreach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 && $lcv < $num) { // every Nth item, unless we're done\n echo \"</div><div>\"; //close old one and open new one\n }\n }\n echo \"</div>\"; //always close the last one.\n}\n</code></pre>\n\n<p>Just to cover the case that whatever search it is didn't actually return anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T21:08:00.120",
"Id": "528",
"ParentId": "82",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "90",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T10:25:28.040",
"Id": "82",
"Score": "7",
"Tags": [
"php"
],
"Title": "Loop with enclosing items every 'n' steps"
} | 82 |
<p>I was wondering for quite some time how to clean up the below code without blowing it up any further. The extension of the classes is the main concern here, it looks a bit too much like magic. That's mainly because it has to handle all the different cases, and I haven't figured out a way to reduce the code in a meaningful fashion here.</p>
<p>Maybe I'm paranoid and the code is just fine, but I'd still love to get some feedback on it.</p>
<p>The original code and test cases are <a href="https://github.com/BonsaiDen/neko.js" rel="nofollow">here</a>.</p>
<pre><code>function is(type, obj) {
return Object.prototype.toString.call(obj).slice(8, -1) === type;
}
function copy(val) { /* ...make shallow copy */ }
function wrap(caller, obj) {
obj = obj || Function.call;
return function() {
return obj.apply(caller, arguments);
};
}
function Class(ctor) {
// ...default ctor stuff here....
function clas(args) { /* ...actual instance ctor stuff... */}
var proto = {};
clas.init = wrap(ctor);
// extend needs to be reduced in width, it easily goes over 80 columns
// without some ugly if statements
clas.extend = function(ext) {
if (is('Function', ext)) {
return ext.extend(proto); // holy closure!
}
for (var e in ext) {
if (!ext.hasOwnProperty(e)) {
continue; // a bit ugly imo, but it helps to prevent the indentation
// from blowing up
}
// this needs some refactoring, it creates bound and unbound
var val = ext[e], func = is('Function', val);
if (/^\$/.test(e)) { // statics
proto[e] = copy(val);
clas[e] = clas.prototype[e] = func ? wrap(clas, val) : val;
} else if (func) {
clas[e] = wrap(proto[e] = clas.prototype[e] = val);
}
}
return clas;
};
// this could also need some clean up I suppose
for (var i = ctor.hasOwnProperty('init') ? 0 : 1,
l = arguments.length; i < l; i++) {
var arg = arguments[i];
is('Object', arg) ? clas.extend(arg) : arg.extend(clas);
}
return clas;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-26T23:40:36.333",
"Id": "391",
"Score": "2",
"body": "Don't emulate classes. This is ECMAScript."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T23:32:30.313",
"Id": "1335",
"Score": "0",
"body": "A while back I took a crack at making my own class definition system and if I recall my goals were similar to the things you accomplish herein. Yours looks more concise in various ways and JS development in general has come a long way since then, but I'll see if I can dig it up and find any nuggets of cleverness that might apply as well here. All in all, I find the latest revision to be pretty succinct for what it is, though admittedly I haven't given it a full on review. Still, I like what I see :)"
}
] | [
{
"body": "<p>A few tips:</p>\n\n<ul>\n<li>Make sure your using good indentation</li>\n<li>Do not create a function that runs a native method\n<ul>\n<li>so: <code>if(is(\"Function\",ext))</code> becomes <code>if(typeof ext == \"Function\")</code></li>\n</ul></li>\n<li>remove unnecessary comments and comments should only be at the head of an entity.</li>\n<li>Do not shorten your variables as it causes issues with the latter developers</li>\n<li>use stricter typecasting:\n<ul>\n<li><code>if (!ext.hasOwnProperty(e))</code> becomes <code>if(ext.hasOwnProperty(e) == false)</code></li>\n</ul></li>\n<li>Keep your conditions in the for loops on one line</li>\n<li>There's is not point in reassigning a value from an array becuase you want to send it to a function\n<ul>\n<li><code>var arg = arguments[i];</code> gets removed and <code>arguments[i]</code> is sent to the function</li>\n</ul></li>\n</ul>\n\n<p>Taking into account the above your class would look like so:</p>\n\n<pre><code>function Class(ClassBase)\n{\n /*\n * Default Constructor, used to do XXX with YYY\n */\n var Arguments = args || [];\n\n function __Class(Arguments)\n {\n\n }\n\n var Prototype = {};\n __Class.Initialize= Wrap(ClassBase);\n\n\n /*\n * extend needs to be reduced in width, it easily goes over 80 columns\n * without some ugly if statements\n */\n\n __Class.Extend = function(ExtendableEntity)\n {\n if (typeof ExtendableEntity == \"function\")\n {\n return ExtendableEntity.extend(Prototype);\n }\n\n for (var Entity in ExtendableEntity)\n {\n if (ext.hasOwnProperty(Entity) == true)\n {\n var Value = ext[Entity]\n var _Function = (typeof Value == \"function\");\n\n if (/^\\$/.test(Entity)) \n {\n Prototype[Entity] = Copy(Value);\n __Class[Entity] = __Class.Prototype[Entity] = function ? Wrap(__Class, Value) : Value;\n }else \n {\n __Class[Entity] = Wrap(Prototype[Entity] = __Class.Prototype[Entity] = Value);\n }\n }\n }\n return __Class;\n }\n\n for (var i = ClassBase.hasOwnProperty('Initialize') ? 0 : 1, l = Arguments.length; i < l; i++)\n {\n (typeof Arguments[i] == 'object') ? __Class.Extend(Arguments[i]) : Arguments[i].Extend(__Class);\n }\n return __Class;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:17:17.903",
"Id": "121",
"Score": "5",
"body": "Uh, that's exactly what I didn't want :D Someone with a lot less knowledge about JS posting an answer. First of `is(\"Function\",ext)` is **not** `typeof`. `typeof` is completely broken, **never** use it for getting the type of an object. `arguments` is a special variable inside a functions scope. Starting method names with uppercase goes against all common practice in JS land. `hasOwnProperty` only returns `true` or `false` so `!` is completely ok in this case. Braces on next line can introduce subtle bugs. Check out: http://bit.ly/JSGarden for more infos."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:17:51.070",
"Id": "122",
"Score": "0",
"body": "Aside from the above, you're right on using longer variable names and that there's no point of `var arg = arguments[i]`. PS: Your code fails all tests :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:25:32.187",
"Id": "125",
"Score": "0",
"body": "Thats a fair comment, `is()` function is not available for review therefore I had to assume (you also stated in comment *Check for type*), Why is should you not use Upper-cased function within JavaScript, who said you should not and is there a reason? and the reason for `== true` is its always good to get used to strict type and value checking, Also my coded wasn't made to work, the reason for there format is to show an example of what my comments was for, pseudo only sir."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T14:00:05.407",
"Id": "133",
"Score": "5",
"body": "`== true` is in **no** way strict typing. `==` **does do** type coercion. If you really wanted *strict* comparison of types, you would have used `===`. Also, it might be a good idea to check the source for left out methods before guessing around what they do, not that I'm ranting here, but I suppose that people who review code here actually put some effort into it when the links are provided. Concerning the use of uppercase, most of the big JS projects that I've seen (and also most of my code) uses uppercase only for user defined Types."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T10:46:23.970",
"Id": "241",
"Score": "2",
"body": "@RobertPitt there is actually a reason not to use upper-case for regular function names: this is a convention that indicates that the function is a constructor, i.e. it is intended to be used with the keyword new. For example, new Date() vs getDate()."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T10:51:39.800",
"Id": "242",
"Score": "1",
"body": "I would definitely *not* \"remove unnecessary comments\" and I strongly disagree that \"comments should only be at the head of an entity\". Comments should be as close as possible to the thing that is commented (principle of proximity, which helps to understand the association) if only because it's best to keep the comment within the same screen as commented code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T12:06:55.883",
"Id": "89",
"ParentId": "85",
"Score": "1"
}
},
{
"body": "<p>I would suggest to add comments (Javadoc-style, but probably best if much lighter) to describe the intent of each method. Even the most simple ones. I found it especially useful in JavaScript to describe:</p>\n\n<ul>\n<li>the type and range of arguments expected</li>\n<li>which arguments are optional and what are the default values</li>\n<li>the type of the result value, if any</li>\n<li>what is the result when provided arguments do not match expectations</li>\n</ul>\n\n<p>Otherwise I agree with your inline comment \"this needs some refactoring, it creates bound and unbound\", corresponding code should be extracted into a separate function, which will also reduce nesting, which seems to be one of your worries.</p>\n\n<p>Regarding the code itself, I would rename wrap() to bind() to match <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\">the bind() function added in ECMAScript 5</a> and I would rename l to length in the for loop as letter l is easily confused with number 1.</p>\n\n<p>I have doubts about this portion of the code:</p>\n\n<pre><code>if (is('Function', ext)) {\n return ext.extend(proto); // holy closure!\n}\n</code></pre>\n\n<p>In my understanding: you check first that ext is a funciton before calling the extend() method, but:</p>\n\n<ul>\n<li>extend() is not defined in JavaScript, it is one of your custom methods, so there is no guarantee that you will find this property on the function. You should probably add a check.</li>\n<li>I do not understand the intent: an inline comment would help :)</li>\n</ul>\n\n<p>All in all, I think it's fine that the code is a bit hairy because <a href=\"http://www.crockford.com/javascript/inheritance.html\">adding support for classes in JavaScript is no simple matter</a>, but a lot more inline comments (up to one comment per line of code for the most complex stuff) would improve the code readability immensely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T15:20:47.520",
"Id": "248",
"Score": "1",
"body": "Hm renaming `wrap` to `bind` seems indeed like a good idea. the `ext.extend` expects another `Class` instance, maybe an `ext instanceof clas` would be a better choice here. Adding comments might help too, my main problem is that it's hard to keep them short and simple, just as it is hard naming things. I'll try to clean it up and update the question then."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T13:17:03.077",
"Id": "422",
"Score": "0",
"body": "Looks like you're on the right path :) I would suggest adding descriptions of parameters for each function, and inline comments for each bit of cleverness such as use of regular expression: \"if (/^\\$/.test(i))\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T11:21:24.270",
"Id": "156",
"ParentId": "85",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T10:56:43.527",
"Id": "85",
"Score": "19",
"Tags": [
"javascript",
"classes"
],
"Title": "Cleaning up class creation / extension"
} | 85 |
<p>I'm new to Postgres and PostGIS, but not to geospatial applications.</p>
<p>I have a table loaded up with graph data in the form of links (edges). The link database has about <strong>60,000,000</strong> rows. I am trying to extract the nodes to allow for quicker searching. For some of my proof-of-concept work I was able to use the link table for the searches, but there will be lots of duplicates, and there's no guarantee that either the source column or the target column contains all nodes.</p>
<p>This is Postgres & PostGIS, so I am also using the table to cache a geometry->geography conversion. Yes I do need to use geography fields. I'm also copying the geometry information "just in case".</p>
<p>Table creation SQL:</p>
<pre><code>-- Recreate table and index
DROP TABLE IF EXISTS nodes;
CREATE TABLE nodes (node integer PRIMARY KEY, geog geography(POINT,4326) );
CREATE INDEX geogIndex ON nodes USING GIST(geog);
SELECT AddGeometryColumn('nodes', 'geom', 4326, 'POINT', 2);
-- Insert all unique nodes from the source column
INSERT INTO nodes (node,geog,geom)
SELECT DISTINCT ON (source) source,geography( ST_Transform(geom_source,4326)),geom_source
FROM view_topo;
-- Insert any nodes in the target column that we don't have already
INSERT INTO nodes (node,geog,geom)
SELECT DISTINCT ON (target) target,geography( ST_Transform(geom_target,4326)),geom_target
FROM view_topo
WHERE NOT EXISTS( SELECT 1 FROM nodes WHERE nodes.node = view_topo.target);
VACUUM ANALYZE;
</code></pre>
<p>I left the first <code>INSERT</code> running overnight and it took about 2-3hrs to run. This resulted in about <strong>40,000,000</strong> unique nodes being added.</p>
<p>I have just enabled the second <code>INSERT</code> and the <code>VACUUM ANALYZE</code>. I am expecting it to take until at least lunchtime.</p>
<p>Luckily this is only a batch job that has to be executed once after I've loaded a new link table, but is there a better way? Is there a faster way?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T00:40:10.920",
"Id": "173",
"Score": "0",
"body": "Yes Postgres doesn't like the VACUUM ANALYZE in a script like that. However the rest appears to have worked okay."
}
] | [
{
"body": "<p>Check out <a href=\"http://www.postgresql.org/docs/8.2/static/populate.html\" rel=\"noreferrer\">PostgreSQL's tips on adding a lot of data into a table</a>. In particular, are you sure that you need that index before <code>INSERT</code>ing all that data? It might speed things up if you create the index after all the data has been added to the table.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T14:48:29.170",
"Id": "438",
"Score": "1",
"body": "Thanks. Yesterday I founded I needed an index on the geometry field - retroactively adding that took quite a while to execute. This initially made me doubtful, but then in conventional programming a create-store-access-destroy pattern on sorted data is usually a lot faster implemented with an unsorted container and as create-store-sort-access-destroy - ie. essentially what you are suggesting. Build it then sort it one big sort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T04:46:33.527",
"Id": "254",
"ParentId": "92",
"Score": "5"
}
},
{
"body": "<p>WHERE NOT EXISTS is not fast SQL. How about a union of the two selects, inside a select distinct? I haven't got a postgresql instance to test this on, but maybe something like this:\nINSERT INTO nodes (node, geom, geom)\nSELECT DISTINCT ON (node), geom1, geom2\nFROM\n (SELECT source AS node,\n geography( ST_Transform(geom_source,4326)) AS geom1,\n geom_source AS geom2\n FROM view_topo\nUNION\n SELECT target AS node,\n geography( ST_Transform(geom_target,4326)) AS geom1,\n geom_target AS geom2\n FROM view_topo)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T15:17:34.970",
"Id": "445",
"Score": "0",
"body": "Thanks, I'm trying a UNION. I guess the NOT EXISTS relies on a nested SQL statement which would be executed for each row."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T15:35:31.077",
"Id": "449",
"Score": "0",
"body": "Out of memory! It sounds like your approach should be faster for smaller datasets but with 60M rows in my view_topo view, and about 8-9M unique rows to be inserted, my PC can't hack it. (4GB installed, but booted as 32 bit because PostGIS is currently only available for 32 bit)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T14:00:43.447",
"Id": "273",
"ParentId": "92",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "254",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T13:55:23.193",
"Id": "92",
"Score": "8",
"Tags": [
"sql",
"postgresql"
],
"Title": "Extracting nodes from a graph database"
} | 92 |
<p>I have written a method to tokenize HTTP request paths such as <code>/employee/23/edit</code>:</p>
<pre><code>protected void compile(String path){
int mark=0;
for(int i=0; i<path.length(); ++i){
if(path.charAt(i)==DELIM){
if(mark!=i)
tokens.add(path.substring(mark,i));
mark=i+1;
}
else if(path.length()==i+1){
tokens.add(path.substring(mark,i+1));
}
}
}
</code></pre>
<p>And a method to tokenize the consumer of these paths such as <code>/employee/[id]/edit</code>:</p>
<pre><code>protected void compile(String path){
int mark=0;
boolean wild=false;
for(int i=0; i<path.length(); ++i){
if(!wild){
if(path.charAt(i)==DELIM){
if(mark!=i)
tokens.add(path.substring(mark,i));
mark=i+1;
}
else if(path.length()==i+1){
tokens.add(path.substring(mark,i+1));
}
else if(path.charAt(i)=='['){
wild=true;
}
}
else if(path.charAt(i)==']'){
tokens.add("?");
wild=false;
mark=i+1;
}
}
}
</code></pre>
<p>The idea here is that there will be an implicit variable called <code>id</code> with the value <code>23</code>. However, that isn't here nor there. How does my approach look? Can it be improved? Also: <code>DELIM = '/'</code>.</p>
<p>This is more-or-less an exercise in writing a parser, which is why I didn't use <code>String#split()</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:23:19.373",
"Id": "155",
"Score": "1",
"body": "Wouldn't String.split() work better for tokenizing a String (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String))?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:26:43.273",
"Id": "156",
"Score": "1",
"body": "It looks like anything between the last `/` and an opening `[` will be ignored. Is that intentional?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:28:54.130",
"Id": "157",
"Score": "0",
"body": "@shambleh: This was more or less an exercise in writing a simple parser. I anticipate it becoming more complicated over time where `String#split()` wont suffice."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:44:48.290",
"Id": "160",
"Score": "0",
"body": "It also seems weird to me that you're just discarding the names of the variables like that. Though without knowing how you'll use the result of the compile method, it's hard to say whether it's bad or not."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:54:44.520",
"Id": "161",
"Score": "0",
"body": "@sepp2k: For sake of posting less code, you don't see anything more than the parsing aspect. I took out the part you are referring to."
}
] | [
{
"body": "<p>Your first <code>compile</code> method can be replaced by a single call to <code>String.split</code>.</p>\n\n<p>Assuming the intended behavior for the second <code>compile</code> method is such that \"/foo/b[a]r/baz\" will compile to <code>{\"foo\", \"?\", \"baz\"}</code>, it can be replaced by a call to <code>split</code> and then iterating over the result and replacing any string the includes square brackets with \"?\".</p>\n\n<p>If the intended behavior is rather that it will compile to <code>{\"foo\", \"b\", \"?\", \"r\", \"baz\"}</code>, you can first replace <code>[anything]</code> by <code>/?/</code> using <code>String.replace</code> and then use <code>String.split</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T18:30:53.690",
"Id": "110",
"ParentId": "109",
"Score": "11"
}
},
{
"body": "<p>Just as an exercise in making the code easier to read, I'd recommend better variable names. I can figure out what \"wild\" and \"mark\" are, but it should be immediately apparent to me so I don't have to spend time trying to figure out what they are.</p>\n\n<p>Also, I'm assuming you are going to eventually handle URLs with \"?\" and such in them. You may want to consider checking for invalid characters in the URL so you know when you hit the end of the actual request path.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T19:59:53.783",
"Id": "165",
"Score": "0",
"body": "I have to disagree about the variable names, unless you can suggest better ones? `mark` is a perfectly valid in my opinion because it is marking a point in the string. I could change `wild` to `isWild` I suppose. As for handling question marks, no, the purpose for the paths with wildcards is to be parsed on the server when the web application starts up. I intend to annotate a method like this: `@Get(\"/employees/[id]\")`. I am just dealing with paths, not the query string."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T17:20:46.847",
"Id": "254",
"Score": "0",
"body": "Well, 'position' might make the intent clearer than 'mark' :) As for 'wild', a name including 'wildcard' might be easier to understand."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T19:49:02.543",
"Id": "114",
"ParentId": "109",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "110",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T18:14:40.340",
"Id": "109",
"Score": "14",
"Tags": [
"java",
"parsing",
"url"
],
"Title": "HTTP request path parser"
} | 109 |
<p>I have written this (truncated) code to fetch some tweets:</p>
<pre><code> dispatch_async(dispatch_get_global_queue(0, 0), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *JSONStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://search.twitter.com/search.json?q=haak&lang=nl&rpp=100"] encoding:NSUTF8StringEncoding error:nil];
if (!JSONStr) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
return;
}
/*... PARSING ETC ...*/
dispatch_sync(dispatch_get_main_queue(), ^{
[delegate didReceiveTweets:foundTweets];
});
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
});
</code></pre>
<p>Note the lines from <code>dispatch_sync(dispatch_get_main_queue(), ^{</code> to <code>});</code>. This will update the UI.</p>
<p>Is this the good way to do it, or are there better ways than using <code>dispatch_sync</code> within a <code>dispatch_async</code>? Or should I not do this at all? Should I also send <code>setNetworkActivityIndicatorVisible:</code> from within the main thread?</p>
<p>The reason I'm not using <code>NSURLConnection</code> is because this code comes from a class method, so I need to create an object containing the delegate for the <code>NSURLConnection</code>, which seems overkill to me.</p>
| [] | [
{
"body": "<p>you don't necessarily have to call -setNetworkActivityIndicatorVisible: from the main thread. I didn't find anything in the documentation about UIApplication not being thread safe, and since your application's main thread doesn't have anything in common with the system, you are free to call it whenever you like.</p>\n\n<p>dispatch_sync: that's fine. you could also call dispatch_async, since i'm not really sure you would want do display the network indicator while the feeds are actually being set on the UI - instead you probably only want the downloading to be indicated. I would probably go for dispatch_async.</p>\n\n<p>But to answer your question, that piece of code is perfectly fine ( with the minor addition that maybe you should really use only one exit point from your method ... )</p>\n\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T10:33:54.050",
"Id": "17554",
"Score": "0",
"body": "But if the method makes any UI calls, it still needs to be called on the main thread."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-25T09:26:03.907",
"Id": "195",
"ParentId": "112",
"Score": "7"
}
},
{
"body": "<p>Typically you want to perform UI interactions from the main thread, I would just move it to before the first dispatch_async call to turn it on. Then have it turn off in the later dispatch in the main_queue, so that it also happens on the main thread. This of course assumes that you were calling from the main thread to start with. If not you could just make another call to dispatch_async with the main_queue at the beginning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T00:52:33.923",
"Id": "249",
"ParentId": "112",
"Score": "4"
}
},
{
"body": "<p>Avoid to dispatch sync code on main queue. This can cause freezing because this code supposed to run on main thread will wait until main thread will be able to run it. In the same time this code will block main thread. Try always use:</p>\n\n<pre><code>dispatch_async(dispatch_get_main_queue(), ^{});\n</code></pre>\n\n<p>Also this is bad style to use direct numerical values of system constants. Try to use predefined values:</p>\n\n<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ .. });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T05:16:53.597",
"Id": "13857",
"ParentId": "112",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T19:19:39.800",
"Id": "112",
"Score": "14",
"Tags": [
"multithreading",
"objective-c",
"twitter"
],
"Title": "Fetching tweets"
} | 112 |
<p>I have a Perl application that allows the user to choose between two different formats for data output (and there will likely be more in the near future). In the heart of the algorithm, the code makes a call to a print subroutine.</p>
<pre><code>my $stats = analyze_model_vectors( $reference_vector, $prediction_vector );
print_result( $stats, $tolerance );
</code></pre>
<p>The <code>print_result</code> subroutine simply calls more specific methods.</p>
<pre><code>sub print_result
{
if($outformat eq "text")
{
print_result_text(@_);
}
elsif($outformat eq "xml")
{
print_result_xml(@_);
}
else
{
# Should not reach this far if input checking is done correctly
printf(STDERR "Error: unsupported output format '%s'\n", $outformat);
}
}
</code></pre>
<p>Is this good practice? What other alternatives are there and what are their pros/cons? I could think of the following alternatives.</p>
<ul>
<li>Test for output format in the heart of the algorithm, and call the appropriate printing subroutine there.</li>
<li>I've never used subroutine references before, but perhaps when I could store a reference to the correct subroutine in a scalar variable and call the print method with that scalar in the heart of the algorithm.</li>
<li>Place code for all output formats in a single subroutine, separated by <code>if/elsif/else</code> statements.</li>
</ul>
<p>Keep in mind there may be more output formats required in the near future.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T18:26:59.350",
"Id": "4224",
"Score": "1",
"body": "Big if/elsif/else chains are ugly. The canonical method of handling this case in Perl is to use a dispatch table: a hash containing subroutine references. See Charles Bailey's response. A tempire offers a more exotic approach, that uses Perl's internal symbol tables for the lookup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-13T18:33:41.423",
"Id": "121221",
"Score": "0",
"body": "How/where is `$outformat` specified?"
}
] | [
{
"body": "<p>I try to avoid Perl if I can, so this is more of a general answer: I've coded like this in an old VB6 app. Each output function had a wrapper function that then called the required implementation using a series of IFs. Sometimes a particular output method wouldn't need anything - eg. \"Start New Line\" is relevant for text file output, but not Excel worksheet output.</p>\n\n<p>I'm currently in the process of porting/re-writing that particular app in C#/.NET 4, where I've been able to take a much more object oriented approach. \nI have defined an \"output base class\" with a standard interface. This is then inherited by the various implementations. As I start the output, I can create the required implementation using a factory method/class, and pass data to it using the standard interface.</p>\n\n<p>This particular implementation is actually multi-threaded, so the bulk of the output base class is actually the thread & queue management. Data is then passed in using a small \"data chunk\" class, and queued for output using a thread-safe queue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T17:16:29.267",
"Id": "253",
"Score": "1",
"body": "The OO approach is definitely making things easier to handle, conceptually and practically. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-09T13:06:13.803",
"Id": "1277",
"Score": "2",
"body": "Can't downvote this yet, but the OOP approach is completely overkill and unnecessary here. Languages like VB6 and Java (not too sure about C#) don't have first-class functions so that you are supposed to do some OOP magic. Perl has first-class functions and thus you can use them as any other variable. The answer provided by Charles Bailey is thus more correct and also more appropriate for the provided code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-16T23:57:39.137",
"Id": "10829",
"Score": "1",
"body": "Seriously, I would down-vote this twice if I could. ( I don't have enough rep to down-vote yet )"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T20:55:54.960",
"Id": "116",
"ParentId": "115",
"Score": "4"
}
},
{
"body": "<p>If you can pass in the subroutine it makes the code a lot simpler, you also don't have to deal with an unknown string format as the subroutine itself has been passed in.</p>\n\n<pre><code>sub print_result\n{\n my $subroutine = shift;\n &$subroutine( @_ );\n}\n\nprint_result( \\&print_result_text, $arg1, $arg2 )\n</code></pre>\n\n<p>Otherwise I think I'd go with with a hash of subroutine references. It's easily readable and simple to update.</p>\n\n<pre><code>sub print_result\n{\n my %print_hash = ( text => \\&print_result_text,\n xml => \\&print_result_xml );\n\n if( exists( $print_hash{ $outformat } ) )\n {\n &{$print_hash{ $outformat }}( @_ );\n }\n else\n {\n printf(STDERR \"Error: unsupported output format '%s'\\n\", $outformat);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T17:15:36.787",
"Id": "252",
"Score": "0",
"body": "I think I'll try using the subroutine references."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T22:47:15.107",
"Id": "118",
"ParentId": "115",
"Score": "15"
}
},
{
"body": "<p>I'd use anonymous subroutines to make the code cleaner:</p>\n\n<pre><code>my %output_formats = (\n 'text' => sub {\n # print_result_text code goes here\n },\n 'xml' => sub {\n # print_result_xml code goes here\n },\n # And so on\n);\n\nsub print_result {\n my ($type, $argument1, $argument2) = @_;\n\n if(exists $output_formats{$type}) {\n return $output_formats{$type}->($argument1, $argument2);\n } else {\n die \"Type '$type' is not a valid output format.\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T04:34:43.130",
"Id": "253",
"ParentId": "115",
"Score": "5"
}
},
{
"body": "<p>I find that Perl's flexibility can help you eliminate many IF/ELSIF/* code constructs, making code much easier to read.</p>\n\n<pre><code>sub print_result {\n my ($stats, $tolerance, $outformat) = @_;\n\n my $name = \"print_result_$outformat\";\n\n print \"$outformat is not a valid format\" and return\n if !main->can($name);\n\n no strict 'refs';\n &$name(@_);\n}\n\nsub print_result_xml { ... }\nsub print_result_text { ... }\nsub print_result_whatever { ... }\n</code></pre>\n\n<p><br>\n<strong>Walkthrough</strong></p>\n\n<pre><code>print \"$outformat is not a valid format\" and return if !main->can($name);\n</code></pre>\n\n<p>This checks the main namespace <em>(I presume you're not using classes, given your code sample)</em> for the $name subroutine. If it doesn't exist, print an error message and get out. The sooner you exit from a subroutine, the easier your code will be to maintain.</p>\n\n<pre><code> no strict 'refs';\n</code></pre>\n\n<p>no strict 'refs' turns off warnings & errors that would be generated for creating a subroutine reference on the fly <em>(You're using 'use strict', aren't you? If not, for your own sanity, and for the children, start)</em>. In this case, since you've already checked for it's existence with main->can, you're safe.</p>\n\n<pre><code> &$name(@_);\n</code></pre>\n\n<p>Now you don't need any central registry of valid formatting subroutines - just add a subroutine with the appropriate name, and your program will work as expected.</p>\n\n<p>If you want to be super hip <em>(some might say awesome)</em>, you can replace the last 5 lines of the subroutine with:</p>\n\n<pre><code>no strict 'refs';\nmain->can($name) and &$name(@_) or print \"$outformat is not a valid format\";\n</code></pre>\n\n<p>Whether you find that more readable or not is a simple personal preference; just keep in mind the sort of folk that will be maintaining your code in the future, and make sure to code in accordance with what makes the most sense to them.</p>\n\n<p>Perl is the ultimate in flexibility, making it inherently the hippest language in existence. Make sure to follow <a href=\"http://blogs.perl.org\">http://blogs.perl.org</a> and ironman.enlightenedperl.org to keep up with the latest in Modern::Perl.</p>\n\n<p>On a separate note, it's Perl, not PERL. The distinction is important in determining reliable & up-to-date sources of Perl ninja-foo.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T18:30:59.923",
"Id": "4225",
"Score": "0",
"body": "Why not use eval? `eval { &$name(@_); 1 } or print \"$outformat is not a valid format\\n\";` `can()` may be fooled by autoloaded functions and other magics, but simply trying the call is as authoritative as it gets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T03:39:24.197",
"Id": "4327",
"Score": "0",
"body": "eval is brute force. Calling the function outright assumes it's idempotent and has no unintended side effects. Also, it seems to me errors should always be avoided. Using eval/try/catch is for the !@#$ moments that _should_ never happen."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T06:17:24.057",
"Id": "256",
"ParentId": "115",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "118",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T20:31:26.477",
"Id": "115",
"Score": "14",
"Tags": [
"perl",
"subroutine"
],
"Title": "Subroutine to call other subroutines"
} | 115 |
<p>So I have a series of objects, which I will call Impl1, Impl2, and Impl3. They each implement an interface, called IImpl. I have a Factory class who's task is to retrieve the ImplX which is appropriate for a given circumstance, and pass it on to its callers. So the code in the factory looks like:</p>
<pre><code>public IImpl GetInstance(params object[] args)
{
if (args[0]=="Some Value")
return new IImpl1();
else if (args[0]=="Other Value")
return new IImpl2(args[1]);
else
return new IImpl3(args[1]);
}
</code></pre>
<p>So depending on the arguments passed in, different instances are selected. All well and good and works ok. The problem now is, that I have a class which needs to call this factory method. It has no references to IImplX, which is good, but it winds up having to know exactly how to construct the input array to GetInstance, in order to ensure it receives the correct kind of instance. Code winds up looking like:</p>
<pre><code>switch (_selectedInputEnum)
{
case InputType.A:
myIImplInst = Factory.GetInstance("Some Value");
case InputType.B:
myIImplInst = Factory.GetInstance("Other Value",this.CollectionB);
case InputType.C:
myIImplInst = Factory.GetInstance("Third Value",this.CollectionC);
}
</code></pre>
<p>This feels very redundant, and off somehow. What would be the best way to abstract the actual parameters of the factory? I feel like with the above switch statement, I am strongly coupled to the implemenations of IImplx, even if I don't have a direct reference.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T13:52:27.023",
"Id": "245",
"Score": "0",
"body": "I think either we need more information, or you're expectations can't be met: if you are required to pass different kinds of parameters to this factory for it to work properly, then the client code always has to provide these parameters, and therefore always has to know which overload to call or which parameters to supply."
}
] | [
{
"body": "<p>How about some kind of intermediary blackboard that the client code constructs before calling the factory, and each concrete Impl can poll to construct itself?</p>\n\n<pre><code>// client code:\n\nBlackboard blackboard = new Blackboard();\nblackboard.pushCollectionB(collectionB);\nblackboard.pushCollectionC(collectionC);\nblackboard.pushFoo(foo); \n\nIImpl myInstance = Factory.GetInstance(b);\n\n///////////////////////////\n\n// in Factory.GetInstance():\n\nreturn new Impl3(blackboard);\n\n////////////////////////////\n\n// in Impl3:\n\nImpl3(Blackboard b) { process(b.getCollectionC()); }\n</code></pre>\n\n<p>I've hidden the switch statement in the client code, but you could move that into the blackboard as well.</p>\n\n<p>What data each concrete Impl needs is now hidden from both the Factory and the client code. However if you need more data in your Blackboard for Impl(x+1) you will need to update every place in your code that creates a Blackboard.</p>\n\n<p>Depending on application, over-constructing the Blackboard like this may be expensive for you. You could construct a cached version at startup, or you could make the Blackboard an interface and have your client code derive from it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T14:45:38.703",
"Id": "188",
"Score": "0",
"body": "In this construct, the factory itself would have to know which ImplX to call, presumably by polling the blackboard itself?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T15:17:04.793",
"Id": "191",
"Score": "0",
"body": "You could go either way, leaving the switch in the client code to translate from InputType, and passing the string into the Factory alongside the Blackboard, or push it into the Blackboard as you suggest. Either way works."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T14:42:09.250",
"Id": "129",
"ParentId": "128",
"Score": "9"
}
},
{
"body": "<p>It seems to me that the factory should be choosing the ImplX based on arg[1] then instead of arg[0]. </p>\n\n<p>So something like this would remove the need for the switch, arg[1] is now arg[0] in this example:</p>\n\n<pre><code>public IImpl GetInstance(params object[] args)\n{\n if (args.length == 0)\n return new IImpl1();\n else if (args[0] is IEnumerable<string>)\n return new IImpl2(args[0]);\n else\n return new IImpl3(args[0]);\n}\n</code></pre>\n\n<p>You could then call it like:</p>\n\n<pre><code>var impl1 = GetInstance();\nvar impl2 = GetInstance(new List<string>{\"1\",\"2\"});\nvar impl3 = GetInstance(\"\");\n</code></pre>\n\n<p>Edit:\nIf you don't want the caller to have to know the inner works of it then you should expose overloads for getInstance so:</p>\n\n<pre><code>public IImpl GetInstance()\n{ \n return new Impl1();\n}\npublic IImpl GetInstance(IEnumberable<string> strings)\n{\n return new Impl2(strings);\n}\npublic IImpl GetInstance(string string)\n{\n return new Impl3(string);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T19:52:37.873",
"Id": "221",
"Score": "1",
"body": "That still requires that the caller of GetInstance (your second code block in this case) know about the internals of how GetInstance works (in this case, knowing to pass different parameters in different orders to GetInstance)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T20:02:08.073",
"Id": "223",
"Score": "0",
"body": "Then I think you will need to create some overrides for GetInstance that support the different calling methods."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T20:31:13.130",
"Id": "225",
"Score": "1",
"body": "Wouldn't they still have to know which override to call?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T20:37:36.823",
"Id": "226",
"Score": "0",
"body": "Are they supposed to be able to decide what ImplX they are getting? If so then instead of GetInstance(IEnumerable<string> strings) it would be GetInstanceImpl2(IEnumerable<string> strings)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T19:44:38.703",
"Id": "141",
"ParentId": "128",
"Score": "1"
}
},
{
"body": "<p>Seems like your abusing the factory pattern, the whole purpose of a factory is that you pass it some general object and the factory decides what is most appropriate to return. The passed object doesnt need to know about the factory but the factory should know about the object it's passed.</p>\n\n<p>If you need to pass it very explicit parameters then that is a code smell in your architecture and I'd think seriously about doing some refactoring rather than just \"fixing\" this problem</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-23T14:43:17.427",
"Id": "272",
"Score": "1",
"body": "That's the exact intent of this question; refactoring this into a better solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-23T12:23:40.070",
"Id": "169",
"ParentId": "128",
"Score": "1"
}
},
{
"body": "<p>Where are CollectionB and CollectionC coming from? The approach I'd shoot for is to have a variety of factories that all accept the same type of input, and then store them in some type of collection. For example, if one has a list of objects to be created, one object per line, and the portion of each line before the first blank defines the type of each item, one could have a factories that take a string and yield an appropriately-configured object. For example, if the input looked like:</p>\n\n<pre>\nsquare 0,5,5,29\nline 5,2 19,23 6,8\ntext 0,29,Hello there!\n</pre>\n\n<p>one could have a SquareFactory, LineFactory, and TextFactory all of which inherit from GraphicObjectFactory, which accept a string and return GraphicObject. One could then have a Dictionary that maps String to GraphicsObjectFactory, and put in it an instance of each of the above mentioned factories. To allow the file reader to handle more types of graphics objects, just add more factories into the Dictionary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T02:03:01.817",
"Id": "627",
"Score": "0",
"body": "Unless I'm misreading this, it seems like a similar concept to tenpn's answer, which is near to what I did, so I like it :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:40:25.250",
"Id": "764",
"Score": "0",
"body": "It's somewhat like tenpn's answer, except that his \"blackboard\" is configured by code in various clients of the class, while I would expect to have the factory constructed from a configuration file or other single point of definition."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-28T21:08:47.497",
"Id": "385",
"ParentId": "128",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "129",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T14:07:09.330",
"Id": "128",
"Score": "23",
"Tags": [
"c#",
".net",
"design-patterns"
],
"Title": "Best way to pass parameters to Factory class?"
} | 128 |
<p><em>Inspired by <a href="https://codereview.stackexchange.com/q/97">this question</a>, but hopefully not a duplicate.</em></p>
<p>I understand that the Law of Demeter is very useful in case of services interacting with other services, for example it's much easier to mock the other services in unit tests.
What about services interacting with data models, though?</p>
<p>Let's say I have a hierarchy of immutable classes:</p>
<pre><code>public final class Document {
private final List<Page> pages;
// Constructor, getter, ...
}
public final class Page {
private final List<Paragraph> paragraphs;
// Constructor, getter, ...
}
public final class Paragraph {
private final List<Line> lines;
// Constructor, getter, ...
}
</code></pre>
<p>Let's say I want to do something with certain lines in a document <code>doc</code>:</p>
<pre><code>public void doSomething(Document doc) {
for (Page page : doc.getPages()) {
for (Paragraph para : page.getParagraphs()) {
for (Line line : para.getLines()) {
if (someCondition(line)) {
someAction(line);
}
}
}
}
</code></pre>
<p>Now, as far as I understand, the above code doesn't obey the Law of Demeter.
However, I don't want to force the law at all cost and clutter the model (here, the <code>Document</code> class) with tens of methods like:</p>
<pre><code>public List<Line> filterWrtSomeCondition();
public List<Line> filterWrtSomeOtherCondition();
</code></pre>
<p>Or maybe there's a third way? I suspect that the Law of Demeter applies primarily to services interacting with other services. Is it a valid interpretation?</p>
| [] | [
{
"body": "<p>I'd say that it isn't cluttering the model personally. You are actually protecting yourself by not exposing internal implementation of your document class. The entire idea is to put all of your behavior into your class instead of having external code modify the class in such a way that it may not pass its own internal invariants.</p>\n\n<p>Perhaps it also would make sense to make subclasses of your Document class which are specialized and only have the methods related to that usage of your Document. You don't have to have a one stop shop where you can do absolutely everything, since that's probably not going to be your primary use case in all instances.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T17:41:24.653",
"Id": "208",
"Score": "0",
"body": "Thanks for your answer! Although I didn't stress that, I've mentioned that the model is immutable, so there is no way to \"break\" it once it's created. Does that change anything?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T17:42:08.957",
"Id": "209",
"Score": "2",
"body": "I'm skeptical of adding subclasses, though. For one, I can clearly name and document the `Document` class, but how do I name a `Document` subclass with methods for evaluating text readability, or with methods for finding occurrences of a given phrase? As in: \"If you can't name it, it shouldn't be a class.\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T17:59:42.617",
"Id": "210",
"Score": "0",
"body": "Didn't catch on to the immutable part. It at least makes it so you can't break it, but exposing the internal implementation is still valid. Without knowing your use case, I'm just guessing and saying that subclasses may be a valid way to address your concern of adding many methods (they may be broken up)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T17:07:04.617",
"Id": "133",
"ParentId": "131",
"Score": "2"
}
},
{
"body": "<p>For some perspective on the LoD, read \"<a href=\"http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx\" rel=\"nofollow noreferrer\">The Law of Demeter Is Not A Dot Counting Exercise</a>\". In particular the part under the heading \"I Fought The Law and The Law Won\".</p>\n\n<p>I think in this instance that pages, paragraphs and lines are very logical subcomponents of documents. These each have different but related behaviour. The each also serve different purposes.</p>\n\n<p>Forcing the document to handle interactions with subcomponents will - as you say - lead to clutter (and more chance of introducing troublesome issues).</p>\n\n<p>The big thing about the LoD is that it aims to reduce coupling. However adding methods to Document doesn't <em>really</em> reduce coupling as you're still writing code that says \"do x to line y\" - you're just asking Document to do it for you.</p>\n\n<p>Don't get me wrong, the LoD is useful. But like all principles it has to be used correctly to stay useful.</p>\n\n<p>(Funnily enough a similar <a href=\"https://stackoverflow.com/questions/3706463/am-i-breaking-the-law-of-demeter\">question</a> with a similar answer as been asked at SO.)</p>\n\n<p><br /><strong>Conclusion</strong></p>\n\n<p>In short I don't see any benefit for you in talking to Document rather than it's contained Pages, Paras, & Lines. Frankly I don't think there's any ROI for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T08:52:43.757",
"Id": "237",
"Score": "3",
"body": "Interesting reference, especially: \"If LoD is about encapsulation (aka information hiding) then why would you hide the structure of an object where the structure is exactly what people are interested in and unlikely to change?\". I tend to think that OO design principles intended for objects with responsibilities and behaviors should be left aside when working with data structures, which are really a different kind of objects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T05:24:42.827",
"Id": "153",
"ParentId": "131",
"Score": "16"
}
},
{
"body": "<p>I'll argue the counterpoint ...</p>\n\n<p>The LoD would say that this client code is being tied to a particular model of the Document. In the end, the code is really interested in the lines of a document. How reasonable is it that we tie that code to the <code>getPage / getParagraph / getLine</code> model?</p>\n\n<p>Its perfectly reasonable to believe that pages wills always be made up of paragraphs and paragraphs made up of lines, but I don't think this is the only consideration. The other question to ask is what other models should Document support? Stated differently:</p>\n\n<p><em><strong>\"Is it reasonable to look at a Document as a series of Lines without regard to what page or paragraph they are in?\"</em></strong></p>\n\n<p>I think it is, so I would give <code>Document</code> a <code>getLines()</code> method and not force our code to go through the Page/Paragraph/Line model.</p>\n\n<p>This <code>getLines()</code> method is also a good thing, because: <em>if it its reasonable for our <code>Document</code>'s client to see things this way, it is reasonable that <code>Document</code> may see things this way too</em>. That is, isn't it possible that the <code>Document</code> <em>may</em> have an efficient structure for moving from line to line (if not now, then perhaps in the future) that may not involve pages and paragraphs? If so, forcing client code to go through the <code>getPage / getParagraph / getLine</code> is hurting the opportunity to use that efficient structure.</p>\n\n<p>I also think its unreasonable \"Forcing the document to handle interactions with subcomponents\" in every conceivable case, so there has to be a happy medium out there. As a counter example, consider:</p>\n\n<p><em><strong>\"is it reasonable to look at a Library as a series of Lines without regard to what document they are in?\"</em></strong></p>\n\n<p>I don't think I'll be providing a <code>getLines()</code> method to my <code>Library</code> class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-26T23:18:58.190",
"Id": "242",
"ParentId": "131",
"Score": "12"
}
},
{
"body": "<p>I also agree that this code violates LoD. The caller is tying the implementation down to a model of nested objects.</p>\n\n<p>Adding a bunch of filter methods also doesn't seem like the right idea, but this is an opportunity in disguise. You really want a general filtering method that can take a \"verb\" to apply to the matching elements. Or, alternatively, a filter method that takes a predicate and returns just the collection of matching elements.</p>\n\n<p>This is one of the useful things about LoD. It helps you uncover places where you are operating at a low level of abstraction, and raise the level. In this case, once you introduce general predicates or verbs, you'll be very likely to find other places to use the same idiom. What begins as a local cleanup can uncover a very general mode of expression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T16:51:16.763",
"Id": "292",
"ParentId": "131",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "153",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T16:26:15.320",
"Id": "131",
"Score": "27",
"Tags": [
"java",
"design-patterns"
],
"Title": "Law of Demeter and data models?"
} | 131 |
<p>Would this function be sufficient enough to remove all malicious code and foreign characters from a string?</p>
<pre><code>//Clean the string
$out = ltrim($do);
$out = rtrim($out);
$out = preg_replace('/[^(\x20-\x7F)]*/','', strip_tags($out));
</code></pre>
<p>This data is not going into a SQL database, so I dont have to worry about sql injection attempts. Is there any way to improve my code and make it more efficient?</p>
<p>This function would clean any user inputted data (forms, and ?), and then save it do a database. This would be used in a global sanitizing function.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T18:09:36.597",
"Id": "211",
"Score": "2",
"body": "How are you using this string that you are worried about it being an attack vector? Where is the string coming from? What do you expect it to contain? Please add that to the question."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T19:50:51.563",
"Id": "220",
"Score": "6",
"body": "The context is still not clear of what you are trying to prevent injection of."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-25T15:33:03.393",
"Id": "305",
"Score": "0",
"body": "`$out = preg_replace('/[^(\\x20-\\x7F)]*/','', strip_tags(rtrim(ltrim($do))));`"
}
] | [
{
"body": "<p>That one is quite simple (for me at least) since there is a very general answer :)</p>\n\n<h2>NO</h2>\n\n<p>There is no way you can ever really safely \"repair\" user input.</p>\n\n<blockquote>\n <p>\"Please provide a list of everything you shouldn't to with a hammer\" </p>\n</blockquote>\n\n<p>is <em>way</em> harder than </p>\n\n<blockquote>\n <p>\"list all appropriate uses of a hammer\". </p>\n</blockquote>\n\n<p>You might forget one or two but no harm done there if you go back and add them.</p>\n\n<p>It might sound harsh but something will always byte you and if it's only <code>EVAL(UNHEX(ASD23426363))</code> or something like that. (Sql example even so you did say it not sql but whatever).</p>\n\n<p>Of course you might want to do things like strip out tags out of input for html context anyways so that a hole in your other code is not as easily exploited and less damage will be done but i shouldn't be your only defense.</p>\n\n<hr>\n\n<p>Someone that said <a href=\"http://terrychay.com/article/php-advent-security-filter-input-escape-output.shtml\"><code>Filter Input, Escape Output</code></a> way better than i could. Terry Chay</p>\n\n<hr>\n\n<p>In short: Whatever you are doing there, find the appropriate escaping function and use it.</p>\n\n<p>Shell context ? <a href=\"http://php.net/escapeshellarg\"><code>escapeshellarg</code></a></p>\n\n<p>Html context ? <a href=\"http://php.net/htmlentities\"><code>htmlspecialchars</code></a></p>\n\n<p>Database context ? Use prepared statements and never worry about sql injection again</p>\n\n<hr>\n\n<p>Little edit:\nI know what i said and the blog post contradict a little but thats fine with me. 'In practice' will always differ from general advice and sometimes you want to do everything you can ;) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T18:14:05.447",
"Id": "137",
"ParentId": "136",
"Score": "17"
}
},
{
"body": "<p>I'm doing a copy-pasta from <a href=\"https://stackoverflow.com/questions/4762824/php-security-sanitize-clean/4763314#4763314\">My Answer to a similar question on SO</a>:</p>\n\n<p>Always remember, <em>Filter In, Escape Out</em> for all user supplied (or untrusted) input.</p>\n\n<p>When reading user supplied data, filter it to known values. <strong>DO NOT BLACKLIST!</strong> Always always always <strong>always</strong> whitelist what you are expecting to get. If you're expecting a hex number, validate it with a regex like: <code>^[a-f0-9]+$</code>. Figure out what you expect, and filter towards that. Do none of your filenames have anything but alpha, numeric and <code>.</code>? Then filter to <code>^[a-z0-9.]+$</code>. But don't start thinking blacklisting against things. It won't work.</p>\n\n<p>When using user-data, escape it properly for the use at hand. If it's going in a database, either bind it as a parameterized query, or escape it with the database's escape function. If you're calling a shell command, escape it with <a href=\"http://us.php.net/manual/en/function.escapeshellarg.php\" rel=\"nofollow noreferrer\"><code>escapeshellarg()</code></a>. If you're using it in a regex pattern, escape it with <a href=\"http://us.php.net/manual/en/function.preg-quote.php\" rel=\"nofollow noreferrer\"><code>preg_quote()</code></a>. There are more than that, but you get the idea.</p>\n\n<p>When outputting user data, escape it properly for the format you're outputting it as. If you're outputting it to HTML or XML, use <a href=\"http://us.php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow noreferrer\"><code>htmlspecialchars()</code></a>. If you're outputting to raw headers for some reason, escape any linebreaks (<code>str_replace(array(\"\\r\", \"\\n\"), array('\\r', '\\n'), $string)</code>). Etc, etc, etc.</p>\n\n<p>But always filter using a white-list, and always escape using the correct method for the context. Otherwise there's a significant chance you'll miss something...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T20:17:55.463",
"Id": "143",
"ParentId": "136",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "137",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-21T18:08:22.390",
"Id": "136",
"Score": "11",
"Tags": [
"php",
"strings",
"security",
"regex"
],
"Title": "Is this a sufficient way to prevent script injections and other bad stuff in strings"
} | 136 |
<p>I don't like the fact that I am selecting all the points, even though I only care about the count of them.</p>
<p>Which of the <code>from</code> parts should appear first, if it even matters?</p>
<pre><code>var count = (from type in ValidTypes()
from point in GetData(type)
where point.Radius > referencePoint.Radius
&& point.Theta > referencePoint.Theta
select point).Count()
</code></pre>
<p><code>ValidTypes()</code> returns a few types, about 5.</p>
<p><code>GetData(type)</code> may return many points, possibly 100,000.</p>
<p>This query is counting the number of points that have both a larger theta and a larger radius than a given point.</p>
<p>Is there a way to write this faster or more readable?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T19:28:47.677",
"Id": "218",
"Score": "1",
"body": "Is this a Linq to sql query or linq to objects?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T19:56:25.033",
"Id": "222",
"Score": "0",
"body": "This is linq to objects."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T12:08:20.080",
"Id": "243",
"Score": "1",
"body": "As has been said already, your code is fine. I'm not sure what you mean by \"selecting\" when you say \"I am selecting all the points\"? That you're iterating over all of them? You can't count them without iterating over them, so that's ok. Or do you think that your linq query creates a temporary array which you then call Count on? It doesn't."
}
] | [
{
"body": "<p>First, your query is written fine. Its structure is not a concern; the order of the froms is clearly correct, the select is appropriate. Where you could look for improvement that could change the query (code and possibly performance) would be in the <code>GetData</code> method. If, for example, <code>GetData</code> is <em>getting data</em> from an external, queryable source, then you may want to offload the filtering to <em>it</em> rather than getting all of the data points and filtering it inside your application, particularly since you have so many points of data (potentially). So maybe your query could instead be </p>\n\n<pre><code>(from type in ValidTypes() \n select GetData(type, referencePoint).Count())\n.Sum();\n\n// or same meaning, different phrasing\n\n(from type in ValidTypes()\nfrom point in GetData(type, referencePoint)\nselect point).Count();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T20:22:39.207",
"Id": "144",
"ParentId": "138",
"Score": "9"
}
},
{
"body": "<p>Why are you doing:</p>\n\n<pre><code>Point.Radius > referencePoint.Radius && point.Theta > referencePoint.Theta\n</code></pre>\n\n<p>Seems this probably should be a function like <code>IsCorrectReferencePoint</code> or whatnot. That will both make your code more readable and more understandable since you can simply look at the function name to see what it does.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T02:21:31.187",
"Id": "99284",
"Score": "0",
"body": "Make sure the function is a proper `Predicate<>` so it can be used in the overload of `.Count()` as in Martin's answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-23T12:26:04.200",
"Id": "170",
"ParentId": "138",
"Score": "7"
}
},
{
"body": "<p>I don't like writing a statement that combines both \"fluent\" and \"expression\" syntax for LINQ. (See SO: <a href=\"https://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression/214610#214610\">Which LINQ syntax do you prefer? Fluent or Query Expression</a>)</p>\n\n<p>I also would choose multiple <code>where</code> clauses over a single <code>where</code> with <code>&&</code>. So, either:</p>\n\n<pre><code>var points = from type in ValidTypes()\n from point in GetData(type)\n where point.Theta > referencePoint.Theta\n where point.Radius > referencePoint.Radius\n select point;\n\nvar count = points.Count();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var count = ValidTypes\n .Select(type => type.GetData())\n .Where(point.Theta > referencePoint.Theta)\n .Where(point.Radius > referencePoint.Radius)\n .Count();\n</code></pre>\n\n<p>I'd look at the code before & after, and see if one of these lends itself to further refactoring.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:45:47.257",
"Id": "16739",
"Score": "1",
"body": "ugh, Your fluent version is syntactically incorrect and should be using `SelectMany` or else you'll get the wrong result. Also, see <a href=\"http://stackoverflow.com/questions/664683/should-i-use-two-where-clauses-or-in-my-linq-query\">should-i-use-two-where-clauses-or-in-my-linq-query</a> regarding multiple `where` vs `&&`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-28T23:06:47.027",
"Id": "394",
"ParentId": "138",
"Score": "2"
}
},
{
"body": "<p>This is an old question, but maybe worth reminding for people that .Count() has a useful overload. Re-writing the query in fluent syntax could let you write:</p>\n\n<pre><code>int count = ValidTypes()\n .SelectMany(type => GetData(type))\n .Count(point => point.Radius > referencePoint.Radius \n && point.Theta > referencePoint.Theta);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:50:04.020",
"Id": "10516",
"ParentId": "138",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "144",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-21T19:10:07.230",
"Id": "138",
"Score": "13",
"Tags": [
"c#",
"linq"
],
"Title": "Counting the number of points that have both a larger theta and a larger radius than a given point"
} | 138 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 75