body
stringlengths 25
86.7k
| 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>Basically, I had written this class a little while ago to ease autoloading of our local libraries. </p>
<p>The premise is that everything is split by packages into multiple layers of sub-packages. Classes are named using CamelCasing. So, a class' name is related to its package as follows: <code>PackageSubpackageSubpackageName</code>. Now, each package can have package specific interfaces defined by <code>isPackageName</code> for interfaces, exceptions by <code>PackageNameException</code>, etc. I tried to make it flexible enough for reuse.</p>
<pre><code>/**
* A class for lazy-loading other classes
*
* This class enables lazy-loading of php classes. The benefit of this is
* three-fold. First, there is a memory benefit, since not all classes are
* loaded until they are needed. Second, there is a time benefit, since not all
* classes are loaded. Third, it produces cleaner code, since there is no need
* to litter files with require_once() calls.
*
* @category Libraries
* @package Libraries
* @author Me
*/
abstract class Loader
{
/**
* @var array An array of class to path mappings
*/
protected static $classes = array();
/**
* @var boolean Has the loader been initialized already
*/
protected static $initialized = false;
/**
* @var array An array of auto-search paths
*/
protected static $namedPaths = array(
'exception',
'interface',
'iterator',
);
/**
* @var array An array of include paths to search
*/
protected static $paths = array(
PATH_LIBS,
);
/**
* Tell the auto-loader where to find an un-loaded class
*
* This can be used to "register" new classes that are unknown to the
* system. It can also be used to "overload" a class (redefine it
* elsewhere)
*
* @param string $class The class name to overload
* @param string $path The path to the new class
*
* @throws InvalidArgumentException Upon an Invalid path submission
* @return void
*/
public static function _($class, $path)
{
$class = strtolower($class);
if (!file_exists($path)) {
throw new InvalidArgumentException('Invalid Path Specified');
}
self::$classes[$class] = $path;
}
/**
* Add a path to the include path list
*
* This adds a path to the list of paths to search for an included file.
* This should not be used to overload classes, since the default include
* directory will always be searched first. This can be used to extend
* the search path to include new parts of the system
*
* @param string $path The path to add to the search list
*
* @throws InvalidArgumentException when an invalid path is specified
* @return void
*/
public static function addPath($path)
{
if (!is_dir($path)) {
throw new InvalidArgumentException('Invalid Include Path Added');
}
$path = rtrim($path, DS);
if (!in_array($path, self::$paths)) {
self::$paths[] = $path;
}
}
/**
* Add a path to the auto-search paths (for trailing extensions)
*
* The path should end with an 's'. Default files should not.
*
* @param string $path The name of the new auto-search path
*
* @return void
*/
public static function addNamedPath($path)
{
$path = strtolower($path);
if (substr($path, -1) == 's') {
$path = substr($path, 0, -1);
}
if (!in_array($path, self::$namedPaths)) {
self::$namedPaths[] = $path;
}
}
/**
* Initialize and register the autoloader.
*
* This method will setup the autoloader. This should only be called once.
*
* @return void
*/
public static function initialize()
{
if (!self::$initialized) {
self::$initialized = true;
spl_autoload_register(array('Loader', 'load'));
}
}
/**
* The actual auto-loading function.
*
* This is automatically called by PHP whenever a class name is used that
* doesn't exist yet. There should be no need to manually call this method.
*
* @param string $class The class name to load
*
* @return void
*/
public static function load($class)
{
$className = strtolower($class);
if (isset(self::$classes[$className])) {
$file = self::$classes[$className];
} else {
$file = self::findFile($class);
}
if (file_exists($file)) {
include_once $file;
}
}
/**
* Find the file to include based upon its name
*
* This splits the class name by uppercase letter, and then rejoins them
* to attain the file system path. So FooBarBaz will be turned into
* foo/bar/baz. It then searches the include paths for that chain. If baz
* is a directory, it searches that directory for a file called baz.php.
* Otherwise, it looks for baz.php under the bar directory.
*
* @param string $class The name of the class to find
*
* @return string The path to the file defining that class
*/
protected static function findFile($class)
{
$regex = '#([A-Z]{1}[a-z0-9_]+)#';
$options = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
$parts = preg_split($regex, $class, null, $options);
$subpath = '';
$file = strtolower(end($parts));
$test = strtolower(reset($parts));
if ($test == 'is') {
array_shift($parts);
return self::findNamedFile($class, $parts, 'interface');
}
foreach ($parts as $part) {
$subpath .= DS . strtolower($part);
}
foreach (self::$paths as $path) {
$newpath = $path . $subpath;
if (is_file($newpath . '.php')) {
return $newpath . '.php';
} elseif (is_file($newpath . DS . $file . '.php')) {
return $newpath . DS . $file . '.php';
}
}
if (in_array($file, self::$namedPaths)) {
//Get rid of the trailing part
array_pop($parts);
return self::findNamedFile($class, $parts, $file);
}
return '';
}
/**
* Find a file for named directories (interfaces, exceptions, iterators, etc)
*
* @param string $class The class name of the exception to find
* @param array $parts The parts of the class name pre-split
* @param string $name The name of the named directory to search in
*
* @return string The found path, or '' if not found
*/
protected static function findNamedFile($class, array $parts, $name)
{
if (empty($parts)) {
return '';
}
$name = strtolower($name);
//Add a trailing s, since individual files are not plural
$filename = $name;
$name .= 's';
//Try the global path first
$subpath = DS . $name . DS . strtolower(implode('', $parts)) . '.php';
foreach (self::$paths as $path) {
$newpath = $path . $subpath;
if (is_file($newpath)) {
return $newpath;
}
}
//Try to build a full sub path for package specific named files
$package = array_shift($parts);
$subpath = DS . strtolower($package) . DS . $name . DS;
if (!empty($parts)) {
$subpath .= strtolower(implode('', $parts)) . '.php';
} else {
$subpath .= $filename . '.php';
}
foreach (self::$paths as $path) {
$newpath = $path . $subpath;
if (is_file($newpath)) {
return $newpath;
}
}
return '';
}
}
</code></pre>
<p>It's also fully unit tested.</p>
<p>What are your thoughts? Is it over-complex?</p>
| [] | [
{
"body": "<p>The first problem I see is that there are a lot of cases where someone will want to create a class with more than one word in the name (DataMapper), and the autoloader you have provided won't allow for that. I would recommend using another character to delimit between package names. The Zend Framework uses Package_SubPackage_SubPackage_Class and that works very well.</p>\n\n<p>As an aside, I'm not sure what your specific reasons are for writing your own autoloader (whether it is for production, education, etc.), but if you are planning to use it for production, I would recommend the Zend_Loader class from the Zend Framework, as it is supported, fully tested, and continually being developed. You can read it's quickstart guide <a href=\"http://framework.zend.com/manual/en/zend.loader.load.html\">Here</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:37:23.417",
"Id": "36",
"Score": "4",
"body": "Well, it's personal preference, but I can't stand using `_` in class names. I find it's harder to type, and breaks it apart too much. As far as multiple words in a name, yes that's a valid point. And why don't I use Zend? Well, it's personal preference. I've tried it in the past, and didn't care for it. I can use it, but it just rubs me the wrong way... Thanks for the insight though..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:50:22.010",
"Id": "41",
"Score": "2",
"body": "To clarify, when I was talking about Zend, I wasn't recommending the entire framework, but just the autoloader class, which can be used completely decoupled from everything else in zf."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T23:36:09.610",
"Id": "63",
"Score": "2",
"body": "`HiMyNameIsRobertAndIWorkLongHoursSadFace` vs `Hi_My_Name_Is_Robert_And_I_Work_Long_Hours_Sad_Face`, i belive this is the reason for the `_`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T14:40:26.333",
"Id": "140",
"Score": "0",
"body": "@RobertPitt: I'd argue that if your class name is really that long, you need to refactor or rethink your packaging system..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:21:04.123",
"Id": "10",
"ParentId": "4",
"Score": "14"
}
},
{
"body": "<p>When it comes to Autoloaders, I would tend make it compatible with any of my projects, therefore I would always stay to the best coding standards such as Zend.</p>\n<p>There is a proposal that states the layout of classes, directory structure, namespaces where autoloaders work very good.</p>\n<p>The following describes the mandatory requirements that must be adhered to for autoloader interoperability.</p>\n<ul>\n<li><p>Mandatory:</p>\n</li>\n<li><p>A fully-qualified namespace and class must have the following structure:</p>\n<pre><code> \\<Vendor Name>\\(<Namespace>\\)*<Class Name>\n</code></pre>\n</li>\n<li><p>Each namespace must have a top-level namespace ("Vendor Name").</p>\n</li>\n<li><p>Each namespace can have as many sub-namespaces as it wishes.</p>\n</li>\n<li><p>Each namespace separator is converted to a <code>DIRECTORY_SEPARATOR</code> when loading from the file system.</p>\n</li>\n<li><p>Each <code>_</code> character in the CLASS NAME is converted to a <code>DIRECTORY_SEPARATOR</code>. The <code>_</code> character has no special meaning in the namespace.</p>\n</li>\n<li><p>The fully-qualified namespace and class is suffixed with ".php" when loading from the file system.</p>\n</li>\n<li><p>Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.</p>\n</li>\n<li><p>Examples:</p>\n</li>\n<li><p><code>\\Doctrine\\Common\\IsolatedClassLoader</code> => <code>/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php</code></p>\n</li>\n<li><p><code>\\Symfony\\Core\\Request</code> => <code>/path/to/project/lib/vendor/Symfony/Core/Request.php</code></p>\n</li>\n<li><p><code>\\Zend\\Acl</code> => <code>/path/to/project/lib/vendor/Zend/Acl.php</code></p>\n</li>\n<li><p><code>\\Zend\\Mail\\Message</code> => <code>/path/to/project/lib/vendor/Zend/Mail/Message.php</code></p>\n</li>\n</ul>\n<p>Using the above to construct your autoloader will surely be migratable around your projects regarding weather you have namespaces or not.</p>\n<p><a href=\"http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1\" rel=\"nofollow noreferrer\">@Reference</a></p>\n<p>There is a very nice class that I use in around 6 projects, and I find that this is perfect and you should study and see what you can do with it.</p>\n<p><a href=\"https://gist.github.com/221634\" rel=\"nofollow noreferrer\">Class Link</a></p>\n<p>An example usage would be like so:</p>\n<pre><code>$classLoader = new SplClassLoader('Doctrine\\Common', '/libs/doctrine');\n$classLoader->register();\n\n$classLoader = new SplClassLoader('Ircmexell\\MyApplication', 'libs/internal');\n$classLoader->register();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-01-19T23:12:28.693",
"Id": "40",
"ParentId": "4",
"Score": "6"
}
},
{
"body": "<p>Some points i found:</p>\n\n<p>Thats the class is marked as <code>abstract</code> struck me as odd as i found out it only has static method calls and since it uses \"self::\" for static call i guess there is no meaningful way to extend the class anyways. (With the LSB issue).</p>\n\n<p>I don't see any big issue with the class beeing \"all static\" and i assume it fits into your project. (You don't have a clear bootstrap and you don't want/need multiple instances of that class)</p>\n\n<hr>\n\n<p>The <code>include_once $file;</code> strucks me as a little odd as the \"_once\" part shouldn't be need. But if you wrote the loader at a later stage in the project i see where it might be needed to not run into issues with classes getting loaded two times.</p>\n\n<p>Usually i'd say you don't have to make php remember if it already touched a file (and do a disk expensive realpath() on it) since the load function will only be called one time for each previously unknown class.</p>\n\n<hr>\n\n<p>All in all i think the code/usefulness ratio is fine and it isn't overly complex.</p>\n\n<h2>Alternatives</h2>\n\n<p>The upcoming \"standards\" and libs are alreay mentioned so i'll just point out another way to do autoloading that \"performs better\" and is less intrusive (requires less code in your application)</p>\n\n<p>The <a href=\"https://github.com/theseer/Autoload\"><code>PHP Autoload Builder</code></a> will scan your codebase and provide one file with a big array mapping for all your classes (interface etc.) that you only need to include in your bootstrap. It can be run again to pick up new classes or the resulting file can be edited by hand. (Some people build tools around it so it automatically recreates itself in development if a class isn't found).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T11:04:43.753",
"Id": "86",
"ParentId": "4",
"Score": "8"
}
},
{
"body": "<p>For about a year I used a very simple autoloader with common PHP files root for my project and all included libraries (Zend, Rediska and so on).</p>\n\n<p>The root of my project contains /app and /external directories.</p>\n\n<p>All libraries in /external are fully checked out from svn/git, and then I make a symlink for their PHP code in /app.</p>\n\n<p>For example, for <code>PHPExcel</code>:</p>\n\n<pre><code>pwd \n/var/www/project/app\nls -lah PHPE*\nPHPExcel -> ../external/PHPExcel/PHPExcel\nPHPExcel.php -> ../external/PHPExcel/PHPExcel.php\n</code></pre>\n\n<p>Then I put something like this in my index.php file:</p>\n\n<pre><code>set_include_path (PATH . 'app');\nrequire 'somepath/Autoloader.php';\nAutoloader::registerAutoload ();\n</code></pre>\n\n<p>It allows me to use one commonly (it's fully compatible with Zend, Rediska, PHPExcel and many other libraries) and is a very simple autoloader for all libraries.</p>\n\n<pre><code>class Autoloader\n{\n\n public static function registerAutoload ()\n {\n spl_autoload_register (array (__CLASS__, 'autoload'));\n }\n\n /**\n * @static\n * @param string $class\n * @return void\n */\n public static function autoload ($class)\n {\n require str_replace (array ('_', '\\\\'), '/', $class) . '.php';\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-12T16:25:43.170",
"Id": "1812",
"ParentId": "4",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:07:43.573",
"Id": "4",
"Score": "27",
"Tags": [
"php",
"library"
],
"Title": "PHP Autoloader Library"
} | 4 |
<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 have a method that has a lot of loops:</p>
<pre><code>private void update(double depth)
{
Console.WriteLine("update with level " + depth);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{
List<Grid> grids = new List<Grid>();
Dependencies.Children.Clear();
Grid g = new Grid();
//Canvas.SetZIndex(g, 100);
g.Width = 50;
g.Height = 50;
g.Tag = focus;
Ellipse e = new Ellipse();
e.Width = 50;
e.Height = 50;
e.Fill = Brushes.Red;
if (depth == 1)
{
Canvas.SetTop(g, 163);
}
else if (depth == 2)
{
Canvas.SetTop(g, 108);
}
else if (depth == 3)
{
Canvas.SetTop(g, 81);
}
else if (depth == 4)
{
Canvas.SetTop(g, 65);
}
else if (depth == 5)
{
Canvas.SetTop(g, 54);
}
else if (depth == 6)
{
Canvas.SetTop(g, 46);
}
Canvas.SetLeft(g, 500);
g.Children.Add(e);
Viewbox box = new Viewbox();
box.Width = e.Width;
box.Height = e.Height;
TextBox txt = new TextBox();
txt.Text = focus.getName();
box.Child = txt;
txt.Background = Brushes.Transparent;
txt.BorderBrush = Brushes.Transparent;
g.Children.Add(box);
grids.Add(g);
List<SourceFile> list = new List<SourceFile>();
list = focus.getInvocations();
int counter = 1;
foreach (SourceFile sf in list)
{
Grid g1 = new Grid();
//Canvas.SetZIndex(g, 101);
g1.Width = 50;
g1.Height = 50;
g1.Tag = sf;
Ellipse e1 = new Ellipse();
//Dependencies.Children.Add(e1);
sf.setGrid(g1);
e1.Width = 50;
e1.Height = 50;
e1.Fill = Brushes.Red;
g1.Children.Add(e1);
if (depth == 1)
{
Canvas.SetTop(g1, 488);
}
else if (depth == 2)
{
Canvas.SetTop(g1, 324);
}
else if (depth == 3)
{
Canvas.SetTop(g1, 244);
}
else if (depth == 4)
{
Canvas.SetTop(g1, 195);
}
else if (depth == 5)
{
Canvas.SetTop(g1, 163);
}
else if (depth == 6)
{
Canvas.SetTop(g1, 139);
}
Canvas.SetLeft(g1, counter * (1000 / (list.Count + 1) ));
Viewbox box1 = new Viewbox();
box1.Width = g1.Width;
box1.Height = g1.Height;
TextBox txt1 = new TextBox();
txt1.Text = sf.getName();
txt1.Background = Brushes.Transparent;
txt1.BorderBrush = Brushes.Transparent;
box1.Child = txt1;
g1.Children.Add(box1);
Line l = new Line();
//Canvas.SetZIndex(l, 1);
l.Stroke = Brushes.Green;
l.StrokeThickness = 10;
Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty);
x1.Converter = new MyConverter();
x1.ConverterParameter = g;
Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty);
y1.Converter = new MyConverter();
y1.ConverterParameter = g;
Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty);
x2.Converter = new MyConverter();
x2.ConverterParameter = g1;
Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty);
y2.Converter = new MyConverter();
y2.ConverterParameter = g1;
x1.Source = y1.Source = g;
x2.Source = y2.Source = g1;
l.SetBinding(Line.X1Property, x1);
l.SetBinding(Line.Y1Property, y1);
l.SetBinding(Line.X2Property, x2);
l.SetBinding(Line.Y2Property, y2);
Dependencies.Children.Add(l);
l.Tag = new Call(focus, sf);
Contacts.AddPreviewContactDownHandler(l, OnLineDown);
counter++;
grids.Add(g1);
SizeChangedEventHandler act = (Object s, SizeChangedEventArgs args) =>
{
BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget();
};
g.SizeChanged += act;
g1.SizeChanged += act;
}
int counter2 = 1;
if (depth >= 2)
{
int invocCount = 0;
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
invocCount = invocCount + s.getInvocations().Count;
}
}
Console.WriteLine(invocCount);
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
Console.WriteLine("`Found invocation of " + s.getName() + ": " + source.getName());
Grid g1 = new Grid();
g1.Width = 50;
g1.Height = 50;
Ellipse e1 = new Ellipse();
// Canvas.SetZIndex(g1, 102);
grids.Add(g1);
e1.Width = 50;
e1.Height = 50;
e1.Fill = Brushes.Red;
source.setGrid(g1);
g1.Tag = source;
g1.Children.Add(e1);
if (depth == 2)
{
Canvas.SetTop(g1, 540);
}
else if (depth == 3)
{
Canvas.SetTop(g1, 406);
}
else if (depth == 4)
{
Canvas.SetTop(g1, 325);
}
else if (depth == 5)
{
Canvas.SetTop(g1, 271);
}
else if (depth == 6)
{
Canvas.SetTop(g1, 232);
}
Canvas.SetLeft(g1, counter2 * (1000 / (invocCount + 1)));
Viewbox box1 = new Viewbox();
box1.Width = g1.Width;
box1.Height = g1.Height;
TextBox txt1 = new TextBox();
txt1.Text = source.getName();
txt1.Background = Brushes.Transparent;
txt1.BorderBrush = Brushes.Transparent;
box1.Child = txt1;
g1.Children.Add(box1);
Line l = new Line();
//Canvas.SetZIndex(l, 2);
l.Stroke = Brushes.Green;
l.StrokeThickness = 10;
Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty);
x1.Converter = new MyConverter();
x1.ConverterParameter = s.getGrid();
Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty);
y1.Converter = new MyConverter();
y1.ConverterParameter = s.getGrid();
Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty);
x2.Converter = new MyConverter();
x2.ConverterParameter = g1;
Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty);
y2.Converter = new MyConverter();
y2.ConverterParameter = g1;
x1.Source = y1.Source = findGrid(grids, s, source);
x2.Source = y2.Source = g1;
l.SetBinding(Line.X1Property, x1);
l.SetBinding(Line.Y1Property, y1);
l.SetBinding(Line.X2Property, x2);
l.SetBinding(Line.Y2Property, y2);
Dependencies.Children.Add(l);
l.Tag = new Call(s, source);
Contacts.AddPreviewContactDownHandler(l, OnLineDown);
counter2++;
SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =>
{
BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget();
};
source.getGrid().SizeChanged += act;
g1.SizeChanged += act;
}
}
}
int counter3 = 1;
if (depth >= 3)
{
int invocCount = 0;
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
invocCount = invocCount + source.getInvocations().Count;
}
}
}
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
Grid g1 = new Grid();
grids.Add(g1);
g1.Width = 50;
g1.Height = 50;
g1.Tag = s1;
Ellipse e1 = new Ellipse();
e1.Width = 50;
e1.Height = 50;
e1.Fill = Brushes.Red;
s1.setGrid(g1);
g1.Children.Add(e1);
if (depth == 3)
{
Canvas.SetTop(g1, 569);
}
else if (depth == 4)
{
Canvas.SetTop(g1, 455);
}
else if (depth == 5)
{
Canvas.SetTop(g1, 379);
}
else if (depth == 6)
{
Canvas.SetTop(g1, 325);
}
Canvas.SetLeft(g1, counter3 * (1000 / (invocCount + 1)));
Viewbox box1 = new Viewbox();
box1.Width = g1.Width;
box1.Height = g1.Height;
TextBox txt1 = new TextBox();
txt1.Background = Brushes.Transparent;
txt1.BorderBrush = Brushes.Transparent;
txt1.Text = s1.getName();
box1.Child = txt1;
g1.Children.Add(box1);
Line l = new Line();
//Canvas.SetZIndex(l, 2);
l.Stroke = Brushes.Green;
l.StrokeThickness = 10;
Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty);
x1.Converter = new MyConverter();
x1.ConverterParameter = source.getGrid();
Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty);
y1.Converter = new MyConverter();
y1.ConverterParameter = source.getGrid();
Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty);
x2.Converter = new MyConverter();
x2.ConverterParameter = g1;
Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty);
y2.Converter = new MyConverter();
y2.ConverterParameter = g1;
x1.Source = y1.Source = findGrid(grids, source, s1);
x2.Source = y2.Source = g1;
l.SetBinding(Line.X1Property, x1);
l.SetBinding(Line.Y1Property, y1);
l.SetBinding(Line.X2Property, x2);
l.SetBinding(Line.Y2Property, y2);
Dependencies.Children.Add(l);
l.Tag = new Call(source, s1);
Contacts.AddPreviewContactDownHandler(l, OnLineDown);
counter3++;
SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =>
{
BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget();
};
s1.getGrid().SizeChanged += act;
g1.SizeChanged += act;
}
}
}
}
int counter4 = 1;
if (depth >= 4)
{
int invoCount = 0;
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
foreach (SourceFile s2 in s1.getInvocations())
{
invoCount = invoCount + s1.getInvocations().Count;
}
}
}
}
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
foreach (SourceFile s2 in s1.getInvocations())
{
Grid g1 = new Grid();
grids.Add(g1);
g1.Width = 50;
g1.Height = 50;
g1.Tag = s2;
Ellipse e1 = new Ellipse();
e1.Width = 50;
e1.Height = 50;
e1.Fill = Brushes.Red;
s2.setGrid(g1);
g1.Children.Add(e1);
if (depth == 4)
{
Canvas.SetTop(g1, 585);
}
else if (depth == 5)
{
Canvas.SetTop(g1, 488);
}
else if (depth == 6)
{
Canvas.SetTop(g1, 418);
}
Canvas.SetLeft(g1, counter4 * (1000 / (invoCount + 1)));
Viewbox box1 = new Viewbox();
box1.Width = g1.Width;
box1.Height = g1.Height;
TextBox txt1 = new TextBox();
txt1.Background = Brushes.Transparent;
txt1.BorderBrush = Brushes.Transparent;
txt1.Text = s2.getName();
box1.Child = txt1;
g1.Children.Add(box1);
Line l = new Line();
//Canvas.SetZIndex(l, 2);
l.Stroke = Brushes.Green;
l.StrokeThickness = 10;
Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty);
x1.Converter = new MyConverter();
x1.ConverterParameter = s1.getGrid();
Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty);
y1.Converter = new MyConverter();
y1.ConverterParameter = s1.getGrid();
Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty);
x2.Converter = new MyConverter();
x2.ConverterParameter = g1;
Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty);
y2.Converter = new MyConverter();
y2.ConverterParameter = g1;
x1.Source = y1.Source = findGrid(grids, s1, s2);
x2.Source = y2.Source = g1;
l.SetBinding(Line.X1Property, x1);
l.SetBinding(Line.Y1Property, y1);
l.SetBinding(Line.X2Property, x2);
l.SetBinding(Line.Y2Property, y2);
Dependencies.Children.Add(l);
l.Tag = new Call(s1, s2);
Contacts.AddPreviewContactDownHandler(l, OnLineDown);
counter4++;
SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =>
{
BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget();
};
s2.getGrid().SizeChanged += act;
g1.SizeChanged += act;
}
}
}
}
}
int counter5 = 1;
if (depth >= 5)
{
int invoCount = 0;
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
foreach (SourceFile s2 in s1.getInvocations())
{
foreach (SourceFile s3 in s2.getInvocations())
{
invoCount = invoCount + s2.getInvocations().Count;
}
}
}
}
}
foreach (SourceFile s in list)
{
foreach (SourceFile source in s.getInvocations())
{
foreach (SourceFile s1 in source.getInvocations())
{
foreach (SourceFile s2 in s1.getInvocations())
{
foreach (SourceFile s3 in s2.getInvocations())
{
Grid g1 = new Grid();
g1.Width = 50;
g1.Height = 50;
grids.Add(g1);
g1.Tag = s3;
Ellipse e1 = new Ellipse();
//Dependencies.Children.Add(e1);
e1.Width = 50;
e1.Height = 50;
e1.Fill = Brushes.Red;
s3.setGrid(g1);
g1.Children.Add(e1);
if (depth == 5)
{
Canvas.SetTop(g1, 596);
}
else if (depth == 6)
{
Canvas.SetTop(g1, 511);
}
Canvas.SetLeft(g1, counter5 * (1000 / (invoCount + 1)));
Viewbox box1 = new Viewbox();
box1.Width = g1.Width;
box1.Height = g1.Height;
TextBox txt1 = new TextBox();
txt1.Background = Brushes.Transparent;
txt1.BorderBrush = Brushes.Transparent;
txt1.Text = s3.getName();
box1.Child = txt1;
g1.Children.Add(box1);
Line l = new Line();
//Canvas.SetZIndex(l, 2);
l.Stroke = Brushes.Green;
l.StrokeThickness = 10;
Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty);
x1.Converter = new MyConverter();
x1.ConverterParameter = s2.getGrid();
Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty);
y1.Converter = new MyConverter();
y1.ConverterParameter = s2.getGrid();
Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty);
x2.Converter = new MyConverter();
x2.ConverterParameter = g1;
Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty);
y2.Converter = new MyConverter();
y2.ConverterParameter = g1;
x1.Source = y1.Source = findGrid(grids, s2, s3);
x2.Source = y2.Source = g1;
l.SetBinding(Line.X1Property, x1);
l.SetBinding(Line.Y1Property, y1);
l.SetBinding(Line.X2Property, x2);
l.SetBinding(Line.Y2Property, y2);
l.Tag = new Call(s2, s3);
Contacts.AddPreviewContactDownHandler(l, OnLineDown);
Dependencies.Children.Add(l);
counter5++;
SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =>
{
BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget();
BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget();
};
s3.getGrid().SizeChanged += act;
g1.SizeChanged += act;
}
}
}
}
}
}
foreach (Grid grid in grids)
{
Dependencies.Children.Add(grid);
Contacts.AddPreviewContactDownHandler(grid, DownOnSourceFile);
}
}
));
}
</code></pre>
<p>Is there any easy way to improve that? And to make it working not only for 6 steps but also for n steps?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:26:50.047",
"Id": "29",
"Score": "17",
"body": "tl;dr. You'll likely have a better response if you remove a lot of the boilerplate or focus on the part you're really interested in. I think pseudo-code would help a lot here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:20:41.843",
"Id": "66",
"Score": "12",
"body": "Whenever you think of using copy and paste, don't. Make a method and call it twice."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T01:04:20.503",
"Id": "175",
"Score": "3",
"body": "Break your method into a lot of smaller ones."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:15:14.470",
"Id": "984",
"Score": "0",
"body": "Even with your code abstracted, changing this from a static depth to n-depth is very non-trivial and off topic for this site. You will require formulas instead of constants and recursion or otherwise completely different looping structure to walk the tree (depending on how deep you want to go recursion becomes problematic due to limited stack space, though optimizations on x64 machines may be able to help with that). Regardless, the review is unanimous: refactor/abstract and improve naming; the solution to your unsolved problem, however, is for a different site."
}
] | [
{
"body": "<p>Break this down into several methods - it's very long, meaning it's not easy to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:28:01.803",
"Id": "67",
"Score": "1",
"body": "Actually it is even longer ;) I wasn't able to post the whole method because of the character limit;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T01:10:53.220",
"Id": "176",
"Score": "2",
"body": "@Roflcoptr You must be trying to beat my former supervisor 1200 lines-long methods. Definitely break it down, it is a nightmare in the making."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T10:24:32.597",
"Id": "180",
"Score": "1",
"body": "+1 definitely break it down to smaller methods - and use some Linq as well!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-05T01:31:34.790",
"Id": "161872",
"Score": "0",
"body": "@Roflcoptr In the future if you need to post a lot of code maybe try [GitHub Gists](https://gist.github.com/). *(Although, it's likely a good indicator that your example it too long if it won't fit.)*"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:24:59.400",
"Id": "13",
"ParentId": "9",
"Score": "63"
}
},
{
"body": "<p>Give some thought to abstracting the decisions around setting the top of the canvas (cf. all those <code>if</code> statements) out into a set of classes - or perhaps a single class with different suitable parameters in the constructor. A lot of this code differs only in the numbers being applied.</p>\n\n<p>A simple rule is \"Abstract the concept that varies\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:27:45.830",
"Id": "15",
"ParentId": "9",
"Score": "18"
}
},
{
"body": "<p>For the n steps bit, consider using recursion - but tread carefully.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:29:04.710",
"Id": "17",
"ParentId": "9",
"Score": "6"
}
},
{
"body": "<p>I might recommend the use of switch statements and white space along with LRE's suggestion of breaking this into multiple methods. It also looks like you have quite a bit of repeated code maybe try to break that out for sure it its own methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:41:45.367",
"Id": "52",
"Score": "0",
"body": "In this case switch may not be the best option. It would make the code use case instead of if/else but the code will almost be equally lengthy"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T21:29:43.017",
"Id": "18",
"ParentId": "9",
"Score": "9"
}
},
{
"body": "<p>This code...</p>\n\n<pre><code>if (depth == 1)\n{\n Canvas.SetTop(g1, 163);\n}\nelse if (depth == 2)\n{\n Canvas.SetTop(g1, 108);\n}\nelse if (depth == 3)\n{\n Canvas.SetTop(g1, 81);\n}\nelse if (depth == 4)\n{\n Canvas.SetTop(g1, 65);\n}\nelse if (depth == 5)\n{\n Canvas.SetTop(g1, 54);\n}\nelse if (depth == 6)\n{\n Canvas.SetTop(g1, 46);\n}\n</code></pre>\n\n<p>Could be better implemented using an array...</p>\n\n<pre><code>int[] values = new [] { 0, 163, 108, 81, 65, 54, 46 }\n</code></pre>\n\n<p>Or Dictionary...</p>\n\n<pre><code>var values = new Dictionary<int,int>() { { 1, 163 }, { 2, 108 }, { 3, 81 }, { 4, 65 }, { 5, 54 }, { 6, 46} };\n</code></pre>\n\n<p>This way you could simple say</p>\n\n<pre><code>Canvas.SetTop(g1, values[depth])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:42:45.400",
"Id": "69",
"Score": "3",
"body": "alternatively, a switch statement would help and introduce absolutely no overhead (in fact, it's faster than repeated `if/else` operations)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T02:18:44.180",
"Id": "78",
"Score": "16",
"body": "@Felix: But a switch statement wouldn't really make the code shorter."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T22:03:07.877",
"Id": "167",
"Score": "4",
"body": "There seem to be some prejudices towards using a control statement exactly for what it was made. I embrace brevity, but if this is in its own method it will be readable again, and if performance makes a difference, I would strongly prefer the switch statement"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T23:59:50.233",
"Id": "171",
"Score": "2",
"body": "Don't forget The question says it should be done not just for 6 but for n iterations. There's no such thing as a dynamic-n-cases-switch. But I do agree that portion of code should be in it own method"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T09:19:19.733",
"Id": "179",
"Score": "0",
"body": "I'm not sure if replacing the else ifs with this is any more readable and if the code would would perform better.."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T14:36:58.320",
"Id": "187",
"Score": "0",
"body": "Mmmm let's see. How would you implement this mathematical function: f(x) = 3x . This way: F(int x) { return 3 * x } Or this way: F(int x) { if ( x == 1 ) return 3; if (x == 2) return 6; if (x == 3) return 9; ..... } or maybe this way: F(int x) { switch (x) { case 1: return 3; case 2: return 6; case 3 return 9; ..... } }"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-21T15:36:19.860",
"Id": "197",
"Score": "1",
"body": "@Carlos right -- what we need is a formula to spit out a number for any *n*. I can't think of the right one just now, but it probably has do something with log2"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-19T22:34:52.687",
"Id": "29",
"ParentId": "9",
"Score": "59"
}
},
{
"body": "<p>Break your code into its own methods definitely, there are other ways, but that will probably be the easiest and less time consuming way to make it easier read and debug down the track for a start.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:18:27.980",
"Id": "46",
"ParentId": "9",
"Score": "3"
}
},
{
"body": "<p>There are a couple of immediately obvious things that havent been mentioned yet:</p>\n\n<p>You have a lot of magic numbers in your code. Try to define them as <code>const</code>s with meaningful names.</p>\n\n<p>For example </p>\n\n<p><code>g.Width = 50;</code></p>\n\n<p>becomes</p>\n\n<pre><code>private const int DefaultGridWidth = 50;\n...\ng.Width = DefaultGridWidth;\n</code></pre>\n\n<p>It seems like a trivial change but it makes a big difference to someone who is reading your code. It gives an indication of <strong>why</strong> the value is 50, not just that it <strong>is</strong> 50.\n<hr>\nYou should use more meaningful names for your identifiers. Names like <code>g</code> and <code>g1</code> do not tell me a lot about what the object is, but <code>mainGrid</code> and <code>innerGrid</code> contain more information for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T22:05:40.760",
"Id": "168",
"Score": "0",
"body": "That is indeed true, too many literals in code make it harder to maintain and adapt, especially so if there are cross-dependencies among the values!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T07:47:00.157",
"Id": "2434",
"Score": "1",
"body": "He should use static readonly instead of const - then he won't have to recompile assemblies that depend on his code with every change! Also, he's not limited to only values but can use references as constants as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T10:33:10.783",
"Id": "84",
"ParentId": "9",
"Score": "29"
}
},
{
"body": "<p>This should simplify the looping assuming that you can generalize the positioning code like mention in several of the other answers</p>\n\n<pre><code> //Get the initial set of sourcefiles\n var sourceFiles = from file in list\n from invocation in file.getInvocations()\n group invocation by (SourceFile)null into groupedByInvoker\n select groupedByInvoker;\n\n for (var currentDepth = 0; currentDepth <= depth; currentDepth++)\n {\n foreach (var currentGroup in sourceFiles)\n {\n int sourceFileCount = currentGroup.Count();\n int counter = 0;\n\n foreach (var invocation in currentGroup)\n {\n /*\n * Generalized grid code goes here\n */\n counter++;\n }\n }\n\n //Select the current sub source files\n sourceFiles = from invokerGroup in sourceFiles\n from file in invokerGroup\n from invocation in file.getInvocations()\n group invocation by file into groupedByInvoker\n select groupedByInvoker;\n\n }\n</code></pre>\n\n<p>This is not an exact mapping to the above code in that this goes over the getInvocations tree breadth first instead of depth first.</p>\n\n<p>Updated with imput from <a href=\"https://codereview.stackexchange.com/questions/182/is-this-linq-code-clear-enough-and-how-could-i-improve-it/329#329\">Update grid from source hierarchy</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T21:43:51.547",
"Id": "117",
"ParentId": "9",
"Score": "7"
}
},
{
"body": "<p>Since you're using C#, you can make your initializers a bit nicer:</p>\n\n<pre><code>Grid g = new Grid()\n{\n Width = 50,\n Height = 50,\n Tag = focus,\n}\n//Canvas.SetZIndex(g, 100);\n</code></pre>\n\n<p>The last part of your code (or rather, the second half) does very similar things multiple times: code duplication is a sign your code can be made clearer. For instance (note that your code almost surely contains a bug! The statement inside all the loops invokes s2 and not s3):</p>\n\n<pre><code>foreach (SourceFile s in list)\n{\n foreach (SourceFile source in s.getInvocations())\n {\n foreach (SourceFile s1 in source.getInvocations())\n {\n foreach (SourceFile s2 in s1.getInvocations())\n {\n foreach (SourceFile s3 in s2.getInvocations())\n {\n invoCount = invoCount + s2.getInvocations().Count;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>can be changed into</p>\n\n<pre><code>list.CountRecursive(t => t.getInvocations(), t => t.getInvocations().Count, 5);\n\n(...)\n\npublic static int CountRecursive<T>(this IEnumerable<T> x, Func<T, IEnumerable<T>> f, Func<T, int> c, int depth)\n{\n int counter = 0;\n foreach (T t in x)\n {\n if (depth > 1)\n {\n counter += f(t).CountRecursive(f, c, depth - 1);\n }\n else\n {\n counter += c(t);\n }\n }\n return counter;\n}\n</code></pre>\n\n<p>which also makes it a lot easier to do it for different recursion levels.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-21T00:30:18.750",
"Id": "122",
"ParentId": "9",
"Score": "18"
}
},
{
"body": "<p>I refactored it for you. I did all of this without testing, so there's likely a bunch of bugs and off-by-one errors. I also made some assumptions about the code that you didn't include. Now that the code's a lot smaller, it should be easier for you to find those bugs.</p>\n\n<p>A couple of important points:</p>\n\n<ol>\n<li><p>Recursion is a fundamental concept in programming. If you are a professional programmer, you absolutely must be comfortable with it, or you will never be able to deal with nested structures effectively.</p></li>\n<li><p>If you copy and paste, you're doing it wrong. Every time you hit Ctrl+C, a kitten dies. No no no.</p></li>\n<li><p>If you have variables named <code>something1</code>, <code>something2</code>, <code>something3</code>, etc. <em>you're doing it wrong</em>. At the very least, those should be an array.</p></li>\n<li><p>You had <code>depth</code> as a <code>double</code> but were comparing it to literal values other than zero. That's bad.</p></li>\n</ol>\n\n<p>Here you go:</p>\n\n<pre><code>private void update(int depth)\n{\n Console.WriteLine(\"update with level \" + depth);\n\n Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()\n {\n List<Grid> grids = new List<Grid>();\n\n Dependencies.Children.Clear();\n\n Grid grid = MakeOuterGrid(grids, focus, e.Width, e.Height, depth);\n\n List<SourceFile> list = focus.getInvocations();\n\n for (int i = 1; i <= depth; i++)\n {\n int invocCount = CountInvocations(focus, i + 1);\n int counter = 0;\n MakeRecursiveGrids(grids, null, focus, i, invocCount, i, ref counter);\n }\n\n foreach (Grid grid in grids)\n {\n Dependencies.Children.Add(grid);\n Contacts.AddPreviewContactDownHandler(grid, DownOnSourceFile);\n }\n }));\n}\n\nvoid AdjustTop(int depth, int table) {\n int[][] depthTable = new int[][] {\n new int[] { 163, 108, 81, 65, 54, 46 },\n new int[] { 488, 324, 244, 195, 163, 139 },\n new int[] { -1, 540, 406, 325, 271, 232 },\n new int[] { -1, -1, 569, 455, 379, 325 },\n new int[] { -1, -1, -1, 585, 488, 418 },\n new int[] { -1, -1, -1, -1, 596, 511 },\n }\n\n int[] depths = depthTable[table];\n if ((depth < depths.Length) && (depths[depth - 1] != -1)) {\n Canvas.SetTop(depths[depth - 1]);\n }\n}\n\nSizeChangedEventHandler UpdateBindings(Line line) {\n SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =>\n {\n BindingOperations.GetBindingExpressionBase(line, Line.X1Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.Y1Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.X2Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.Y2Property).UpdateTarget();\n };\n\n return act;\n}\n\nint CountInvocations(SourceFile source, int depth)\n{\n int count = 0;\n\n if (depth > 0)\n {\n foreach (SourceFile inner in source.getInvocations())\n {\n count = count + CountInvocations(inner, depth - 1);\n }\n }\n else\n {\n count = source.Count;\n }\n\n return count;\n}\n\nGrid MakeGrid(List<Grid> grids, SourceFile source)\n{\n Grid grid = new Grid();\n grid.Width = 50;\n grid.Height = 50;\n grid.Tag = source;\n source.setGrid(grid);\n grids.Add(grid);\n\n Ellipse ellipse = new Ellipse();\n ellipse.Width = 50;\n ellipse.Height = 50;\n ellipse.Fill = Brushes.Red;\n\n grid.Children.Add(ellipse);\n\n return grids;\n}\n\nvoid MakeRecursiveGrids(List<Grid> grids, SourceFile outer, SourceFile source,\n int maxDepth, int invocCount, int recurseDepth, ref int counter)\n{\n if (recurseDepth > 0)\n {\n foreach (SourceFile inner in source)\n {\n MakeRecursiveGrids(grids, source, inner, maxDepth, invocCount,\n recurseDepth - 1, ref counter);\n }\n }\n else\n {\n MakeGrid(grids, outer, inner, depth, maxDepth, invocCount, counter);\n counter++;\n }\n}\n\nGrid MakeGrid(List<Grid> grids, SourceFile outer, SourceFile inner,\n int depth, int[] depths, int invocCount, int counter)\n{\n Grid grid = MakeGrid(grids, inner);\n\n MakeViewbox(grid, grid.Width, grid.Height, inner.getName());\n\n AdjustTop(depth, depths);\n Canvas.SetLeft(grid, counter * (1000 / (invocCount + 1)));\n\n MakeLine(grids, grid, outer, inner);\n\n return grid;\n}\n\nGrid MakeOuterGrid(List<Grid> grids, SourceFile inner, int width, int height,\n int depth)\n{\n Grid grid = MakeGrid(grids, inner);\n\n MakeViewbox(grid, width, height, inner.getName());\n\n AdjustTop(depth, 0);\n Canvas.SetLeft(grid, 500);\n\n return grid;\n}\n\nBinding MakeBinding(Object parameter, Grid grid)\n{\n Binding binding = new Binding();\n binding.Path = new PropertyPath(parameter);\n binding.Converter = new MyConverter();\n binding.ConverterParameter = grid;\n}\n\nvoid MakeLine(List<Grid> grids, Grid grid, SourceFile outer, SourceFile inner)\n{\n Grid g2 = outer.getGrid();\n\n Line line = new Line();\n line.Stroke = Brushes.Green;\n line.StrokeThickness = 10;\n\n Binding x1 = MakeBinding(Canvas.LeftProperty, g2);\n Binding y1 = MakeBinding(Canvas.TopProperty, g2);\n Binding x2 = MakeBinding(Canvas.LeftProperty, grid);\n Binding y2 = MakeBinding(Canvas.TopProperty, grid);\n\n Grid g = findGrid(grids, outer, inner);\n x1.Source = g;\n y1.Source = g;\n x2.Source = grid;\n y2.Source = grid;\n\n line.SetBinding(Line.X1Property, x1);\n line.SetBinding(Line.Y1Property, y1);\n line.SetBinding(Line.X2Property, x2);\n line.SetBinding(Line.Y2Property, y2);\n\n Dependencies.Children.Add(line);\n\n Contacts.AddPreviewContactDownHandler(line, OnLineDown);\n\n line.Tag = new Call(outer, inner);\n\n SizeChangedEventHandler act = UpdateBindings(line);\n inner.getGrid().SizeChanged += act;\n g1.SizeChanged += act;\n}\n\nvoid MakeViewBox(Grid grid, int width, int height, string text)\n{\n Viewbox box = new Viewbox();\n box.Width = width;\n box.Height = height;\n\n TextBox textBox = new TextBox();\n textBox.Text = text;\n\n box.Child = textBox;\n\n grid.Children.Add(box);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T19:12:58.543",
"Id": "315",
"ParentId": "9",
"Score": "8"
}
},
{
"body": "<p>Instead of <code>Grid g</code> and <code>Ellipse e</code>, use <code>Grid grid</code> and <code>Ellipse ellipse</code>. A loc with <code>e.size=</code> says less than <code>ellipse.Size=</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T21:47:30.027",
"Id": "523",
"Score": "0",
"body": "You're absoluletly right, but I don't think that this is the real problem here ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-27T19:44:05.510",
"Id": "320",
"ParentId": "9",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "13",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-19T21:19:59.470",
"Id": "9",
"Score": "34",
"Tags": [
"c#",
"performance",
"algorithm"
],
"Title": "Too many loops in Drawing App"
} | 9 |
<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"
}
},
{
"body": "<p>Personally I think your going the wrong way about things, you can easily pass in a query string into the <code>select</code> method and set the 2nd param to true to bypass backticks.</p>\n<p>So the output would place the sub query string within the main query select.</p>\n<p>I would do something along the lines of:</p>\n<pre><code>class MyModel extends Model\n{\n public function getRows()\n {\n //Create a subquery and render it to a stirng\n $sub = $this->db->select('number')->from('numbers')->where('numberID', 2)->_compile_select();\n\n //Clear the data from the CI Arrays\n $this->db->_reset_select();\n\n //Build the main query passing in the sub-query and disabling backticks\n $this->db->select("word,(" . $sub . ")", false)->where('wordID', 3);\n\n //Get the results\n $result = $this->get("words");\n }\n}\n</code></pre>\n<p>Sources:</p>\n<ul>\n<li>@ <a href=\"https://bitbucket.org/ellislab/codeigniter/src/b84189dcdfe3/system/database/DB_active_rec.php#cl-1693\" rel=\"noreferrer\">_compile_select()</a></li>\n<li>@ <a href=\"https://bitbucket.org/ellislab/codeigniter/src/b84189dcdfe3/system/database/DB_active_rec.php#cl-2022\" rel=\"noreferrer\">_reset_select()</a></li>\n</ul>\n<p>Firstly let me just state that the code above may not be fully working as i have not test machine a.t.m, but I do know that this is possible and you do not need all the extra logic specified.</p>\n<p>It seems pretty simple to me without creating new <code>$db</code>'s.</p>\n<p>I also would recommend you encapsulate the logic above into a class so you can pass the object's around and make life simpler as the above is a <strong>POC</strong></p>\n<hr />\n<h1>Concept:</h1>\n<pre><code>class InnerQuery extends CI_DB_active_record\n{\n public function __construct()\n { \n }\n\n public function __call($method,$params = array())\n {\n //Remove methods that modify the database\n switch(strtolower($method))\n {\n case 'get':\n case 'count_all_results':\n case 'get_where':\n trigger_error("Cannot use {$method} in InnerQuery");\n break;\n }\n return $this;\n }\n \n public function compile()\n {\n return "(" . $this->_compile_select() . ")";\n }\n\n public function __tostring()\n {\n return $this->compile();\n }\n}\n</code></pre>\n<p>Ok so the above class extends the same object as <code>$this->db</code> in your controller, so you can use all the methods to build a query such as</p>\n<pre><code>$this->InnerQuery->select("item as item_key")->from("inner_table")->where("foo","zed");\n</code></pre>\n<p>You should disable the parent methods that change the database or run any queries as this is only used to build a select string.</p>\n<p>so you should in thoery be able to do:</p>\n<pre><code>$this->db->select("word")->where('wordID', 3);\n$this->db->select($this->InnerQuery,false);\n</code></pre>\n<p>which would use the DB class to build your query and can just be passed into the outer select and the <code>__tostring</code> will return the <code>(SELECT ...)</code> with braces and pass it into the main query.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T15:05:01.903",
"Id": "440",
"Score": "0",
"body": "I'd rather not have to call `_compile_select()` and `_reset_select()` on the main DB object. That would mean I'd have to declare all subqueries before the rest of the query, and I don't want to have to do that. Also, the point of this library is to abstract this."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T15:08:36.913",
"Id": "442",
"Score": "0",
"body": "But I also stated that *I aso would recommend you encapsulate the logic above into a class so you can pass the object's around and make life simpler.* this would resolve that issue"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-28T05:09:20.367",
"Id": "549",
"Score": "0",
"body": "I originally tried to extend the active record class, but that failed. I think I was doing it wrong. I really like your method, I'll probably do that when I get the time to update my library."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-29T12:03:59.200",
"Id": "666",
"Score": "1",
"body": "No problem, sorry for all the confusion above, hope you get a more stable class together :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-27T14:57:07.827",
"Id": "277",
"ParentId": "12",
"Score": "16"
}
}
] | {
"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>A few functions to let me manage TAGS files more easily. Typically, my projects contain at least one sub-folder. I got sick of manually updating, so I wrote this to help me update a single TAGS file per project (always in the projects' root directory).</p>
<p>Please share your thoughts (aside from "Why are you using Emacs?", you're not likely to change my mind).</p>
<p>One thing I've noticed that could trip me up is that it only tags files of one language (and if I had a project that had both Haskell and JS code, for example, I could tag one or the other). I would particularly appreciate advice on better ways to write find-parent-tags than just building each path from available sub-strings.</p>
<pre><code>(defun create-tag-table ()
"This will recursively tag all files of a given type starting with the current buffers' directory.
It overwrites the old TAGS file, if one exists.
Haskell files assume you've installed `hasktags`."
(interactive)
(let ((file-type (get-taggable-extension))
(cur-dir default-directory)
(tags-file (find-parent-tags default-directory)))
(if (equalp file-type "hs")
(shell-command "hasktags --ignore-close-implementation --etags `find . -type f -name \"*.*hs\"`")
(shell-command (concat "find -name \"*." file-type "\" -print | etags -")))))
(defun find-parent-tags (dir)
"Traverses the directory tree up to /home/[user]/ or / whichever comes first.
Returns either nil or the directory containing the first TAGS file it finds."
(interactive (list default-directory))
(find-parent-tags-rec (build-tag-paths dir)))
(defun find-parent-tags-rec (list-of-filepath)
(cond ((null list-of-filepath) nil)
((file-exists-p (car list-of-filepath)) (car list-of-filepath))
(t (find-parent-tags-rec (cdr list-of-filepath)))))
(defun build-tag-paths (dir-string)
(build-tag-paths-rec (remove-if #'empty-string? (split-string dir-string "/")) (list "/")))
(defun build-tag-paths-rec (steps acc)
(if (null steps)
(mapcar (lambda (p) (concat p "TAGS")) acc)
(build-tag-paths-rec (cdr steps)
(cons (concat (car acc) (car steps) "/") acc))))
(defun get-taggable-extension ()
"Either returns the current file's extension (if it's appropriate) or asks the user to pick one with completion"
(let ((b-name (buffer-file-name (current-buffer)))
(valid-exts (list "lisp" "py" "c" "hs" "rb" "ss" "scm" "js" "erl" "el")))
(string-match "\\.\\(.*?\\)$" b-name)
(let ((current-filetype (match-string 1 b-name)))
(if (member current-filetype valid-exts)
current-filetype
(completing-read "File type: " valid-exts nil 'confirm)))))
(defun empty-string? (s) (equalp s ""))
(provide 'tagariffic)
</code></pre>
| [] | [
{
"body": "<h3>General notes</h3>\n\n<ul>\n<li>Always prefix your functions with the name of your package or project, e.g. <code>tagariffic-create-tag-table</code> and so on. Emacs has no package scoping.</li>\n<li>Whenever possible (i.e. in the absence of mutual recursion), define your functions before using them. It's a lot clearer for the reader. It's also necessary if you ever define macros.</li>\n<li>You're using some functions from the <code>cl</code> package, so you should start with <code>(require 'cl)</code>.</li>\n<li>The usual style for predicates in Lisp is <code>name-p</code>, not <code>name?</code> (that's Scheme).</li>\n<li>Emacs has functions to manipulate <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/File-Names.html#File-Names\">file and directory names</a>. Use them rather than going around concatenating slashes; this way your code will work on exotic platforms such as Windows.</li>\n</ul>\n\n<h3>Finding the tags file</h3>\n\n<p>Emacs 23 has a function <code>locate-dominating-file</code> (in <code>files.el</code>).</p>\n\n<blockquote>\n <p>Look up the directory hierarchy from <code>FILE</code> for a file named <code>NAME</code>.<br>\n Stop at the first parent directory containing a file <code>NAME</code>,\n and return the directory. Return <code>nil</code> if not found.</p>\n</blockquote>\n\n<p>Your <code>(find-parent-tags default-directory)</code> is almost equivalent to <code>(locate-dominating-file (buffer-file-name) \"TAGS\")</code>. If you want to use the current directory rather than the directory of the current buffer's file (they're almost always the same), use <code>(locate-dominating-file (concat (default-directory) \".\") \"TAGS\")</code>. <code>locate-dominating-file</code> stops at your home directory, too.</p>\n\n<p>The code you posted does nothing with the <code>tags-file</code> variable. Did you mean to run the tag generation command in that directory, or failing that in the current directory? If so, this should do it:</p>\n\n<pre><code>(let ((default-directory (if tags-file (file-name-directory tags-file) default-directory)))\n (shell-command …))\n</code></pre>\n\n<h3>From file type to shell commands</h3>\n\n<p>Rather than build in an exception for Haskell, the usual style would be to define an <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/Association-List-Type.html#Association-List-Type\">alist</a> from extensions to commands.</p>\n\n<pre><code>(defvar tagariffic-command-alist\n '((\"hs\" . \"… hasktags …\")\n (t . \"… etags …\")))\n</code></pre>\n\n<p>However, there's a better approach than separate commands for each type; see below.</p>\n\n<h3>The shell commands</h3>\n\n<p>Your <code>hasktags</code> command will choke on file or directory names that contain shell special characters: <code>\\[?*</code> and whitespace. This isn't very common in source trees, but it could happen. Generally speaking, never use command substitution to generate a list of file names. Instead, let <code>find</code> call the command.</p>\n\n<pre><code>find . -type f -name '*.hs' -exec hasktags --ignore-close-implementation --etags {} +\n</code></pre>\n\n<p>A second problem is that if there are too many files, the command you wrote will die of a command line too long error; the one I just showed will run <code>hasktags</code> several times with command lines of a permitted size, causing the tag file to be overwritten. As a workaround, start by creating an empty tags file and tell <code>hasktags</code> to append to the tags file.</p>\n\n<pre><code>: >TAGS\nfind . -type f -name '*.hs' -exec hasktags --ignore-close-implementation -e -a {} +\n</code></pre>\n\n<p>An improvement to the <code>find</code> commands would be to ignore certain directories belonging to version control systems. Especially with svn, this could speed things up.</p>\n\n<pre><code>find . -type d \\( -name .bzr -o -name .git -o -name .hg -o -name .svn -o -name CVS -o -name _darcs \\) -prune -o \\\n -type f …\n</code></pre>\n\n<p>Above I mentioned a different approach to choosing the tag generation command. Your approach assumes that a given project will be in a single language. It's easy enough to cater for mixed-language projects: build a single tags file containing the output generated by <code>etags</code> and <code>hasktags</code>.</p>\n\n<pre><code>: >TAGS\nfind . -type d \\( -name .bzr -o … \\) -prune -o \\\n -type f -name '*.hs' -exec hasktags -e -a {} + -o \\\n -type f \\( -name '*.[CScls]' -o -name '*.el' -o … \\) -exec etags {} +\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-16T22:29:51.700",
"Id": "115253",
"Score": "0",
"body": "FWIW - a detail: I disagree with *define your functions before you use them*. Sometimes that is good practice, sometimes not. Sometimes things are more readable top-down, with the detailed utility functions defined after the high-level ones. IOW, master-detail order. And this is more the case in a declarative (e.g. functional, logic) language. [It is of course the case that sometimes definition order is imposed, as for macros, as you pointed out.]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-25T23:26:27.180",
"Id": "3633",
"ParentId": "45",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "3633",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T00:10:13.883",
"Id": "45",
"Score": "16",
"Tags": [
"elisp"
],
"Title": "Emacs Etags Shortcut Functions"
} | 45 |
<p>This shows a test case for an old caching library that I use for a project. It features simple save/load/delete functions (sadly static calls) but what I want to focus on is the test code written for this class.</p>
<p>In my opinion the unit tests for a class should show how all functions in the class work and what to <em>expect</em> from that class.</p>
<p>Recently we got this great change to show off code, so I'd like to ask you if you can read that test code, understand what the class might do and how you would improve upon it.</p>
<pre><code><?php
class DatenCacheTest extends PHPUnit_Framework_TestCase {
function testNothingFound() {
$this->assertSame(false, DatenCache::load("testNotHereCache"));
}
function testSaveLoadSimple() {
$sDatenSimple = "testStringSaveLoadSimple";
$sDatenSimpleParam = "testStringParam";
$sDatenSimpleParam2 = "testStringParam2";
$sDatenSimpleParam3 = "";
$sDatenSimpleParam4 = 0;
$this->assertSame(true, DatenCache::save("testCacheSimple", false, $sDatenSimple));
$this->assertSame($sDatenSimple, DatenCache::load("testCacheSimple", false));
$this->assertSame(true, DatenCache::save("testCacheLinearParam", "string", $sDatenSimpleParam));
$this->assertSame($sDatenSimpleParam, DatenCache::load("testCacheLinearParam", "string"));
$this->assertSame(true, DatenCache::save("testCacheLinearParam", 5, $sDatenSimpleParam2));
$this->assertSame($sDatenSimpleParam2, DatenCache::load("testCacheLinearParam", 5));
$this->assertSame(true, DatenCache::save("testCacheBoundStringParam", false, $sDatenSimpleParam3));
$this->assertSame($sDatenSimpleParam3, DatenCache::load("testCacheBoundStringParam", false));
$this->assertSame(true, DatenCache::save("testCacheBoundIntParam", false, $sDatenSimpleParam4));
$this->assertSame($sDatenSimpleParam4, DatenCache::load("testCacheBoundIntParam", false));
$oObj = new stdClass();
$oObj->bob = 2;
$this->assertSame(true, DatenCache::save("testCacheBoundObjParam", $oObj, "zwei"));
$this->assertSame("zwei", DatenCache::load("testCacheBoundObjParam", $oObj));
}
function testSaveLoadArray() {
$aDaten = array("da" => "ten", array("ten" => "da"), "Striche" => "' \";s:5:", "h''uh" => "mep", "\\mep\\" => "^^", "Zeilenumbruch" => "\n", "Zeug" => "::}}{:", "'" => '"', '"' => "'");
$this->assertSame(true, DatenCache::save("testCacheArray", false, $aDaten));
$this->assertSame($aDaten, DatenCache::load("testCacheArray", false));
}
function testSaveLoadExpired() {
$this->assertSame(true, DatenCache::save("testCacheExpired", false, "testStringLoadExpired", "-1 seconds"));
$this->assertSame(false, DatenCache::load("testCacheExpired", false));
}
function testSaveLoadObject() {
$oObj = new stdClass();
$oObj->bob = 2;
$this->assertSame(true, DatenCache::save("testCacheBoundIntParam", false, $oObj));
$oNewObj = DatenCache::load("testCacheBoundIntParam", false);
$this->assertEquals($oObj, $oNewObj);
$this->assertSame($oObj->bob, $oNewObj->bob);
}
function testSaveLoadComplexParam() {
$aKonfigEins = array(DatenCache::ANLAGEN_ID() => 1, DatenCache::SESSION_ID() => "id1");
$aKonfigZwei = array(DatenCache::ANLAGEN_ID() => 1, DatenCache::SESSION_ID() => "id2");
$aKonfigDrei = array(DatenCache::ANLAGEN_ID() => 1, DatenCache::SESSION_ID() => "id3");
$aKonfigVier = array(DatenCache::ANLAGEN_ID() => 1);
$aKonfigFuenf = array(DatenCache::SESSION_ID() => "id3");
$aKonfigSechs = array(DatenCache::ANLAGEN_ID() => 1, DatenCache::SESSION_ID() => "id3", DatenCache::PERSON_ID() => 1);
$this->assertSame(true, DatenCache::save("testCacheComplexParam", $aKonfigEins, "v1"));
$this->assertSame("v1", DatenCache::load("testCacheComplexParam", $aKonfigEins));
$this->assertSame(true, DatenCache::save("testCacheComplexParam", $aKonfigZwei, "v2"));
$this->assertSame("v2", DatenCache::load("testCacheComplexParam", $aKonfigZwei));
$this->assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigDrei));
$this->assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigVier));
$this->assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigFuenf));
$this->assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigSechs));
}
function testInvalidate() {
$this->assertSame(true, DatenCache::save("testCacheSimple", false, "testStringInvalidate"));
DatenCache::invalidate("testCacheSimple");
$this->assertSame(false, DatenCache::load("testCacheSimple", false));
}
function testInvalidateWithParams() {
$sTestStringEins = "testStringInvalidateWithParams";
$sTestStringZwei = "testStringInvalidateWithParamsZwei";
$aKonfigEins = array(DatenCache::ANLAGEN_ID() => 1, "Pony" => false);
$aKonfigZwei = array(DatenCache::ANLAGEN_ID() => 1, "Pony" => true);
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigZwei, $sTestStringEins));
DatenCache::invalidate("testCacheInvalidateWithParams", $aKonfigEins);
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins));
$this->assertSame($sTestStringEins, DatenCache::load("testCacheInvalidateWithParams", $aKonfigZwei));
$aKonfigDrei = array(DatenCache::ANLAGEN_ID() => 1, DatenCache::BENUTZER_ID() => 123, "bob" => "please");
$aKonfigVier = array(DatenCache::ANLAGEN_ID() => 2, "Pony" => true, "bob" => "please");
$aPartEins = array(DatenCache::ANLAGEN_ID() => 1);
$aPartZwei = array(DatenCache::BENUTZER_ID() => 123);
$aPartDrei = array("bob" => "please");
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."1"));
DatenCache::invalidate("testCacheInvalidateWithParams", $aPartEins);
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."2"));
DatenCache::invalidate("testCacheInvalidateWithParams", $aPartZwei);
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."3"));
DatenCache::invalidate("testCacheInvalidateWithParams", $aPartDrei);
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigZwei, $sTestStringEins));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringEins));
DatenCache::invalidate("testCacheInvalidateWithParams", array(DatenCache::ANLAGEN_ID() => 1));
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins));
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigZwei));
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins));
$this->assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigVier, $sTestStringEins));
DatenCache::invalidate("testCacheInvalidateWithParams", array(DatenCache::ANLAGEN_ID() => 1));
$this->assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins));
$this->assertSame($sTestStringEins, DatenCache::load("testCacheInvalidateWithParams", $aKonfigVier));
}
function testCleanup() {
$this->assertSame(true, DatenCache::save("testCacheSimple", false, "testString", "-5 seconds"));
$this->assertSame(true, DatenCache::save("testCacheSimpleBleibt", false, "testString", "+30 seconds"));
DatenCache::cleanup();
$this->assertSame("testString", DatenCache::load("testCacheSimpleBleibt", false));
$this->assertSame(false, DatenCache::load("testCacheSimple", false));
// Direkt auf der DB Prüfen ob der Datensatz wiklich gelöscht wurde und nicht nur ausgelaufen ist
$this->assertSame(
array(),
McDb::getConnection(DB_MC_CACHES)->getRow(
"SELECT * FROM mc_caches.T_DATEN_CACHE WHERE PARAMETER = ? AND VALUE = ?", "NAME", "testCacheSimple"
)
);
}
function testCleanupWithParam() {
$aKonfig = array(DatenCache::ANLAGEN_ID() => 1);
$this->assertSame(true, DatenCache::save("testCacheSimple", $aKonfig, "testString", "+120 seconds"));
DatenCache::cleanup();
$this->assertSame("testString", DatenCache::load("testCacheSimple", $aKonfig));
}
function testInvalidateByParam() {
$mValue1 = 1;
$mValue2 = 2;
$aKonfigEins = array(DatenCache::ANLAGEN_ID() => $mValue1);
$aKonfigZwei = array(DatenCache::ANLAGEN_ID() => $mValue2);
$this->assertSame(true, DatenCache::save("testCacheInvalidateByParam", $aKonfigEins, "testString"));
$this->assertSame(true, DatenCache::save("testCacheInvalidateByParam2", $aKonfigZwei, "testString2"));
DatenCache::invalidateByParam(DatenCache::ANLAGEN_ID());
$this->assertSame(false, DatenCache::load("testCacheInvalidateByParam", $aKonfigEins));
$this->assertSame(false, DatenCache::load("testCacheInvalidateByParam2", $aKonfigZwei));
$this->assertSame(true, DatenCache::save("testCacheSimple", $aKonfigEins, "testString"));
$this->assertSame(true, DatenCache::save("testCacheSimple2", $aKonfigZwei, "testString2"));
DatenCache::invalidateByParam(DatenCache::ANLAGEN_ID(), $mValue1);
$this->assertSame(false, DatenCache::load("testCacheSimple", $aKonfigEins));
$this->assertSame("testString2", DatenCache::load("testCacheSimple2", $aKonfigZwei));
}
function testInvalidateByParamLike() {
$mValue1 = "I wan't a Pony";
$mValue2 = "No Pony for you !";
$mValue3 = "xxx";
$this->assertSame(true, DatenCache::save("PonyCache", array("PonyParam" => $mValue1), "test1"));
$this->assertSame(true, DatenCache::save("PonyCache", array("PonyParam" => $mValue2), "test2"));
$this->assertSame(true, DatenCache::save("PonyCache", array("PonyParam" => $mValue3), "test3"));
DatenCache::invalidateByParam("PonyParam", "%Pony%", true);
$this->assertSame(false, DatenCache::load("PonyCache", array("PonyParam" => $mValue1)));
$this->assertSame(false, DatenCache::load("PonyCache", array("PonyParam" => $mValue2)));
$this->assertSame("test3", DatenCache::load("PonyCache", array("PonyParam" => $mValue3)));
}
/**
* @expectedException PHPUnit_Framework_Error
*/
function testInvalidSaveTime() {
$this->assertSame(false, DatenCache::save("testFail", null, "test1", "invalidStrtotime"));
}
function testInvalidSaveTimeReturn() {
$this->assertSame(false, @DatenCache::save("testFail", null, "test1", "invalidStrtotime"));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T19:19:00.860",
"Id": "162",
"Score": "0",
"body": "This looks like the long-code-questions version of Stack Overflow"
}
] | [
{
"body": "<p>I lack the syntax knowledge to say I understand the class. I can say reading it is a bit hard due to long lines and the fact that the dominant patterns are repetitive method/variable names. Test names are descriptive enough </p>\n\n<p>Maybe if you could extract methods like <code>DatenCache::load</code> to <code>Dload</code> and <code>$this->assertSame</code> to <code>aSame</code> it would get less busy. Or make an utility function, since you're asserting equality on booleans (so <code>assertTrue</code> and <code>assertFalse</code> could make it clearer). Where possible, constructing more arrays outside the calls could also help. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T01:29:45.003",
"Id": "54",
"ParentId": "47",
"Score": "3"
}
},
{
"body": "<p>Other than long lines, I'm not seeing something too unreadable. I don't advise shortening function names as doing so makes it less clear what the function is doing. Instead, try splitting the function calls being passed as parameters onto different lines by either splitting the line across multiple lines or storing the returned value as a variable and passing that variable in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-20T02:40:02.943",
"Id": "62",
"ParentId": "47",
"Score": "7"
}
},
{
"body": "<p>You should provide the optional string message as last argument for assertion calls; turn this:</p>\n\n<pre><code>$this->assertSame(true, DatenCache::save(\"testCacheSimple\", false, $sDatenSimple));\n</code></pre>\n\n<p>Into this:</p>\n\n<pre><code>$this->assertSame(\n true,\n DatenCache::save(\"testCacheSimple\", false, $sDatenSimple),\n \"a successful [describe operation] \".\n \"is expected for [describe arguments]\");\n</code></pre>\n\n<p>This form reminds me of Perl instructions do something or die \"message\", and I use the indentation, keeping the message alone, right-aligned, on a separate line when needed, to put it in perspective:</p>\n\n<pre><code>assert( something, \"something expected\");\nassert( something else, \"something else expected\");\nassert( something long\n that spans multiple lines,\n \"something long \".\n \"that spans multiple lines expected\");\n</code></pre>\n\n<p>In this way, all the messages get aligned on the right, and can be read separately.</p>\n\n<p>Also, you should use the most specific assertion available instead of using assertSame() all the time. When comparing with true, using assertTrue() instead would clarify the intent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-22T10:32:13.810",
"Id": "155",
"ParentId": "47",
"Score": "7"
}
},
{
"body": "<p>IMHO, much like when writing a class a single method should do one thing and do that one thing well.</p>\n\n<p>You should be doing less assertions per function in your test class, <strong>preferably 1 assertion per function</strong>.</p>\n\n<p>As a general rule the least lines of code in a test function the better the test.</p>\n\n<p>This way you can document a test of a usage example for each function and assertion pair and in effect you will be creating usage documentation for the class under test.</p>\n\n<p>Edit: I just noticed after another look at your test that you are testing two functions in alot of the tests (load and save). These should be tested individually as one may affect the other and may produce unpredictable results.</p>\n\n<p><strong>Simple = Robust</strong></p>\n\n<p>I obviously don't know the class under test but i suspect you should be writing tests similar to below. Isolating the methods being tested and breaking the tests into smaller units. Hopefully this will help you.</p>\n\n<pre><code><?php\n// Instead of $this->assertSame() use $this->assertTrue() when testing for true.\n// much easier to see what outcome is needed from test.\n\nclass DatenCacheTest extends PHPUnit_Framework_TestCase {\n\nfunction setup(){\n // runs before every test like __construct() in a class.\n $this->str = 'testString';\n}\n\nfunction tearDown(){\n // runs after every test like __destruct() in a class.\n}\n\nfunction testSaveSimple(){\n $this->assertTrue( DatenCache::save(\"testCacheSimple\", false, $this->str) );\n}\n\nfunction testSaveLinearParam(){\n $this->assertTrue( DatenCache::save(\"testCacheLinearParam\", \"string\", $this->str) );\n}\n\nfunction testSaveBoundObjParam(){\n $oObj = new stdClass();\n $oObj->bob = 2;\n $this->assertTrue( DatenCache::save(\"testCacheBoundObjParam\", $oObj, \"zwei\") );\n}\n// complete tests for all aspects of DatenCache::save()\n\n// Test DatenCache::load() because DatenCache::save() has been tested.\nfunction testLoadSimple(){\n DatenCache::save(\"testCacheSimple\", false, $this->str);\n $this->assertSame( $this->str, DatenCache::load($this->str, false) );\n}\n\nfunction testLoadNoCache(){\n $this->assertFalse( DatenCache::load(\"testNoCache\") );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T03:26:02.510",
"Id": "13502",
"Score": "0",
"body": "I agree with this. Also you can use @covers in the docblocks to ensure that your test coverage is not over-estimated and that each test covers only the method it is trying to test."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:35:14.483",
"Id": "4586",
"ParentId": "47",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "62",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-20T00:42:35.173",
"Id": "47",
"Score": "12",
"Tags": [
"php",
"unit-testing",
"cache"
],
"Title": "Test case for a caching library"
} | 47 |
<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 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 36