body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Here's my first significant Haskell program - it presents a count of each word seen on stdin. Any comments are welcome.</p> <pre><code>import Data.Map emptyMap = empty :: Map String Integer countWord m s = alter (\x -&gt; case x of Nothing -&gt; Just 1 Just n -&gt; Just (n+1)) s m mapPairs m = concat [ k ++ ": " ++ (show v) ++ "\n" | (k,v) &lt;- toList m ] mapTotal = sum . elems mapOutput m = (mapPairs m) ++ "Total words: " ++ (show (mapTotal m)) ++ "\n" wc = interact $ mapOutput . (foldl countWord emptyMap) . words </code></pre> <p>Some of the questions I have are:</p> <ul> <li><p>Am I using Map efficiently here? (I realize there are other solutions which do not use a Map - the main point of this exercise was to learn how to use Data.Map.) </p></li> <li><p>How can I make sure that emptyMap, countWord and mapTotal all use the same integral type (<code>Int</code> vs. <code>Integer</code>)? For instance, the type of mapTotal is <code>Map a Integer -&gt; Integer</code>, and so I'll get a type error if I change the definition of emptyMap to <code>empty :: Map String Int</code>. Ideally I'd like to make the choice between <code>Int</code> and <code>Integer</code> in one place for all three definitions.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T04:26:42.500", "Id": "13944", "Score": "2", "body": "You might like `fromListWith`; you can replace `foldl countWord emptyMap` with something like `fromListWith (+) . flip zip (repeat 1)` and skip defining `countWord` at all." } ]
[ { "body": "<p>Your usage of <code>Data.Map</code> is sound. I see nothing that could be improved as long as you stay with <code>Data.Map</code>.</p>\n\n<p>If you give all of the functions explicit type declarations, so that the Monomorphism Restriction doesn't apply, you can use generic integral types:</p>\n\n<pre><code>mapTotal :: Integral i =&gt; Map a i -&gt; i\n</code></pre>\n\n<p>Some quick style-related things you could change:</p>\n\n<p><strong>First:</strong></p>\n\n<pre><code>(\\x -&gt; case x of\n Nothing -&gt; Just 1\n Just n -&gt; Just (n+1))\n</code></pre>\n\n<p>... is the same as</p>\n\n<pre><code>Just . maybe 1 (+1)\n</code></pre>\n\n<p><strong>Second:</strong></p>\n\n<p>You don't need parens around many of your function calls; if you have something like <code>a +.- (foo bar baz) ¤:* b</code>, it means the same thing as <code>a +.- foo bar baz ¤:* b</code> because every operator has lower precedence than function application.</p>\n\n<p><strong>Third:</strong></p>\n\n<p>You use very long indentations. A tip is to insert newlines after <code>=</code> and before control structures like <code>case</code> to make the code more compact. I find <a href=\"http://snapframework.com/docs/style-guide\">this style</a> to be quite good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T04:05:34.323", "Id": "13945", "Score": "0", "body": "I should probably have waited until this question was migrated to CodeReview; thought it already had been..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T04:41:13.737", "Id": "13946", "Score": "0", "body": "The first snippet is actually `maybe (Just 1) (Just . (+1))`, not `maybe 1 (+1)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-20T03:11:53.390", "Id": "128662", "Score": "1", "body": "[**`Data.Map.Strict`**](http://hackage.haskell.org/package/containers-0.5.0.0/docs/Data-Map-Strict.html) may be more efficient since he is only counting." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T04:04:35.273", "Id": "8905", "ParentId": "8904", "Score": "12" } }, { "body": "<p>It's good code, except for the strictness problem : you're accumulating big thunks of ((1+1)+1)+1.. in your Map. If you're handling long texts with repeated words, you could even end up having a stack overflow when you're finally computing them (in your \"mapPair\").</p>\n\n<p>In your solution, you'll have to do :</p>\n\n<pre><code>Just n -&gt; Just $! (n+1)\n</code></pre>\n\n<p>so that the result is evaluated before Just is applied.</p>\n\n<p>Other solutions :</p>\n\n<pre><code>countWord w m = alter ((Just $!) . maybe 1 (+1)) w m\n</code></pre>\n\n<p>or</p>\n\n<pre><code>fromListWith' :: (v-&gt;v-&gt;v) -&gt; [(k,v)] -&gt; Map k v\nfromListWith' f = foldl' ins empty \n where ins m (k,v) = insertWith' f k v m\n\ncountWords :: String -&gt; Map String Integer\ncountWords = fromListWith' (+) . flip zip (repeat 1) . words\n</code></pre>\n\n<p>Any of these solutions will work like your original one but should be a bit faster and less memory hungry, though it is possible that GHC was already optimising that (if you were using -O or -O2).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T13:11:19.540", "Id": "8920", "ParentId": "8904", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T03:34:39.100", "Id": "8904", "Score": "7", "Tags": [ "haskell" ], "Title": "My Haskell word count program" }
8904
<p>This little script makes list items selectable and draggable. I'm pretty new to programming in general, and even more so to Javascript. Most of my background is in PHP and some C++. On the large, I don't think this is the proper way to be writing code in JavaScript. I know global variables are bad, but I'm not used to dealing with event handling, I don't know how to maintain constants like that throughout various event calls that aren't otherwise attached to each other. I'm really not sure if I'm doing any of this right.</p> <p>A more specific question - This script works as is, but if i change <code>handleDragStart()</code>'s variable <code>dragSrc = this;</code> into <code>var dragSrc = this;</code> as it should be, it breaks. When the <code>handleDrop()</code> event fires, it returns <code>dragSrc is not defined</code>. If anything, I would expect this behavior with the way it is written now, not after adding <code>var</code>. I'm a little lost.</p> <pre><code>var SELECTED_CLASS_CONST = 'selected'; var DROP_CLASS_CONST = 'drophover'; function handleDragStart(e) { dragSrc = this; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/html', this.innerHTML); } function handleDragEnter(e) { this.addClass(DROP_CLASS_CONST); } function handleDragLeave(e) { this.removeClass(DROP_CLASS_CONST); } function handleDragEnd(e) { [].forEach.call(draggables, function(drag) { drag.removeClass(DROP_CLASS_CONST); }); } function handleDragOver(e) { if (e.preventDefault) { e.preventDefault(); } e.dataTransfer.dropEffet = 'move'; return false; } function handleDrop(e) { if (e.stopPropagation) { e.stopPropagation(); } if ( dragSrc != this ) { dragSrc.innerHTML = this.innerHTML; this.innerHTML = e.dataTransfer.getData('text/html'); this.removeClass(DROP_CLASS_CONST); if (dragSrc.hasClass(SELECTED_CLASS_CONST) &amp;&amp; this.hasClass(SELECTED_CLASS_CONST)) { return; } else { swapClass(dragSrc, this, SELECTED_CLASS_CONST); } } return false; } function toggleClass(e) { if (e.preventDefault) { e.preventDefault(); } this.toggleClass(SELECTED_CLASS_CONST); } function swapClass(elemA, elemB, c) { if (elemA.hasClass(c) || elemB.hasClass(c)) { elemA.toggleClass(c); elemB.toggleClass(c); } return; } Element.prototype.toggleClass = function(name) { if (this.hasClass(name)) { this.removeClass(name); } else { this.addClass(name); } }; Element.prototype.hasClass = function(name) { return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className); }; Element.prototype.addClass = function(name) { if(!this.hasClass(name)) { this.className = this.className ? [this.className, name].join(' '): name } }; Element.prototype.removeClass = function(name) { if(this.hasClass(name)) { var curClass = this.className; this.className = curClass.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), ""); } }; var draggables = document.getElementsByClassName('drag'); [].forEach.call(draggables, function(drag) { drag.addEventListener('dragstart', handleDragStart, false); drag.addEventListener('dragenter', handleDragEnter, false); drag.addEventListener('dragover', handleDragOver, false); drag.addEventListener('dragleave', handleDragLeave, false); drag.addEventListener('dragend', handleDragEnd, false); drag.addEventListener('drop', handleDrop, false); drag.addEventListener('click', toggleClass, true); }); </code></pre> <p>I know I could just use jQuery or the myriad of other js libraries, but this is just a project to really learn Javascript thoroughly before moving to a library. At least how to properly structure my code (something I'm still learning how to do in PHP as well...) form closures when necessary, and how to recognize when that is. </p> <p>Edit: <a href="http://jsfiddle.net/JHtqY/" rel="nofollow">JSFiddle</a> (warning: I don't think <code>preventDefault()</code> works in the jsfiddle window, so it will probably redirect you, I didn't test with other browsers.) and <a href="http://html5demos.com/drag" rel="nofollow">another example</a> with source. The second example has a similar code structure, but it's obviously a quick and dirty example; I want to know if there is a better way to do it. It mostly being event binding and maintaining a "<code>const</code>" between various unassociated event function calls.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T13:47:02.937", "Id": "14004", "Score": "0", "body": "On the `var`: a variable declared with var is in the local scope, one without is in the global scope. So when you assign to it in one function, it is available in the other as the variable is in the global scope; while when you use `var dragSrc = this;` then dragSrc is only available inside that function (... so while outside, you will access the global-scope variable with the same name, which is undefined)." } ]
[ { "body": "<p>Edit: I missed that you were talking about the HTML5 drag and drop stuff, but I think this still kind of applies, so I'll leave it here for now. The idea is to \"namespace\" stuff into a singleton object.</p>\n\n<hr>\n\n<p>The usual approach is to use a singleton object and attach all those functions and variables to it as properties.</p>\n\n<p>You might try something like this, for example.</p>\n\n<pre><code>// mouse input stuff\n\nvar mouseInput = {};\n\n// grab (start dragging) a node\nmouseInput.grab = function(node, x, y) {\n this.activeNode = node;\n node.style.position = 'relative';\n node.style.left = '0px';\n node.style.top = '0px';\n node.style.zIndex = '10';\n this.lastX = x;\n this.lastY = y;\n this.lastLeft = 0;\n this.lastTop = 0;\n};\n\n// drag a node\nmouseInput.drag = function(x, y) {\n if (!this.activeNode) return;\n this.lastLeft -= (this.lastX - x);\n this.lastTop -= (this.lastY - y);\n this.activeNode.style.left = this.lastLeft + 'px';\n this.activeNode.style.top = this.lastTop + 'px';\n this.lastX = x;\n this.lastY = y;\n};\n\n// drop (stop dragging) a node\nmouseInput.drop = function(x, y) {\n if (!this.activeNode) return;\n this.activeNode.style.zIndex = null;\n this.activeNode.style.left = null;\n this.activeNode.style.top = null;\n this.activeNode.style.position = null;\n this.activeNode = null;\n};\n</code></pre>\n\n<p>If you prefer, every <code>this</code> can be replaced with <code>mouseInput</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T09:12:28.887", "Id": "13959", "Score": "0", "body": "I think you're misunderstanding a little. HTML5 implements drag and drop events that you can attach functions to with event handlers. No need to keep track of x,y and other things like that. I added a link and JSfiddle to my question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T09:23:05.190", "Id": "13960", "Score": "0", "body": "Ah, my bad. But still, doesn't the same concept apply? i.e. instead of making `dragSrc` a global var, attach it to some kind of namespace object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T09:32:58.830", "Id": "13961", "Score": "0", "body": "`dragSrc` is not the global I was talking about. I meant `SELECTD_CLASS_CONST` and `DROP_CLASS_CONST`. Isn't `dragSrc` in the scope of `handleDragStart()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T10:38:16.890", "Id": "13964", "Score": "0", "body": "I did some digging on the singleton thing and now I get what you mean - having one singleton global variable, and binding all the other ones to it as properties. That definitely answers one question, thanks :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T08:25:36.997", "Id": "8914", "ParentId": "8906", "Score": "2" } } ]
{ "AcceptedAnswerId": "8914", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T07:53:35.333", "Id": "8906", "Score": "4", "Tags": [ "javascript", "html5" ], "Title": "Drag and Drop file handler" }
8906
<p>blah - not even sure if that is the correct way to say it. Basically I have this</p> <pre><code>public class XmlAccess { public XmlAccess() { } public string ApplicationPath = ""; public string DBServer = ConfigurationManager.AppSettings["DB2_Server"]; public string DBName = ConfigurationManager.AppSettings["DB2_Database"]; public string DBLogIn = ConfigurationManager.AppSettings["DB2_User"]; } </code></pre> <p>I am trying to create some seams for some unit tests and have pulled out a lot of interfaces which is great but I have this thing (code above) trying to initialize all these fields (that's just a sample - it goes on and on...) when it fires up. Anyone have any suggestions as to how to refactor this? I have never had to do this sort of major refactor of "old code" but I am sure others have. The way it is handling those variables is silly and untestable but I am not sure what to do about it and it's holding me up. </p>
[]
[ { "body": "<p>Does any code set those fields?</p>\n\n<p>Turn them into properties, then extract the interface that includes the properties. I recommend against letting any code set them, if at all possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T04:04:43.970", "Id": "13948", "Score": "0", "body": "Yeah - I ended up making them all Properties and creating an interface." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:23:11.000", "Id": "8908", "ParentId": "8907", "Score": "6" } }, { "body": "<p>I believe we call \"old code\" \"legacy code\".</p>\n\n<p>But, since those variables are public you should be able to change them to something more appropriate before you run your tests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:41:00.800", "Id": "13949", "Score": "0", "body": "Right - \"old code\" was substitute for \"messy garbage that's driving me insane\", I felt like the term legacy code was giving it too much credit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:24:28.677", "Id": "8909", "ParentId": "8907", "Score": "0" } }, { "body": "<p>Try decoupling <code>XmlAccess</code> from the configuration system:</p>\n\n<pre><code>public class XmlAccess\n{\n public XmlAccess(string applicationPath, string dbServer, string dbName, string dbLogIn)\n {\n ApplicationPath = applicationPath;\n DBServer = dbServer;\n DBName = dbName;\n DBLogIn = dbLogIn\n }\n\n public string ApplicationPath;\n public string DBServer;\n public string DBName;\n public string DBLogIn;\n}\n</code></pre>\n\n<p>Then, when you need an instance, access the configuration file:</p>\n\n<pre><code>new XmlAccess(\n \"\",\n ConfigurationManager.AppSettings[\"DB2_Server\"],\n ConfigurationManager.AppSettings[\"DB2_Database\"],\n ConfigurationManager.AppSettings[\"DB2_User\"]);\n</code></pre>\n\n<p>In your unit tests, you can pass whatever values makes sense for the test and skip the configuration system entirely:</p>\n\n<pre><code>new XmlAccess(\"\", \"TestServer\", \"TestName\", \"TestLogIn\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:43:05.743", "Id": "13950", "Score": "0", "body": "The only problem there is that there are like 40 of these properties, I just read Uncle Bob, \"The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic).\" so I don't want to go that route." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:56:04.910", "Id": "13951", "Score": "0", "body": "@Kenn: That probably indicates `XmlAccess` has too many responsibilities. Have you considered refactoring it so it has fewer dependencies?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T04:15:45.303", "Id": "13952", "Score": "0", "body": "Instantiating the class w/o arguments and setting the properties that you need changed after the fact would PROBABLY work a bit better... But I think I already suggested that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:31:19.060", "Id": "8910", "ParentId": "8907", "Score": "1" } }, { "body": "<p>I would create a new class called something like DBServer to replace those properties you listed. </p>\n\n<pre><code>public class DBServer{\n\n public string Host {get;set;}\n public string Name {get;set;}\n public string Login {get;set;}\n}\n</code></pre>\n\n<p>But I would need to look at the rest of the properties to know how many other classes were needed or were appropriate. I'm reminded of <a href=\"http://www.codinghorror.com/blog/2006/05/code-smells.html\" rel=\"nofollow\">this article by Jeff Atwood</a> about code smells. </p>\n\n<blockquote>\n <p>Large classes, like long methods, are difficult to read, understand,\n and troubleshoot. Does the class contain too many responsibilities?\n Can the large class be restructured or broken into smaller classes?</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T04:07:56.507", "Id": "8911", "ParentId": "8907", "Score": "0" } } ]
{ "AcceptedAnswerId": "8908", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T03:15:33.963", "Id": "8907", "Score": "4", "Tags": [ "c#" ], "Title": "spaghetti code for lunch: refactoring a bunch of fields that always get initialized" }
8907
<p>I have the following block of code which adds pins including descriptions and links onto a Google map. How can I refactor it so that I can add pins easier and without so much redundant code?</p> <pre><code>var map; function initializeMap() { var myOptions = { zoom: 9, center: new google.maps.LatLng(42.2340464046899, -71.0956621170044), mapTypeId: google.maps.MapTypeId.TERRAIN, scrollwheel: false }; map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); var marker1 = new google.maps.Marker({ position: new google.maps.LatLng(42.2340464046899, -71.0956621170044), map: map, title: "Pin 1", url: "#tabs-pin1" }); google.maps.event.addListener(marker1, 'click', function() { $("#tabs").tabs('select', marker1.url); }); var marker2 = new google.maps.Marker({ position: new google.maps.LatLng(41.9584457, -70.6672621), map: map, title: "Pin 2", url: "#tabs-pin2" }); google.maps.event.addListener(marker2, 'click', function() { $("#tabs").tabs('select', marker2.url); </code></pre> <p></p> <pre><code>var marker9 = new google.maps.Marker({ position: new google.maps.LatLng(42.445921, -71.2690294), map: map, title: "Pin 9", url: "#tabs-pin9" }); google.maps.event.addListener(marker9, 'click', function() { $("#tabs").tabs('select', marker9.url); } google.maps.event.addDomListener(window, 'load', initializeMap); </code></pre>
[]
[ { "body": "<p>The simplest solution is extract one function that will form the marker from the parameters and them call it as many times as markers count is:</p>\n\n<pre><code>var markers = []; // probably you don't need this array\nfunction CreateMarker(lat, lng, markerTitle, markerUrl)\n{\nvar marker = new google.maps.Marker({\n position: new google.maps.LatLng(lat, lng),\n map: map,\n title: markerTitle,\n url: markerUrl\n});\ngoogle.maps.event.addListener(marker, 'click', function() {\n $(\"#tabs\").tabs('select', marker.url)\n});\n\nmarkers.push(marker); // you can omit this step if you are not going to work with markers after\n}\n\nfunction initializeMap() {\nvar myOptions = {\n zoom: 9,\n center: new google.maps.LatLng(42.2340464046899, -71.0956621170044),\n mapTypeId: google.maps.MapTypeId.TERRAIN,\n scrollwheel: false\n};\n\nCreateMarker(42.2340464046899, -71.0956621170044, \"Pin 1\", \"#tabs-pin1\");\n// repeat this call for every marker\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T00:46:49.880", "Id": "13955", "Score": "0", "body": "I think you missed a ); after the second block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T00:49:39.630", "Id": "13956", "Score": "0", "body": "Oh, yeah. Sorry, updated the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T00:27:59.940", "Id": "8913", "ParentId": "8912", "Score": "3" } } ]
{ "AcceptedAnswerId": "8913", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T00:18:24.230", "Id": "8912", "Score": "2", "Tags": [ "javascript", "jquery", "google-maps" ], "Title": "Adding pins onto a Google map" }
8912
<p>I'm new to Fortran, and this is pretty much my first escapade. Below is a function that I wrote which relies on calls to LAPACK. The function is sat in a module with some other functions and works perfectly, but seeing as this is really the workhorse of the program I'm building I want to squeeze it hard for performance. How does it look? Am I doing anything stupid, or would another call to BLAS or LAPACK somewhere improve the performance?</p> <p>The function takes a Hermitian matrix <code>H</code>, and returns the matrix exponential of the <em>skew</em>-Hermitian matrix <code>-iHt</code> where <code>i</code> is the imaginary number and <code>t</code> is a real number. (This is the solution to the Schrodinger equation for a time independent Hamiltonian.) <code>s</code>, the length of one side of the Hamiltonian, is included for automatic array initialisation rather than using allocations. Typically it'll be less than 10.</p> <pre class="lang-none prettyprint-override"><code>function time_indep_schrodinger(s,H,t) ! s : The length of one side of H. ! H : The Hamiltonian. ! t : The time t. ! ! The LAPACK subroutine zheev requires a tridiagonal ! subcopy of H. This array is then transformed into ! a matrix of eigenvectors. This also yields the ! eigenvalues as a 1D array, which are then ! exponentiated before using the matrices of ! eigenvectors to produce the evolution operator. ! ! Finds the eigenvalues of Ht, then uses U exp(-i*eigs) U^H. integer, intent(in) :: s complex*16, intent(in) :: H(s,s) real*8, intent(in) :: t complex*16 :: B(s,s), eigv(s,s), time_indep_schrodinger(s,s), work(2*s-1) real*8 :: rwork(3*s-2), eigs(s) integer :: info, n, m ! Hermitian matrix to diagonalise. forall (n=1:s, m=1:s, m&gt;=n) eigv(n,m) = H(n,m)*t ! Get eigenvectors and eigenvalues. call zheev('V','U',s,eigv,s,eigs,work,2*s-1,rwork,info) ! Scale columns of copied matrix be exponentiated eigenvalues (with -i). do n=1,s B(:,n) = eigv(:,n)*exp((0,-1)*eigs(n)) end do ! Finally multiply scaled eigenvectors with conjugate of eigv. time_indep_schrodinger = matmul(B,conjg(transpose(eigv))) end function </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T12:53:11.480", "Id": "13966", "Score": "0", "body": "Is there a directive to instruct the syntax highlighter on which language to highlight for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T04:43:08.923", "Id": "13994", "Score": "0", "body": "Turns out that there is, but fortran is not supported. Turned off syntax highlighting for the code above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T22:00:32.557", "Id": "14417", "Score": "0", "body": "Even though it's the wrong place, you might try posting in StackOverflow. It might get more visibility by [fortran followers](http://stackoverflow.com/tags/fortran/topusers) and if you're lucky, someone will respond w/ some advice before it gets moved here by mods :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T00:11:04.510", "Id": "14420", "Score": "0", "body": "@seand: I tried this question formatted in a different way there a while back. No attention at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T16:46:02.803", "Id": "14456", "Score": "0", "body": "I saw there are LAPACK implementations for a number of languages. Maybe if you could provide an implementation of your code in a more mainstream language you'd get an answer... Though I must admit I haven't got a clue what a \"skew Hermitian matrix\" is :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T16:58:52.010", "Id": "14458", "Score": "0", "body": "@MrHappy: Seriously? We can help you improve your code when you write it in another language? This seems contrary to the point of code review... You do realise that LAPACK is written in fortran for a reason, right? ;)\n\nAlternative performance languages such as C don't handle matrices nicely without using GSL or another library, and the code gets really unreadable really quickly even with one. The above would take more lines in C, be less readable, and would receive about as much attention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T17:00:58.377", "Id": "14460", "Score": "0", "body": "@MrHappy: Anyway, I put up another, totally unrelated question written in PHP5 about accessing an SQLite database. That's got to be pretty \"mainstream\" and has received even less attention than this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T18:02:27.100", "Id": "14463", "Score": "0", "body": "@MarkS.Everitt: I thought you might want to target a wider audience. Anyway I guess you really want fortran specific optimizations and you're sure your algorithm can't be optimized. Good luck!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T18:23:50.293", "Id": "14466", "Score": "0", "body": "@MrHappy: I'm actually certain that there are optimisations to be had. Some quite obvious ones in hindsight too. However, I can't get the bounty back and answering now lowers the odds on *anyone* getting it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T00:02:41.550", "Id": "14494", "Score": "0", "body": "@MarkS.Everitt: Though I would love to steel your bounty with no valid input. Can you not answer you own question and win your own bounty back?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T01:14:01.170", "Id": "14503", "Score": "0", "body": "@LokiAstari: No, I looked into it. Under no circumstances can I get the bounty back, even if it goes to nobody else or I answer my own question." } ]
[ { "body": "<p>Your code looks good. When <code>s</code> is small, there should be no need to use BLAS instead of <code>matmul()</code>. I like you exploit the shorthand array notation and the forall construct.</p>\n\n<p>Debatable is your use of explicit shaped arrays. They could be very slightly faster, because they are contiguous, but in many cases the compiler will have to copy the arrays when calling your routines and the overall code will be slower. The preferred way in modern code are assumed shape arrays, e.g.</p>\n\n<pre><code> complex(complex_kind), intent(in) :: H(:,:)\n complex(complex_kind) :: B(1:ubound(H,1),1:ubound(H,1))\n</code></pre>\n\n<p>but there may be reasons to use your way and it may be shorter.</p>\n\n<p>Generally avoid using star notation <code>real*4 *8 *16</code> for sizes of your variables. It is non-standard and obsolete. Use <code>real(some_kind_constant)</code>.</p>\n\n<p>You can use <code>selected_real_kind()</code> and <code>selected_int_kind()</code> (now preferred), to get the constants.</p>\n\n<p>Or if you don't mind Fortran 2008 features and need to know the size in bits you can use kind constants from the <code>iso_fortran_env</code> module, like <code>integer(int32)</code>, <code>real(real64)</code> and so on. </p>\n\n<p>Another possibility from Fortran 2003 is to use kind constants from the <code>iso_c_binding</code> module, like <code>integer(c_int)</code> if you need interoperability with C code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T09:08:06.907", "Id": "15296", "ParentId": "8917", "Score": "6" } }, { "body": "<p>The solution is OK, if you know that you have to perform a time propagation of exactly <span class=\"math-container\">\\$t\\$</span> with that same Hamiltonian and you have to do so countless times.</p>\n<p>As someone else has suggested, ditch all the matmul and conjg and use only BLAS calls.</p>\n<p>If you apply the propagator to a small number of vectors, however, computing the full propagator is not efficient, due to the matrix-matrix multiplication it entails. Instead, you should evaluate its action on the wavefunction you are propagating by means of three matrix-vector multiplications:\n<span class=\"math-container\">$$e^{-i\\mathbf{H}dt}\\mathbf{c} = \\mathbf{U} e^{-i \\mathbf{E}dt}\\mathbf{U}^\\dagger \\mathbf{c}$$</span>\nthat is\n<span class=\"math-container\">$$\\mathbf{c}_1 = \\mathbf{U}^\\dagger \\mathbf{c},\\qquad \\mathbf{c}_2 = e^{-i \\mathbf{E}dt} \\mathbf{c}_1,\\qquad \\mathbf{c} = \\mathbf{U} \\mathbf{c}_2$$</span></p>\n<p>If you need to propagate multiple different times, of course, diagonalizing the Hamiltonian for every time is definitely not a good idea. Instead, you should do the diagonalization only once, and follow the triple-multiplication procedure above, whose computational cost scales as <span class=\"math-container\">\\$N^2\\$</span> rather than <span class=\"math-container\">\\$N^3\\$</span>.</p>\n<p>If your hamiltonian were to ever become time-dependent, <span class=\"math-container\">\\$\\mathbf{H}=\\mathbf{H}(t)\\$</span>, you must break the propagation in steps\n<span class=\"math-container\">$$\\mathbf{c}(t+dt) = \\mathbf{U}(t+dt,t)\\mathbf{c}(t),$$</span>\nwhere <span class=\"math-container\">\\$\\hat{U}(t+dt,t)\\$</span> is the time-ordered exponential propagator,</p>\n<p><span class=\"math-container\">$$\\mathbf{U}(t+dt,t)=\\hat{T}e^{-i\\int d\\tau\\mathbf{H}(\\tau)}$$</span>.</p>\n<p>An excellent unitary second-order propagator is the mid-point exponential\n<span class=\"math-container\">$$ c(t+dt) = e^{-i \\mathbf{H}(t+dt/2) dt} c(t).$$</span>\nTo evaluate this step, there are many ways that are much better than a brutal direct diagonalization at each time step. First, if you can afford the diagonalization of the full Hamiltonian and if the Hamiltonian has the form\n<span class=\"math-container\">$$\\mathbf{H}(t) = \\mathbf{H}_0 + F(t) \\mathbf{H}_I$$</span>\nwhere both <span class=\"math-container\">\\$\\mathbf{H}_0\\$</span> and <span class=\"math-container\">\\$\\mathbf{H}_I\\$</span> are time-independent Hermitean operators and <span class=\"math-container\">\\$F(t)\\$</span> is a real function, then the best approach is to split symmetrically the propagator:\n<span class=\"math-container\">$$e^{-i \\mathbf{H}(t+dt/2) dt} = e^{-i \\mathbf{H}_0 dt/2}e^{-i \\mathbf{H}_I F(t+dt/2) dt}e^{-i \\mathbf{H}_0 dt/2} + o(dt^3),$$</span>\nwhere <span class=\"math-container\">\\$ o(dt^3)\\$</span> is the difference between the two approximations to the time-step propagator. The mid-point propagator was already accurate only to second order anyway, so you are not losing any accuracy. With this arrangement, you need to perform the diagonalization only <em>once</em>, at the very beginning of the program, separately for <span class=\"math-container\">\\$\\mathbf{H}_0\\$</span> and <span class=\"math-container\">\\$\\mathbf{H}_I\\$</span>,\n<span class=\"math-container\">$$\\mathbf{H}_0 = \\mathbf{U}_0 \\mathbf{E}^{(0)} \\mathbf{U}_0^\\dagger,\\qquad\\mathbf{H}_I = \\mathbf{U}_I \\boldsymbol{\\Delta} \\mathbf{U}_I^\\dagger,$$</span>\nwhere <span class=\"math-container\">\\$\\mathbf{E}^{(0)}_{ij}=E^{(0)}_i\\delta_{ij}\\$</span>, <span class=\"math-container\">\\$\\boldsymbol{\\Delta}_{ij}=\\Delta_i\\delta_{ij}\\$</span> are diagonal matrices.\nIn this way, your propagator becomes\n<span class=\"math-container\">$$U(t+dt,t) = \\mathbf{U}_0 e^{-i \\mathbf{E}^{(0)} dt/2}\\mathbf{U}_0^\\dagger\\mathbf{U}_I e^{-i \\boldsymbol{\\Delta}_I F(t+dt/2) dt}\\mathbf{U}_I^\\dagger\\mathbf{U}_0 e^{-i \\mathbf{H}_0 dt/2}\\mathbf{U}_0^\\dagger + o(dt^3),$$</span>\nYou can pre-compute the matrix <span class=\"math-container\">\\$\\mathbf{O}=\\mathbf{U}_0^\\dagger\\mathbf{U}_I\\$</span>, of course, in which case\n<span class=\"math-container\">$$U(t+dt,t) = \\mathbf{U}_0 e^{-i \\mathbf{E}_0 dt/2}\\mathbf{O} e^{-i \\mathbf{E}_I F(t+dt/2) dt}\\mathbf{O}^\\dagger e^{-i \\mathbf{H}_0 dt/2}\\mathbf{U}_0^\\dagger + o(dt^3).$$</span></p>\n<p>If your time step is constant, you can neglect the first half free propagation, and merge the second with the first of the following step, thus obtaining\n<span class=\"math-container\">$$U(t+dt,t) \\simeq \\mathbf{U}_0 e^{-i \\mathbf{E}_0 dt}\\mathbf{O} e^{-i \\mathbf{E}_I F(t+dt/2) dt}\\mathbf{U}_I^\\dagger.$$</span>\nIn this way, you have replaced a diagonalization (order <span class=\"math-container\">\\$N^3\\$</span>) with three consecutive matrix-vector multiplications (order <span class=\"math-container\">\\$N^2\\$</span>).\nIf applicable to your case, therefore, this change will result in a wild speed up.</p>\n<p>If either <span class=\"math-container\">\\$H_0\\$</span> or <span class=\"math-container\">\\$H_I\\$</span> are too large to be diagonalized (they are not equivalent, since <span class=\"math-container\">\\$H_0\\$</span> is typically block diagonal and hence it is sufficient to diagonalize its diagonal blocks), then you can still use the symmetric splitting as a way to precondition the matrix, and use an iterative method (look up Krylov spaces) to determine the action of the operator on your target function, rather than the opearator over the whole Hilbert space, which is almost always an overkill.</p>\n<p>PS: For folks not familiar with the simple syntax of modern Fortran, I suggest <a href=\"https://fortran-lang.org/learn/quickstart\" rel=\"nofollow noreferrer\">quick modern Fortran tutorial</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-15T03:20:20.660", "Id": "254726", "ParentId": "8917", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T10:14:18.947", "Id": "8917", "Score": "5", "Tags": [ "beginner", "mathematics", "matrix", "fortran" ], "Title": "High performance exponential of a skew Hermitian matrix in Fortran 95" }
8917
<p>I have implemented <a href="http://en.wikipedia.org/wiki/Zeller%27s_congruence" rel="nofollow">Zeller's algorithm</a> in Python to calculate the day of the week for some given date. I would like to get some feedback on how I can make the code shorter and more elegant: </p> <pre><code>def input_value(input_name, prompt, min_num, max_num): while True: data = raw_input(prompt) if data: try: input_name = int(data) except ValueError: print 'Invalid input...' else: if input_name &gt;= min_num and input_name &lt;= max_num: return input_name break input_name = 'Please try again: ' else: print 'Goodbye!' break month = 0 day = 0 year = 0 century = 0 month = input_value(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ", 1, 12) day = input_value(day, "Please enter the day (from 1-31): ", 1, 31) year = input_value(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ", 0, 99) century = input_value(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ", 0, 99) A = month B = day C = year D = century W = (13*A - 1) / 5 X = C / 4 Y = D / 4 Z = W + X + Y + B + C - 2*D R = Z % 7 birthday = "You were born on " + str(B) + "/" + str(A+2) + "/" + str(D) + str(C) + " which was a " if R == 0: print birthday + 'Sunday' elif R == 1: print birthday + 'Monday' elif R == 2: print birthday + 'Tuesday' elif R == 3: print birthday + 'Wednesday' elif R == 4: print birthday + 'Thursday' elif R == 5: print birthday + 'Friday' elif R == 6: print birthday + 'Saturday' </code></pre> <p>Thanks in advance for taking the time to look at this. </p>
[]
[ { "body": "<pre><code>def input_value(input_name, prompt, min_num, max_num):\n</code></pre>\n\n<p><code>input_name</code> is always a number - why are you calling it a 'name'? Also, there's no need to take it as an argument, since you never use its initial value in your function.</p>\n\n<pre><code> while True:\n data = raw_input(prompt)\n if data:\n try:\n input_name = int(data)\n except ValueError:\n print 'Invalid input...'\n</code></pre>\n\n<p>Consider putting a <code>continue</code> here, for clarity. It isn't necessary, though.</p>\n\n<pre><code> else:\n if input_name &gt;= min_num and input_name &lt;= max_num:\n</code></pre>\n\n<p>Python understands <code>if min_num &lt;= input_name &lt;= max_num:</code></p>\n\n<pre><code> return input_name\n break\n</code></pre>\n\n<p>You don't need <code>break</code> here, the <code>return</code> makes it unreachable.</p>\n\n<pre><code> input_name = 'Please try again: '\n</code></pre>\n\n<p>Assigning a string to something that's otherwise always a number is odd, and this value is never used anyway. Nix this line.</p>\n\n<pre><code> else:\n print 'Goodbye!'\n break\n</code></pre>\n\n<p>This will end up falling off the end of the function, and so returning <code>None</code>. The rest of your script will continue, but eventually fail horribly. This probably isn't what you want.</p>\n\n<pre><code>month = 0\nday = 0\nyear = 0\ncentury = 0\n</code></pre>\n\n<p>Only reason to initialise these to 0 is to pass them into <code>input_value</code>, but, as I said above, it never uses the zero values. So, you don't need this. </p>\n\n<pre><code>month = input_value(month, \"Please enter the month (from 1-12, where March is 1 and February is 12): \", 1, 12)\n</code></pre>\n\n<p>March = 1 is an odd system. Consider inputting it as January=1 and then transforming it with:</p>\n\n<pre><code># Weirdify month counting\nmonth = month - 2 if month &lt; 3 else month + 10\n</code></pre>\n\n<p>To not surprise your users.</p>\n\n<pre><code>day = input_value(day, \"Please enter the day (from 1-31): \", 1, 31)\nyear = input_value(year, \"Please enter the year (from 0 - 99, eg. 88 in 1988): \", 0, 99)\ncentury = input_value(century, \"Please enter the century (from 0 - 99, eg. 19 in 1988): \", 0, 99)\n</code></pre>\n\n<p>These lines are very long. You should wrap them per <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>:</p>\n\n<pre><code> year = input_value(\"Please enter the century (from 0 - 99, eg. 19 in 1988): \",\n 0, 99)\n</code></pre>\n\n<p>Also, you might consider inputting <code>year</code> and <code>century</code> as a single value ('1988') and separating it in the script.</p>\n\n<pre><code>A = month\nB = day\nC = year\nD = century\n</code></pre>\n\n<p>Just use the long names throughout your formulae, eg <code>X = year / 4</code>. </p>\n\n<pre><code>W = (13*A - 1) / 5\nX = C / 4\nY = D / 4\nZ = W + X + Y + B + C - 2*D\nR = Z % 7\n\nbirthday = \"You were born on \" + str(B) + \"/\" + str(A+2) + \"/\" + str(D) + str(C) + \" which was a \"\n</code></pre>\n\n<p>Use string formatting instead of concatenation:\n birthday = \"You were born on {}/{}/{}, which was a {}{}\".format(day, month+2, \n century, year)</p>\n\n<pre><code>if R == 0:\n print birthday + 'Sunday'\nelif R == 1:\n print birthday + 'Monday'\nelif R == 2:\n print birthday + 'Tuesday'\nelif R == 3:\n print birthday + 'Wednesday'\nelif R == 4:\n print birthday + 'Thursday'\nelif R == 5:\n print birthday + 'Friday'\nelif R == 6:\n print birthday + 'Saturday'\n</code></pre>\n\n<p>This can go into a list:</p>\n\n<pre><code> days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', \n 'Thursday', 'Friday', 'Saturday']\n day_of_week = days[R]\n</code></pre>\n\n<p>And then that can go in the above string formatting instead of being concatenated on later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T15:44:05.317", "Id": "13970", "Score": "0", "body": "@Ivc thanks, this is really great advice. There are two points which I don't fully understand. I don't know how to use `continue`, even after looking it up on the python docs. I also don't fully understand the 'string formatting' and 'listing days of the week' point. Can you offer any more advice here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T03:51:23.873", "Id": "13992", "Score": "0", "body": "`continue` is sortof like `break`, except that it goes back to the top of the loop instead of falling out the bottom. For string formatting, look up the documentation for `str.format()`, and the \"String Formatting mini language\". Basically it achieves the same thing as concatenating all your variables into the string, except its easier to read, and potentially more efficient (especially if your code ever gets run on, say, PyPy). For the days of the week, `days[0]` is `'Sunday'` - it avoids the chain of `if`/`elif`, and will error instead of failing silently if your R is >6 somehow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T12:14:45.227", "Id": "8919", "ParentId": "8918", "Score": "5" } } ]
{ "AcceptedAnswerId": "8919", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T11:41:52.803", "Id": "8918", "Score": "2", "Tags": [ "python", "algorithm", "datetime" ], "Title": "Zeller's algorithm in Python" }
8918
<p><strong>My inspiration for creating this protocol came from iOS 5's "dismissViewControllerAnimated:completion:" addition to UIViewController. I wanted this functionality in iOS 4.3. I find using the modal view's -viewDidDissapear to invoke methods on the presenting view controller work's very well. One benefit is the ability to delay deallocation on the modal view controller. Please post any improvements I can make.</strong></p> <hr> <p><strong>PresentorDelegateProtocol.h</strong></p> <pre><code>@protocol PresentorDelegateProtocol &lt;NSObject&gt; @optional /* Extra protocol methods defined in protocol for flexibility. Main methods are: - (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated; - (void)modalViewDissapeared:(id)modalView; //used in modal view's -viewDidDissapear */ - (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated; - (void)modalViewDissapeared:(id)modalView; // use the block in this method send messages to save state, etc. This is the one I like to use. - (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated withBlock:(void(^)())block; // use in other classes that are not controlling dismissal of the modal view - (void)executeBlockOnModalDissapearance: (void(^)())block; @end </code></pre> <hr> <p><strong>PresentingViewController.h</strong></p> <pre><code>#import "PresentorDelegateProtocol.h" @interface PresentingViewController : UIViewController &lt;PresentorDelegateProtocol&gt; - (void)showModalVC; @end </code></pre> <hr> <p><strong>ModalViewController.h</strong></p> <pre><code>#import "PresentorDelegateProtocol.h" @interface ModalViewController : UIViewController @property (nonatomic, assign) id &lt;PresentorDelegateProtocol&gt; presentorDelegate; - (void)close; @end </code></pre> <hr> <p><strong>PresentingViewController.m</strong></p> <pre><code>#import "PresentingViewController.h" #import "ModalViewController.h" @implementation PresentingModalViewController - (void)showModalVC { ModalViewController *modalVC = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil]; modalVC.presentorDelegate = self; [self presentModalViewController:modalVC animated:YES]; } - (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated { if ([modalView isKindOfClass:[ModalViewController class]]) { NSLog(@"Can invoke based on class"); } [self dismissModalViewControllerAnimated:animated]; } - (void)dismissPresentingModalViewController:(id)modalView animated:(BOOL)animated withBlock:(void(^)())block { block(); /* execute block before or after calling to dismiss modal view */ [self dismissPresentingModalViewController:modalView animated:animated]; //block(); } - (void)modalViewDissapeared:(id)modalView { if ([modalView isKindOfClass:[ModalViewController class]]) { NSLog(@"Do stuff based on class."); } } - (void)executeBlockOnModalDissapearance: (void(^)())block { block(); NSLog(@"This delay's dealloc on modal view until block completes"); } @end </code></pre> <hr> <p><strong>ModalViewController.m</strong></p> <pre><code>#import "ModalViewController.h" @implementation ModalViewController @synthesize presentorDelegate; - (void)close { if (1 == 0 /*need to do something before dealloc*/){ [self.presentorDelegate dismissPresentingModalViewController:self animated:YES withBlock:^{ NSLog(@"Do stuff with block. Save, animate, etc"); }]; } else { [self.presentorDelegate dismissPresentingModalViewController:self animated:YES]; } } - (void)viewDidDisappear:(BOOL)animated { if (1 == 0 /*stuff to do*/){ [self.presentorDelegate executeBlockOnModalDissapearance:^{ // do stuff before modal view is deallocated }]; } [self.presentorDelegate modalViewDissapeared:self]; presentorDelegate = nil; [super viewDidDisappear:animated]; } @end; </code></pre>
[]
[ { "body": "<p>Two light suggestions:</p>\n\n<ul>\n<li>disappear has one s and two ps.</li>\n<li>the word \"block\" to describe a block is accurate but not very descriptive. OK, so I need to pass a block, but I can see that from the parameter list. What the block is <em>for</em> should be explained in the method name: this is why Apple often uses phrases like \"completion handler\" or \"comparator\" to describe block parameters.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T07:25:53.697", "Id": "11428", "ParentId": "8924", "Score": "2" } }, { "body": "<p>It's not very clear from your description of which problem you're trying to solve and how. The role of the objects is not really clear. Please try to describe the proposed architecture so that it's becomes easier to understand.</p>\n\n<p>how the objects react to events and interact with each other.</p>\n\n<ul>\n<li>Is one or both of the classes supposed to be reused or are you describing a pattern that has to reimplemented for each usage?</li>\n<li>Which events on the view controllers lead to execution of which methods?</li>\n<li>How do the objects interact?</li>\n</ul>\n\n<p>Glimpsing over the code I noticed the way you use blocks. I don't see the benefit of blocks when the method that takes the block just immediately executes it. Are the blocks supposed to be kept around and called later?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T08:24:28.353", "Id": "11429", "ParentId": "8924", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T18:43:32.737", "Id": "8924", "Score": "2", "Tags": [ "objective-c", "ios" ], "Title": "iOS4 alternatives for dismissViewControllerAnimated:completion:" }
8924
<p>This is from an answer to my own <a href="https://stackoverflow.com/q/9242733/12048">StackOverflow question</a> on how to efficiently find a <a href="http://en.wikipedia.org/wiki/Regular_number" rel="nofollow noreferrer">regular number</a> that is greater than or equal to a given value.</p> <p>I originally implemented this in C# but translated it to Python because I guessed (correctly) that it would be shorter and would eliminate a third-party library dependency.</p> <p>I am a Python newbie though - This is the longest Python program I have ever written. So I would like to know:</p> <ul> <li>Is there a convention for indicating what version of the language you are targeting (like <code>require&nbsp;&lt;version&gt;</code> in perl?) This program only works in 2.6. <li>Instead of the priority queue, is there a better way to generate the odd regular numbers? I know it is possible to implement lazy lists in Python but they are not in 2.6 are they? <li>Any other idioms/naming conventions I am missing? </ul> <pre><code>from itertools import ifilter, takewhile from Queue import PriorityQueue def nextPowerOf2(n): p = max(1, n) while p != (p &amp; -p): p += p &amp; -p return p # Generate multiples of powers of 3, 5 def oddRegulars(): q = PriorityQueue() q.put(1) prev = None while not q.empty(): n = q.get() if n != prev: prev = n yield n if n % 3 == 0: q.put(n // 3 * 5) q.put(n * 3) # Generate regular numbers with the same number of bits as n def regularsCloseTo(n): p = nextPowerOf2(n) numBits = len(bin(n)) for i in takewhile(lambda x: x &lt;= p, oddRegulars()): yield i &lt;&lt; max(0, numBits - len(bin(i))) def nextRegular(n): bigEnough = ifilter(lambda x: x &gt;= n, regularsCloseTo(n)) return min(bigEnough) </code></pre>
[]
[ { "body": "<pre><code>from itertools import ifilter, takewhile\nfrom Queue import PriorityQueue\n\ndef nextPowerOf2(n):\n</code></pre>\n\n<p>Python convention says that function should be named with_underscores</p>\n\n<pre><code> p = max(1, n)\n while p != (p &amp; -p):\n</code></pre>\n\n<p>Parens not needed.</p>\n\n<pre><code> p += p &amp; -p\n return p\n</code></pre>\n\n<p>I suspect that isn't the most efficient way to implement this function. See here for some profiling done on various implementations. <a href=\"http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/\" rel=\"nofollow\">http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/</a></p>\n\n<pre><code># Generate multiples of powers of 3, 5\ndef oddRegulars():\n q = PriorityQueue()\n</code></pre>\n\n<p>So this is a synchronized class, intended to be used for threading purposes. Since you aren't using it that way, you are paying for locking you aren't using.</p>\n\n<pre><code> q.put(1)\n prev = None\n while not q.empty():\n</code></pre>\n\n<p>Given that the queue will never be empty in this algorithm, why are you checking for it?</p>\n\n<pre><code> n = q.get()\n if n != prev:\n prev = n\n</code></pre>\n\n<p>The prev stuff bothers me. Its ugly code that seems to distract from your algorithm. It also means that you are generating duplicates of the same number. I.e. it would be better to avoid generating the duplicates at all.</p>\n\n<pre><code> yield n\n if n % 3 == 0:\n q.put(n // 3 * 5)\n q.put(n * 3)\n</code></pre>\n\n<p>So why don't you just push <code>n * 3</code> and <code>n * 5</code> onto your queue?</p>\n\n<pre><code># Generate regular numbers with the same number of bits as n\ndef regularsCloseTo(n):\n p = nextPowerOf2(n)\n numBits = len(bin(n))\n</code></pre>\n\n<p>These two things are basically the same thing. <code>p = 2**(numBits+1)</code>. You should be able to calculate one from the other rather then going through the work over again.</p>\n\n<pre><code> for i in takewhile(lambda x: x &lt;= p, oddRegulars()):\n yield i &lt;&lt; max(0, numBits - len(bin(i)))\n</code></pre>\n\n<p>I'd have a comment here because its tricky to figure out what you are doing. </p>\n\n<pre><code>def nextRegular(n):\n bigEnough = ifilter(lambda x: x &gt;= n, regularsCloseTo(n))\n return min(bigEnough)\n</code></pre>\n\n<p>I'd combine those two lines.</p>\n\n<blockquote>\n <p>Is there a convention for indicating what version of the language you are targeting (like > require in perl?) This program only works in 2.6.</p>\n</blockquote>\n\n<p>Honestly, much programs just fail when trying to use something not supported in the current version of python. </p>\n\n<blockquote>\n <p>I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?</p>\n</blockquote>\n\n<p>Lazy lists? You might be referring to generators. But they are supported in 2.6, and you used one in your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:57:08.783", "Id": "14009", "Score": "0", "body": "The point of the bit twiddling was to calculate exactly the right power of 2 to multiply by to get the regular number in the right range. This could be applied to your version, if you turn those nested loops inside-out, the inner loop could be replaced by a bit count + shift. \nAnd no I was referring to lazy lists: http://svn.python.org/projects/python/tags/r267/Lib/test/test_generators.py" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T17:00:59.270", "Id": "14010", "Score": "0", "body": "@finnw, oh I figured out what you were doing with the bit twiddles. It just took me a while, hence my suggestion for a comment. Certainly you can further improve my version, I've left that as an exercise for the reader." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T17:03:14.480", "Id": "14011", "Score": "1", "body": "@finnw, I don't think that any version of python includes lazy lists. You can implement lazy lists, which is what is done in what you linked. But as far as I know they've never been added to the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T23:51:52.010", "Id": "51372", "Score": "0", "body": "Note that this doesn't fulfill the original requirements of \"greater than or equal to\". The original question wants p(18) = 18, but this returns 24" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T02:02:45.247", "Id": "51605", "Score": "0", "body": "This doesn't produce the right numbers. `next_regular(670)` should produce 675 but produces 720, `next_regular(49)` should produce 50 but produces 54, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T02:06:41.250", "Id": "51606", "Score": "1", "body": "@endolith, removed apparently bad algorithm." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T04:53:31.293", "Id": "8931", "ParentId": "8928", "Score": "2" } } ]
{ "AcceptedAnswerId": "8931", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T23:29:25.053", "Id": "8928", "Score": "5", "Tags": [ "python" ], "Title": "Find the smallest regular number that is not less than N (Python)" }
8928
<p>It compiles, works well, solves my problem of zipping old or big log files and removes them from a hard drive. However, following <a href="https://stackoverflow.com/a/9190590/692020">this answer</a>, I would like to know what was wrong with the code.</p> <pre><code>Dir.foreach(FileUtils.pwd()) do |f| if f.end_with?('log') File.open(f) do |file| if File.size(f) &gt; MAX_FILE_SIZE puts f puts file.ctime puts file.mtime # zipping the file orig = f Zlib::GzipWriter.open('arch_log.gz') do |gz| gz.mtime = File.mtime(orig) gz.orig_name = orig gz.write IO.binread(orig) puts "File has been archived" end #deleting the file begin File.delete(f) puts "File has been deleted" rescue Exception =&gt; e puts "File #{f} can not be deleted" puts " Error #{e.message}" puts "======= Please remove file manually ==========" end end end end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T01:39:05.067", "Id": "28985", "Score": "1", "body": "Ruby's indentation style is usually 2 spaces, just as a minor heads up." } ]
[ { "body": "<p>My proposal, please see also the comments in the code.</p>\n\n<pre><code>require 'zlib'\nMAX_FILE_SIZE = 1024 #One KB\n\n#Use a glob to get all log-files\nDir[\"#{Dir.pwd}/*.log\"].each do |f|\n #skip file, if file is small\n next unless File.size(f) &gt; MAX_FILE_SIZE\n #Make a one line info\n puts \"#{f}: #{File.size(f)/1024}KB, created #{File.ctime(f)} modified #{File.mtime(f)} \"\n\n # zipping the file - each log in a file\n Zlib::GzipWriter.open(\"arch_#{File.basename(f)}.gz\") do |gz|\n gz.mtime = File.mtime(f)\n gz.orig_name = File.basename(f) #filename without path\n #File.read should be fine for log files. Or is there a reason for IO.binread\n gz.write File.read(f) \n puts \"File #{f} has been archived\"\n end\n\n #deleting the file\n begin\n #~ File.delete(f)\n puts \"File #{f} has been deleted\"\n rescue Exception =&gt; e\n puts \"File #{f} can not be deleted\"\n puts \" Error #{e.message}\" \n puts \"======= Please remove file manually ==========\"\n end\nend\n</code></pre>\n\n<p>Remark:</p>\n\n<p>This solution creates one gz-file per log file. Your old solution created one <code>arch_log.gz</code>. If there were two log-files, the 2nd would overwrite the 1st.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T11:24:50.380", "Id": "14003", "Score": "0", "body": "defintely sorry I didn't put require and global variables, thanks for a good answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T18:43:34.967", "Id": "14064", "Score": "1", "body": "@DanielMyasnikov if this answered the question (made a good suggestion?) then you should mark it as the selected answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:48:58.117", "Id": "14152", "Score": "0", "body": "@knut, no there were no reason for IO.binread, I just got if from Ruby Doc library web-site (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/zlib/rdoc/Zlib/GzipWriter.html)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T09:35:04.983", "Id": "8934", "ParentId": "8929", "Score": "4" } } ]
{ "AcceptedAnswerId": "8934", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T23:59:24.470", "Id": "8929", "Score": "3", "Tags": [ "ruby", "file-system", "file", "logging", "compression" ], "Title": "GZip archiver for log files" }
8929
<p>I've been playing with Clojure for the last few evenings, going through the well known 99 problems (I'm using <a href="http://aperiodic.net/phil/scala/s-99/" rel="nofollow">a set adapted for Scala</a>).</p> <blockquote> <p><strong>Problem 26</strong></p> <p>Given a set <em>S</em> and a no. of items <em>K</em>, returns all possible combinations of <em>K</em> items that can be taken from set <em>S</em>.</p> </blockquote> <p>Here's my solution:</p> <pre><code>(defn combinations [k s] (cond (&gt; k (count s)) nil ;not enough items in sequence to form a valid combination (= k (count s)) [s] ;only one combination available: all items (= 1 k) (map vector s) ;every item (on its own) is a valid combination :else (reduce concat (map-indexed (fn [i x] (map #(cons x %) (combinations (dec k) (drop (inc i) s)))) s)))) (combinations 3 ['a 'b 'c 'd 'f]) </code></pre> <p>My basic solution is to take each item from the given sequence (<code>map-indexed</code>) and recurse to generate combinations of size <code><em>K</em> - 1</code> from the remaining sequence. The termination conditions are described above.</p> <p>I'm still a complete Clojure newbie and would welcome comments on structure, efficiency, readability, resemblance to idiomatic Clojure, etc. Feel free to be brutal, but please remember I've been doing Clojure for only a few hours :)</p> <p>I'm less interested in alternative mathematical methods for generating <em>k</em>-combinations, more interested in feedback on whether this is passable Clojure.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T01:38:30.703", "Id": "34042", "Score": "2", "body": "Check how it is done in math.combinatorics https://github.com/clojure/math.combinatorics/blob/master/src/main/clojure/clojure/math/combinatorics.clj#L69" } ]
[ { "body": "<p>I'm currently reading \"Joy of Clojure\" so I'm (very) far from being \"fluent\" in Clojure but what I noticed is:</p>\n\n<ul>\n<li>your solution is clever but quite complicated, you use \"imperative\" habits like indexed iteration</li>\n<li>try to keep with simple abstractions like sequence <b>first</b> and <b>rest</b> and the solution will work with any Clojure collection - see example below</li>\n<li>your solution use <b>cond</b> with three checks for <b>k</b> - consider using <b>condp</b></li>\n</ul>\n\n<p>Here's my code:</p>\n\n<pre><code>(defn subsets [n items]\n(cond\n (= n 0) '(())\n (empty? items) '()\n :else (concat (map\n #(cons (first items) %)\n (subsets (dec n) (rest items)))\n (subsets n (rest items)))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T20:18:59.863", "Id": "9569", "ParentId": "8930", "Score": "3" } } ]
{ "AcceptedAnswerId": "9569", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T00:21:33.320", "Id": "8930", "Score": "5", "Tags": [ "clojure", "combinatorics" ], "Title": "Enumerate k-combinations in Clojure (P26 from 99 problems)" }
8930
<p>I saw this question <a href="https://codereview.stackexchange.com/q/7226/7153">"Is this implementation of an Asynchronous TCP/UDP Server correct"</a> and it is very similar to what I want to do but it goes about it in a different way so I am wondering if anyone would mind doing some constructive critism on my method please.</p> <p>I'm looking for any feedback along the lines of "when x happens your server will fall over because of y" or something like that.</p> <p>My intention is that the server should log out errors that happen and raise an event when it has data. I want it to be really resilient and just deal with errors where it can and carry on waiting for clients but there is a point where I think that is not possible which is why I have the FatalError event.</p> <p>So, my server class will have this interface:</p> <pre><code>public interface IMySocketServer { // Start the server listening and return immediately void Open(); // Stop the server void Close(); // Raised when data is receieved event EventHandler&lt;SocketDataEventArgs&gt; DataReceived; // Raised when a fatal error has happened such that the // server cannot recover itself event EventHandler&lt;EventArgs&gt; FatalError; } </code></pre> <p>and for completeness here is the event arguments class:</p> <pre><code>public class SocketDataEventArgs : EventArgs { private readonly byte[] _data; public SocketDataEventArgs(byte[] data) { _data = data; } public byte[] GetData() { return _data; } } </code></pre> <p>My implementation looks like this:</p> <pre><code>public class MySocketServer : IMySocketServer { private readonly TcpListener _listener; private ILogger _logger = NullLogger.Instance; public event EventHandler&lt;SocketDataEventArgs&gt; DataReceived; public event EventHandler&lt;EventArgs&gt; FatalError; public MySocketServer(int port) : this(port, 2048) { } public MySocketServer(int port, int inputBufferSize) { InputBufferSize = inputBufferSize; _listener = new TcpListener(IPAddress.Any, port); } public ILogger Logger { get { return _logger; } set { _logger = value; } } public int InputBufferSize { get; set; } protected virtual void OnDataReceived(SocketDataEventArgs e) { var evt = DataReceived; if (evt != null) { evt(this, e); } } protected virtual void OnFatalError(EventArgs e) { var evt = FatalError; if (evt != null) { evt(this, e); } } public void Close() { _listener.Stop(); } // Start the server - this will throw a SocketException or an // ObjectDisposedException if it cannot start - the caller can catch // these and deal with them. It will also check the buffer is a // sensible size and throw an ArgumentOutOfRangeException if not public void Open() { if (InputBufferSize &lt;= 0) { throw new ArgumentOutOfRangeException("The buffer must be larger than 0"); } _listener.Start(); var res = _listener.BeginAcceptSocket(OnAcceptSocket, _listener); if (res.CompletedSynchronously) { AcceptSocket(res); } } private void OnAcceptSocket(IAsyncResult res) { var thread = Thread.CurrentThread; if (string.IsNullOrEmpty(thread.Name)) { thread.Name = "Accept " + thread.ManagedThreadId; } if (!res.CompletedSynchronously) { AcceptSocket(res); } } private void AcceptSocket(IAsyncResult res) { // End the current Accept and get the socket and start another // one straight away so as not to block the server var listener = (TcpListener)res.AsyncState; Socket socket = null; try { socket = listener.EndAcceptSocket(res); } catch (ObjectDisposedException e) { // Will log this exception but I do not think there is anything // else to do here? Logger.Error(e); } catch (SocketException e) { // If the socket is closed before we can end log the error but // bury it since it is probably a client that has disconnected Logger.Error(e); } try { var r = listener.BeginAcceptSocket(OnAcceptSocket, listener); if (r.CompletedSynchronously) { AcceptSocket(r); } } catch (SocketException e) { // This is really bad if this happens - we will not // be able to accept the next TCP request not sure there // is much I can do here, the server is just broken, or // is there something I can do?? Logger.Error(e); OnFatalError(new EventArgs()); } catch (ObjectDisposedException e) { // See above - same reason Logger.Error(e); OnFatalError(new EventArgs()); } if (socket != null) { // If it gets here, we are waiting for the next client and we // have the socket for this client HandleSocket(socket); } } private void HandleSocket(Socket socket) { var ms = new MemoryStream(); using (socket) { try { // Read the input in chunks and append them // to the data array var buffer = new byte[InputBufferSize]; int read; while ((read = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) &gt; 0) { ms.Write(buffer, 0, read); } } catch (SocketException e) { Logger.Error(e); } } // Now everything should be closed we can raise the data received // event OnDataReceived(new SocketDataEventArgs(ms.ToArray())); } } </code></pre> <p><strong>Update</strong></p> <p>It has been pointed out that I should clarify some thnigs (thanks <a href="https://codereview.stackexchange.com/users/2612/bobby">Bobby</a>):</p> <ol> <li><p>The names of the types are just because I didn't want to say exactly what I would call it in real life since it would describe the product (rest assured the name is not My anything and is wonderfully descriptive).</p></li> <li><p>I didn't go XML doc comment style because I wanted to keep the code part brief for this question (I do always xml comment in the real world, but I wanted to know about the implementation and just commented essentially what each bit is doing). </p></li> <li><p>The Data of my SocketEventArgs should not be a readonly property because I do not want it to be modified by the caller.</p></li> <li><p>I don't agree with the naming convention for c# member variables described at <a href="http://msdn.microsoft.com/en-us/library/ms229002.aspx" rel="nofollow noreferrer">Guidelines for Names</a> as I have found that I really do want to know if a variable is a member) and the <code>_</code> is pretty common (and less tedious and mistake prone than requiring <code>this.</code>) - just a personal preference thing I know!</p></li> <li><p>The wrapping is because I keep the code to 80 characters wide (this is a convention to make it easy to read on whatever resolution/font size you are using - I find horizontal scrolling code to be a horrible reading experience) - lining up the parameters like that is so you can see which method they are gonig into. </p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T08:17:48.860", "Id": "22229", "Score": "0", "body": "No comment on the listener at the mo, but a quick suggestion would be to make Logger private unless there's a specific reason you want to expose it to the world. I would then set it via the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T10:13:43.350", "Id": "22244", "Score": "0", "body": "The logger is like that so that it can be injected by an IoC container (if an ILogger is registered with the container, if not it will use the NullLogger)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T10:26:49.747", "Id": "22245", "Score": "0", "body": "Modules like Ninject and Unity allow injection via constructor. However if it's a design need, then fair enough. I like to remove as much public exposure of properties as I can if it's not needed that's all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T11:11:32.653", "Id": "22249", "Score": "0", "body": "Yup, I do not know about those two containers but I use Windsor and a constructor argument that is not registered with the container will result in the class not being able to be resolved (here I don't care whether ILogger is registered or not - it is an optional dependency) - good point about the public exposure thing but in this case I think it is justified" } ]
[ { "body": "<p>I'd raise the events <code>DataReceived</code> and <code>FatalError</code> on a different thread, to avoid blocking the TCP work. To elaborate this point, I suggest you take a look at <a href=\"https://github.com/kayak/kayak/\" rel=\"nofollow\">Kayak</a>'s implementation (it's an implementation of HTTP server, but the core looks quite similar).</p>\n\n<p>Other than that, any magic number, like the 1024 bytes buffer size, should be exposed somehow, or at least be injected in the constructor.</p>\n\n<p><strong>Update</strong></p>\n\n<p>You use a setter to the buffer size without validation. I'd throw an exception if the new value is non-positive.</p>\n\n<p>In your <code>HandleSocket</code> method, you build a byte array in a non-effective technique: you reallocate memory in each iteration. I'd use a <code>List&lt;byte&gt;</code> and invoke its <code>AddRange</code> method. After the loop is done - invoke <code>ToArray</code>.</p>\n\n<p>As for the async pattern, it looks non-blocking what so ever, I missed the point of handling the socket <strong>after</strong> re-invoking <code>BeginAcceptSocket</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T05:20:54.547", "Id": "24113", "Score": "0", "body": "Thanks very much! I have added the buffer size as a constructor argument (via an overload to make it optional and a property) and will have a look at the Kayak stuff about raising the events in a separate thread - as I am using the asynchronous pattern though - will it actually block the TCP work as it stands?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T08:02:35.687", "Id": "24917", "Score": "0", "body": "Thanks for your update (sorry, I didn't notice it) - I added some validation into Open to check the buffer size (I dunno, I just prefer it if setters and constructors don't throw - rather have Open check the state of the world before it starts off). About the array copy stuff: I thought that was a bit poor but the thing is I cannot call AddRange on a List<byte> because it only takes an IEnumerable and would, therefore, append the entire buffer, but I want to append just the \"read\" bytes. I can only thing a for loop and calling Add on the List would work, but would that be any better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T08:59:37.083", "Id": "24922", "Score": "0", "body": "I asked about the array stuff over on Stack Overflow: http://stackoverflow.com/q/12296053/1039947 and went with a MemoryStream." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T04:47:33.180", "Id": "14842", "ParentId": "8935", "Score": "3" } } ]
{ "AcceptedAnswerId": "14842", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T12:22:54.503", "Id": "8935", "Score": "8", "Tags": [ "c#", ".net" ], "Title": ".Net TCP Server" }
8935
<p>i'm rewriting some Matlab code to c++ using <a href="http://arma.sourceforge.net/docs.html#syntax" rel="nofollow">armadillo</a>, a libs for linear algebra. really good libs, IMHO. but i had to translate some matlab construct because armadillo isn't matlab.</p> <p>i want to share my little snippet because i think there should be a better way (in terms of speed, mainly) to solve thoose little problems. i hope someone here could help me to improve my code!</p> <pre><code>static mat log(mat A) { /* * log function operates element-wise on matrix A * MATLAB code&gt; log(A) */ mat X(A); mat::iterator a = X.begin(); mat::iterator b = X.end(); for(mat::iterator i=a; i!=b; ++i) { (*i) = log(*i); } return X; } </code></pre> <p>-</p> <pre><code>static mat vectorize(mat A) { /* * vectorise a matrix (ie. concatenate all the columns or rows) * MATLAB code&gt; A(:) */ mat B = mat(A); B.reshape(B.n_rows*B.n_cols, 1); return B; } </code></pre> <p>-</p> <pre><code>static bool any(mat X, double n) { /* * check if there are some n in X * MATLAB code&gt; any(X==n) * TODO: i'm not sure of description but it works for me */ uvec _s = find(, n); if ( _s.is_empty() ) return true; else return false; } </code></pre> <p>-</p> <pre><code>static double sum(mat X) { /* * sum a matrix * MATLAB code&gt; sum(X) */ return sum(sum(X)) } </code></pre> <p>-</p> <pre><code>static field&lt;rowvec num2cell(mat X) { /* * converts matrix X into field by placing each row of X into a separate row * this method assume that a cell is a field&lt;rowvec&gt;, mayebe a template should be used to generalize.. * MATLAB code&gt; num2cell(X) */ field&lt;rowvec&gt; data1(X.n_rows,1); for (uint r = 0; r &lt; X.n_rows; ++r) { data1(r,0) = X.row(r); } return data1; } </code></pre>
[]
[ { "body": "<p>Cannot say much about the speed, but here are two observations:</p>\n\n<ul>\n<li><p>Your implementation of any appears to give true and false in the opposite way that Matlab would give them.</p></li>\n<li><p>If you want to mimic the n dimensional matrix sum in Matlab, the output should not be a number but a n-1 dimensional matrix. In case of a 'regular' matrix the output should be a vector.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T15:01:35.777", "Id": "19969", "ParentId": "8938", "Score": "3" } }, { "body": "<ol>\n<li><p>You're doing a copy in most of those snippets: if it was possible to do without a copy, it could be faster. Libraries such as Boost often offer two version a specific function: one which copies and another one which modifies in place.</p></li>\n<li><p><code>*i</code> is enough, you don't need <code>(*i)</code>:</p>\n\n<pre><code>*i = log(*i);\n</code></pre></li>\n<li><p>This code:</p>\n\n<pre><code>if ( _s.is_empty() ) \n return true;\nelse\n return false;\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code>return _s.is_empty();\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T13:29:11.367", "Id": "21577", "ParentId": "8938", "Score": "6" } }, { "body": "<p>For new users coming to this page, <a href=\"http://arma.sourceforge.net/docs.html\" rel=\"nofollow noreferrer\">Armadillo</a> has come a long way since 2012. All of these functions have native Armadillo implementations. </p>\n\n<p>Armadillo has had <a href=\"http://arma.sourceforge.net/docs.html#misc_fns\" rel=\"nofollow noreferrer\">element-wise functions</a> since inception I think (someone please correct me): <code>log(A)</code>, <code>log2(A)</code>, and <code>log10(A)</code>:</p>\n\n<pre><code>using namespace arma;\n// Generate a matrix with the elements set to random floating point values\n// randu() uses a uniform distribution in the [0,1] interval \nmat A = randu&lt;mat&gt;(5,5); // or mat A(5, 5, fill::randu);\nmat B = log(A);\n</code></pre>\n\n<p>Added <code>any</code> and <a href=\"http://arma.sourceforge.net/docs.html#vectorise\" rel=\"nofollow noreferrer\">vectorize</a> in version 3.910:</p>\n\n<pre><code>vec V = randu&lt;vec&gt;(10);\nmat X = randu&lt;mat&gt;(5,5);\n\n\n// status1 will be set to true if vector V has any non-zero elements\nbool status1 = any(V);\n\n// status2 will be set to true if vector V has any elements greater than 0.5\nbool status2 = any(V &gt; 0.5);\n\n// status3 will be set to true if matrix X has any elements greater than 0.6;\n// note the use of vectorise()\nbool status3 = any(vectorise(X) &gt; 0.6);\n\n// generate a row vector indicating which columns of X have elements greater than 0.7\nurowvec A = any(X &gt; 0.7);\n</code></pre>\n\n<p>Added <a href=\"http://arma.sourceforge.net/docs.html#accu\" rel=\"nofollow noreferrer\">accu</a> before version 4.6:</p>\n\n<pre><code>mat A(5, 6, fill::randu); // fill matrix with random values\nmat B(5, 6, fill::randu);\ndouble x = accu(A);\ndouble y = accu(A % B); // \"multiply-and-accumulate\" operation\n // operator % performs element-wise multiplication\n</code></pre>\n\n<p>The <code>accu</code> function 'accumulates a sum', while the <code>sum</code> function generates a row or column vector that is the sum of the specified matrix dimension. For a column vector,\nthe sum of the elements is returned:</p>\n\n<pre><code>colvec v = randu&lt;colvec&gt;(10,1);\ndouble x = sum(v);\n\nmat M = randu&lt;mat&gt;(10,10);\n\nrowvec a = sum(M);\nrowvec b = sum(M,0);\ncolvec c = sum(M,1);\n\ndouble y = accu(M); // find the overall sum regardless of object type\n</code></pre>\n\n<p>And Armadillo has its own <a href=\"http://arma.sourceforge.net/docs.html#field\" rel=\"nofollow noreferrer\">field</a> class template:</p>\n\n<pre><code>using namespace arma;\nmat A = randn(2,3);\nmat B = randn(4,5);\n\nfield&lt;mat&gt; F(2,1);\nF(0,0) = A;\nF(1,0) = B; \n\nF.print(\"F:\");\nF.save(\"mat_field\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-02T23:14:11.350", "Id": "238273", "ParentId": "8938", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T14:35:00.433", "Id": "8938", "Score": "4", "Tags": [ "c++", "matlab" ], "Title": "MATLAB and Armadillo, hints on translating" }
8938
<p>I'm writing a checkout form for purchasing online tests. You can buy a certification or a recertification, as well as a pdf or book study manual.</p> <p>I'm using Jinja2 templates to provide test data into the Javascript. The test object is a dictionary with the following structure. All prices are in cents.</p> <pre><code>test { id: Integer, name: String, acronym: String, certification_price: Integer, recertification_price: Integer, study_pdf_price: Integer, study_book_price: Integer, } </code></pre> <p>If a user buys more than one test, they get a discount of 10% off for each additional test.</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script&gt; $(document).ready(function() { var calcTotal = function(){ var total = 0; var numTests = 0; {% for test in tests %} {% if test.certification_price %} if ($('#buy-{{ test.acronym }}-certification').is(':checked')) { total += {{ test.certification_price }}; numTests++; } {% endif %} {% if test.recertification_price %} if ($('#buy-{{ test.acronym }}-recertification').is(':checked')) { total += {{ test.recertification_price }}; numTests++; } {% endif %} {% if test.study_pdf_price %} if ($('#buy-{{ test.acronym }}-pdf').is(':checked')) { total += {{ test.study_pdf_price }}; } {% endif %} {% if test.study_book_price %} if ($('#buy-{{ test.acronym }}-book').is(':checked')) { total += {{ test.study_book_price }}; } {% endif %} {% endfor %} // take 10 percent off for each additional test after the first if (numTests &gt; 0) numTests--; var discountPrice = Math.round(((10 - numTests) * 0.1) * total); $('.product-total').html(Math.round(discountPrice)); $('#final-total').val(discountPrice); } $('.product-selection').click(calcTotal); calcTotal(); }); &lt;/script&gt; &lt;body&gt; &lt;h2&gt;Selected Products&lt;/h2&gt; &lt;form id="registration-form" action="" method="POST"&gt; &lt;table id="products-table"&gt; &lt;tr&gt; &lt;th&gt;Product&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;th&gt;Add to Cart&lt;/th&gt; &lt;/tr&gt; {% for test in tests %} {% if test.certification_price %} &lt;tr&gt; &lt;td&gt;{{ test.acronym }} Certification{% if test.study_pdf_price %} (PDF Manual Included){% endif %}&lt;/td&gt; &lt;td&gt;${{ test.certification_price }}&lt;/td&gt; &lt;td&gt;&lt;input class="product-selection" type="checkbox" id="buy-{{ test.acronym }}-certification" name="buy-{{ test.acronym }}-certification" /&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} {% if test.recertification_price %} &lt;tr&gt; &lt;td&gt;{{ test.acronym }} Recertification&lt;/td&gt; &lt;td&gt;${{ test.recertification_price }}&lt;/td&gt; &lt;td&gt;&lt;input class="product-selection" type="checkbox" id="buy-{{ test.acronym }}-recertification" name="buy-{{ test.acronym }}-recertification" /&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} {% if test.study_pdf_price %} &lt;tr&gt; &lt;td&gt;{{ test.acronym }} {{ test.study_pdf_description }}&lt;/td&gt; &lt;td&gt;${{ test.study_pdf_price }}&lt;/td&gt; &lt;td&gt;&lt;input class="product-selection" type="checkbox" id="buy-{{ test.acronym }}-pdf" name="buy-{{ test.acronym }}-pdf" /&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} {% if test.study_book_price %} &lt;tr&gt; &lt;td&gt;{{ test.acronym }} {{ test.study_book_description }}&lt;/td&gt; &lt;td&gt;${{ test.study_book_price }}&lt;/td&gt; &lt;td&gt;&lt;input class="product-selection" type="checkbox" id="buy-{{ test.acronym }}-book" name="buy-{{ test.acronym }}-book" /&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} &lt;tr&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&lt;/tr&gt; {% endfor %} &lt;tr&gt;&lt;td&gt;&lt;strong&gt;Total&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&lt;strong&gt;$&lt;span class="product-total"&gt;0&lt;/span&gt;&lt;/strong&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;input type="hidden" id="final-total" name="final-total" /&gt; &lt;p&gt;&lt;input id="submit-button" type="submit" value="Place Order"&gt;&lt;/p&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I feel like I am repeating myself a lot, but I don't know how I would do this differently. Also, this way of providing data by writing Javascript code with the templating language seems messy. Any ideas?</p>
[]
[ { "body": "<p>You're right, templating JavaScript code in the way you're doing is messy and usually a bad option. If possible it's almost always better to pass in a single JSON object with all of the values you need and then operate on that object in JavaScript. I don't know Python but something like this:</p>\n\n<pre><code>var tests = {{ json.dumps( tests ) }}, // this is the only template insertion\n total = 0,\n numTests = 0,\n test,\n testIdPfx\n // only one `var` is necessary for multiple declarations\n;\n\n// do this loop in JavaScript instead of the templating system\nfor ( var i; i &lt; tests.length; i++ ) {\n test = tests[ i ]\n\n // do this concatenation just once at the beginning\n testIdPfx = '#buy-' + test.acronym + '-';\n\n // this condition also in JavaScript instead of the template--combined with the\n // `if` you're already doing\n if ( test.certification_price &amp;&amp;\n $( testIdPfx + 'certification' ).is( ':checked' )\n ) {\n total += test.certification_price;\n numTests++;\n }\n\n if ( test.recertification_price &amp;&amp;\n $( testIdPfx + 'recertification' ).is( ':checked' )\n ) {\n total += test.recertification_price;\n numTests++;\n }\n\n // and so on...\n}\n\n// ...\n</code></pre>\n\n<p>(You could also load the JSON object with an Ajax request and avoid templating in your JavaScript entirely, but that might be overkill.)</p>\n\n<p>Already that looks a lot cleaner but you still have a lot of repetition.</p>\n\n<p>Basically the only thing different between your four <code>if</code> blocks is one word: <code>certification</code>, <code>recertification</code>, <code>study_pdf</code> and <code>study_book</code>. So why not put those four words in an array and then reuse the same code four times?</p>\n\n<pre><code>var tests = {{ json.dumps( tests ) }}, // this is the only template insertion\n // here's your four words:\n types = [ 'certification', 'recertification', 'study_pdf', 'study_book' ]\n total = 0,\n numTests = 0,\n test, testIdPfx,\n type,\n price\n;\n\nfor ( var testIdx; testIdx &lt; tests.length; testIdx++ ) {\n test = tests[ testIdx ]\n testIdPfx = '#buy-' + test.acronym + '-';\n\n // repeat for each of the four words in `types`\n for ( var typeIdx; typeIdx &lt; types.length; typeIdx++ ) {\n type = types[ typeIdx ];\n // exploit the fact that `test.foo` and `test['foo']` are equivalent in JavaScript\n price = test[ type + '_price' ];\n\n if ( price &amp;&amp; $( testIdPfx + type ).is( ':checked' ) ) {\n total += price;\n numTests++;\n }\n }\n}\n\n// ...\n</code></pre>\n\n<p>(<strong>Note:</strong> You'll have to adjust your markup to have <code>#buy-{{ test.acronym }}-study_pdf</code> insteady of just <code>-pdf</code> and <code>#buy-{{ test.acronym }}-study_book</code> instead of <code>-book</code> to match the <code>types</code> values, or vice versa.)</p>\n\n<p>A nice side-effect of doing the main <code>for</code> loop in JavaScript instead of the templating system is that you're sending proportionally less JavaScript code to the client, which saves on bandwidth.</p>\n\n<p>If you wanted you could perform a similar reduction in your markup.</p>\n\n<p>Hope that helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:01:01.200", "Id": "8941", "ParentId": "8939", "Score": "2" } } ]
{ "AcceptedAnswerId": "8941", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T15:14:32.993", "Id": "8939", "Score": "0", "Tags": [ "javascript", "python", "html" ], "Title": "How would you improve this point of interaction between Python and Javascript?" }
8939
<p>I wrote some code which divides a line through the words of the text so that each substring is no longer than <code>MaxWidth</code>. It works well, but it's very slow.</p> <pre><code>Pattern pattern = Pattern.compile("(.{1," + symbols + "}(\\b|\\s))"); // symbols - MaxWidth Pattern pattern2 = Pattern.compile("\\s.*"); while ((line = in.readLine()) != null) { // reading file by lines String dopLine = ""; if (pattern2.matcher(line).matches()) { // If a line begins with a space, it is the beginning of a paragraph and need to add \ n if(!tempDopLine.equals("")) { // tempDopLine - Some part of the previous line, which is not full screen tempStringBuffer.append(tempDopLine); tempStringBuffer.append("\n"); lineCounter++; if (lineCounter == lines) { addPage(tempStringBuffer); // create page tempStringBuffer = new StringBuilder(""); lineCounter = 0; numberOfPages++; } } tempDopLine = ""; dopLine = line; } else { dopLine = tempDopLine + " " + line; // if this line } Matcher matcher = pattern.matcher(dopLine); // divide a string into a substrings HashMap&lt;Integer, String&gt; temp = new HashMap&lt;Integer, String&gt;(); int i = 0; while (matcher.find()) { temp.put(i, matcher.group()); i++; } for(i = 0; i &lt; temp.size(); i++) { if (i&lt;(temp.size()-1)) { String tempL = temp.get(i); tempStringBuffer.append(tempL); tempStringBuffer.append("\n"); lineCounter++; if (lineCounter == lines) { addPage(tempStringBuffer); tempStringBuffer = new StringBuilder(""); lineCounter = 0; numberOfPages++; } } else { tempDopLine = temp.get(i); // The last part of the string remember to display it along with the next line } } } </code></pre>
[]
[ { "body": "<p>Few thought,</p>\n\n<p>You do a while loop ( while( matcher.find() ) to find all matchs, then you do a for loop to deal with it. I think that can be done in only one loop.</p>\n\n<p>in you last for loop, you could remove the first if :</p>\n\n<pre><code> for(i = 0; i &lt; (temp.size() -1); i++) {\n\n String tempL = temp.get(i);\n\n tempStringBuffer.append(tempL);\n\n tempStringBuffer.append(\"\\n\");\n lineCounter++;\n if (lineCounter == lines) {\n addPage(tempStringBuffer);\n tempStringBuffer = new StringBuilder(\"\");\n lineCounter = 0;\n numberOfPages++;\n }\n\n } // End for loop\n\n tempDopLine = temp.get(temp.size()-1); \n\n} \n</code></pre>\n\n<p>Other suggestion the HashMap temp got be only a array, because right now your code do a lot of autoboxing ( from int to Integer) add and to retrieve information from your HashMap.</p>\n\n<p><strong>Edit</strong>: Here a quick example to merge your two loops:</p>\n\n<pre><code>String tempL = matcher.group();\nwhile (matcher.find()) {\n\n tempStringBuffer.append(tempL);\n\n tempStringBuffer.append(\"\\n\");\n lineCounter++;\n if (lineCounter == lines) {\n addPage(tempStringBuffer);\n tempStringBuffer = new StringBuilder(\"\");\n lineCounter = 0;\n numberOfPages++;\n }\n tempL = matcher.group();\n\n\n} \n\ntempDopLine = tempL; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T18:36:51.507", "Id": "14014", "Score": "0", "body": "To combine the two loop I need to get the number of elements found in the Matcher. How to do it? In my code - last match must writing to tempDopLine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T07:15:22.877", "Id": "14097", "Score": "0", "body": "Thank you very mych. I using this, but it did not give a large increase in performance. It seems to me that such a low rate because of the regular expressions. They can be something like speed?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:11:14.910", "Id": "8943", "ParentId": "8940", "Score": "2" } } ]
{ "AcceptedAnswerId": "8943", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T15:52:36.657", "Id": "8940", "Score": "2", "Tags": [ "java", "performance", "strings" ], "Title": "Breaking a string into substrings" }
8940
<p>I have recently been trying to improve the quality of my code. Towards this goal I want to start writing unit tests and I also am trying to implement things i have read as best practices. I have read that its better to have a class raise exceptions over returning error codes. In the below class I have an <strong>init</strong> method that has dependency requirements based on other arguments being passed in.</p> <p>Extra details... The class is from a contracts module that has 3 classes. Contract, ContractLine, ContractCustomer. Contracts can be of two types ('item','vendor') and a contract can also be a group contract. Group contracts are one contract shared amount many customers. A "normal" or non group contract would only have one customer these are all sqlalchemy declarative classes. TimeUserMixin is a class that provides create_time,modify_time, create_user,modify_user to classes where i want to track who made changes and when the changes were made.</p> <p>My Questions ...</p> <ol> <li>Are exceptions the right way to go or is there a "better" way to do what I am trying to do.</li> <li>How would I write a tests for this init method?</li> <li><p>Is it a bad idea to pass in other objects to my classes verse passing in the objects id(db id)?</p> <pre><code> class Contract(DeclarativeBase,TimeUserMixin): """ Contract definition. This is the customer contract definition. Valid contract_type's = 'item'|'vendor' """ __tablename__ = 'contracts' contract_id = Column(Integer, primary_key=True,autoincrement=True) code = Column(Unicode(25),nullable=False) description = Column(Unicode(100),nullable=False) notes = Column(Unicode()) is_group_contract = Column(Boolean,nullable=False,default=False) contract_type = Column(Unicode(20)) start_date = Column(Date,nullable=False,default=datetime.date.today) end_date = Column(Date,nullable=False) reminder_date = Column(Date,nullable=False) discount_perc = Column(Numeric(precision=5,scale=4),nullable=False,default=Decimal('0.0')) vendor_id = Column(Integer,ForeignKey('vendors.vendor_id')) vendor = relation('Vendor',backref=backref('contracts'), primaryjoin='Contract.vendor_id == Vendor.vendor_id') _CONTRACT_TYPES = ('item','vendor') @property def customer(self): """ Returs Contracts Customer Returns the customer object if contract is not a group contract. If contract is a group contract raise exception AttributeError """ if self.is_group_contract: raise AttributeError('customer property not avaible on group contracts.') return self.customers[0] def add_line(self,item,price,min_qty=None): """Adds a new contract line to the contract.""" new_line = ContractLine(self,item,price,min_qty) DBSession.add(new_line) def add_customer(self,customer): """ Adds a customer to a contract. customer -- Customer object Raises TypeError if not a group contract and a cutomer is already assigned. """ if not self.is_group_contract and \ len(self.customers) &gt; 1: raise TypeError('Contract is not a group contract, and already has a customer assigned.') new_customer = ContractCustomer(self,customer) DBSession.add(new_customer) def __init__(self,code,description,contract_type, start_date,end_date,reminder_date, customer=None,isgroup=False,vendor=None, discount_perc=None): """ Create new contract Requires 'contract_type' ['item','vendor'] if not a group contract requires customer object if vendor contract requires vendor object and discount perc """ self.code = code self.description = description self.contract_type = contract_type self.start_date = start_date self.end_date = end_date self.reminder_date = reminder_date if contract_type not in self._CONTRACT_TYPES: raise AttributeError("Valid contract types are 'item' &amp; 'vendor'") if isgroup: if customer: raise AttributeError("Group contracts should not have 'customer' passed in") self.is_group_contract = True else: if customer: self.add_customer(customer) else: raise AttributeError('Customer required for non group contracts.') if contract_type == 'vendor': if vendor and discount_perc: self.vendor = vendor self.discount_perc = discount_perc else: if not vendor: raise AttributeError('Vendor contracts require vendor to be passed in') if not discount_perc: raise AttributeError('Vendor contracts reqire discount_perc(Decimal)') class ContractLine(DeclarativeBase,TimeUserMixin): """Contract Line Definition""" __tablename__ = 'contract_lines' line_id = Column(Integer, primary_key=True,autoincrement=True) min_qty = Column(Integer,default=0,nullable=False) contract_price = Column(Numeric(precision=13,scale=2)) contract_id = Column(Integer,ForeignKey('contracts.contract_id'),nullable=False) contract = relation(Contract,backref=backref('lines')) item_id = Column(Integer,ForeignKey('items.item_id'),nullable=False) item = relation('Item',backref=backref('contract_lines')) def __init__(self,contract,item,price,min_qty=None): """Create new contract line""" self.contract = contract self.item = item self.contract_price = price if min_qty: self.min_qty = min_qty class ContractCustomer(DeclarativeBase): """ Contract customer definition Private class should only be accessed from Contract class """ __tablename__ = 'contract_customers' contract_customer_id = Column(Integer, primary_key=True,autoincrement=True) contract_id = Column(Integer,ForeignKey('contracts.contract_id'),nullable=False) contract = relation(Contract,backref=backref('customers'), primaryjoin="ContractCustomer.contract_id == Contract.contract_id") customer_id = Column(Integer,ForeignKey('customers.customer_id')) customer = relation(m_ar.Customer,backref=backref('contracts'), primaryjoin='Customer.customer_id==ContractCustomer.customer_id') def __init__(self,contract,customer): """ Assigns customer to contract contract -- contract object customer -- customer object """ self.contract = contract self.customer = customer </code></pre></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:15:33.803", "Id": "14008", "Score": "0", "body": "I can't seem to get the code block to format correctly." } ]
[ { "body": "<p>You raise odd exceptions. <code>TypeError</code> should be raised when the type of an object is incorrect. But you are raising for not following business rules. <code>AttributeError</code> should be raised when an attribute is not available, not when you fail validation. You should really either raise your own exceptions or use <code>ValueError</code>.</p>\n\n<p>You write unit tests by calling the constructors with different arguments and making sure the correct exceptions get thrown. Where are you having trouble?</p>\n\n<p><code>contract_type</code> is a type parameter. That's a sign that you should really have separate classes for the two types of contracts. You should really have a VendorContract and and ItemContract. </p>\n\n<p>The <code>customer</code> thing doesn't feel right. The class basically modifies its interface depending on whether or not its a group contract. Do you actually need to modify the interface? Can you simply say that Contracts with multiple customers are group contracts, and not separately keep track of whether its a group contract? Does other code distinguish between group and non-group contracts? I don't like they way you've done it here, but without more information I'm not sure of a better way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T17:32:04.833", "Id": "8945", "ParentId": "8944", "Score": "2" } } ]
{ "AcceptedAnswerId": "8945", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:11:22.107", "Id": "8944", "Score": "1", "Tags": [ "python" ], "Title": "Best way to test for required attributes of a classes __init__ method" }
8944
<p>I'm working on a <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Game Of Life</a> clone as my first project. I'm still relatively new to programming, so my code is probably not really optimised.</p> <p>The biggest bottleneck is in my <code>Start()</code> method, but that contains a lot of Unity3D specific methods which most people here probably don't know about. That's why I'm leaving that out.</p> <p>My second bottleneck is somewhere in my <code>Update()</code> method. In here, I'm looping through my array which is currently 100 by 100 large, 10.000 in total.</p> <p>I've been checking with the built-in profiler of Unity3D, and this reports that the biggest bottleneck is the garbage collection.</p> <p>I also tried to put half of the loop in another thread, but that didn't work out properly, because it needs to look up cells in the other half.</p> <p>If you see any other ways to improve my code, and not just the performance, feel free to let me know. But please, keep it simple, as I'm still relatively new to programming.</p> <p>The relevant code:</p> <pre><code>void Update() { timeElapsed += Time.deltaTime; // this will add deltaTime to timeElapsed, if (timeElapsed &gt;= timeBetween) // until timeElapsed exceeds timeBetween, { // which allows a new generation to be calculated timeElapsed -= timeBetween; if (gameState == GameState.Game_Playing) { grid = CheckAdjacent(grid); // draw new generation UpdateInformation(); // update information variables } } } public static void DrawGeneration(bool[,] grid) { for (int x = 0; x &lt; gridX; x++) { for (int y = 0; y &lt; gridY; y++) { cubeGrid[x,y].renderer.enabled = grid[x,y]; // enables the renderer for active cells. } } } private void UpdateInformation() { generation++; //counts the generations } public static int GetAliveCells () { int i = 0; for (int x = 0; x &lt; gridX; x++) { for (int y = 0; y &lt; gridY; y++) { if (grid[x, y]) // counts the number of alive cells i++; } } return i; } bool IsCellAlive(int adjacentCount, bool isAlive) { if (isAlive) return liveRule.Contains(adjacentCount); else return becomeAliveRule.Contains(adjacentCount); } private bool[,] CheckAdjacent(bool[,] grid) { int adjacentSquares = 0; bool[,] newGrid = new bool[gridX, gridY]; for (int x = 0; x &lt; gridX; x++) { for (int y = 0; y &lt; gridY; y++) { adjacentSquares = 0; if (grid[calcX(x - 1), calcY(y - 1)]) adjacentSquares++; if (grid[calcX(x), calcY(y - 1)]) adjacentSquares++; if (grid[calcX(x + 1), calcY(y -1)]) adjacentSquares++; if (grid[calcX(x - 1), calcY(y)]) adjacentSquares++; if (grid[calcX(x + 1), calcY(y)]) adjacentSquares++; if (grid[calcX(x - 1), calcY(y + 1)]) adjacentSquares++; if (grid[calcX(x), calcY(y + 1)]) adjacentSquares++; if (grid[calcX(x + 1), calcY(y + 1)]) adjacentSquares++; newGrid[x,y] = IsCellAlive(adjacentSquares, grid[x,y]); } } return newGrid; } private int calcX(int x) { x += gridX; return (x % gridX); } private int calcY(int y) { y += gridY; return (y % gridY); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:06:43.800", "Id": "14055", "Score": "0", "body": "This is too awesome... favourited!" } ]
[ { "body": "<ol>\n<li><p>I would advise you to count neighbours from alive points, not for cells to be checked. Null a 100x100 int array Neighbours. For every alive cell add +1 into every neighbouring cell in Neighbours. After the pass you have number of neighbours for the every cell, but time used is about 1/4 at most, because you saved the time not counting neighbours for zero cells.</p></li>\n<li><p>You are taking left neighbours for utmost left cells, for example. Out of boundaries! You are blocking this by taking a function and modulo and thus making the toroid out of plane, but thus you are counting much longer - division or modulo are slow, functions even more slow. Simply count neighbours normally for the field except boundaries, otherwards for the four sides and four corners. More to write, but less to count later. </p></li>\n<li><p>If you want a shorter code, you could use a help arrays ( I have invented them for myself in 1978)</p>\n\n<pre><code>// neighbor-vectors in xy coordinates clockwise from algebraic x axis.\nint [8] dx={1,1,0,-1,-1,-1,0,1};\nint [8] dy={0,-1,-1,-1,0,1,1,1};\n</code></pre>\n\n<p>and in counting neighbours for a cell do:</p>\n\n<pre><code>if(cell[x,y]&gt;0)\nfor(i=0;i&lt;8;i++){\n x1=x+dx[i];\n y1=y+dy[i];\n if(x1&gt;=0 &amp; x1&lt;100 &amp; y1&gt;=0 &amp; y1&lt;100){\n neighbours[x1,y1]++;\n }\n}\n</code></pre></li>\n<li><p>Count the time spent for different activities, for not to waste time on optimizing part that takes 0.1% of time.</p>\n\n<p>So you can throw off many objects, not to create them at all. Only hold 2 desk in 2x100x100 array - each time one will be active, the other will be old. You can even count neighbours and later make living/dead cells on the same desk. No garbage collection.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T09:35:20.490", "Id": "14037", "Score": "0", "body": "Thank you very much for the help! Will try to implement it later, at home. With suggestion 4, do you mean to make the array [2, 100, 100], instead of 2 arrays of [100, 100]?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T09:48:52.327", "Id": "14038", "Score": "0", "body": "You are welcome. Yes, thus you could easier switch from one to another. BTW, if you like some post, except thanks there are upvotes and answer markings :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T10:06:30.517", "Id": "14039", "Score": "0", "body": "I know ;) Was a bit in a hurry and didn't think of upvoting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T10:36:49.817", "Id": "14041", "Score": "0", "body": "Of course, you can also make array [2] of arrays [100,100]. Choose what is more understandable. But if you make the desk as an object, that will have array and, for example, the number of generation, and/or other things, then Desk[2] array would be more natural" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-30T10:31:23.063", "Id": "136729", "Score": "0", "body": "The garbage collection problem will go away if you allocate two grids and 'double buffer' by reading from one to the other on each generation and then back the other way on the next. That is what @Gangnus is recommending at the end of his post." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T21:02:25.453", "Id": "8947", "ParentId": "8946", "Score": "5" } }, { "body": "<p>@Gangnus made some very good suggestions. But additionally, two ideas.</p>\n\n<ol>\n<li><p>Instead of having a grid of bool and calculate each cell, why not have an intermediate grid of int?</p></li>\n<li><p>Another improvement might be to harness the power of parallel processing: <a href=\"http://www.dotnetcurry.com/ShowArticle.aspx?ID=608\" rel=\"nofollow\">http://www.dotnetcurry.com/ShowArticle.aspx?ID=608</a><br>\nInstead of using regular for cycles, and since each iteration is independent from all other iterations, you can convert <code>for(int i=0; i&lt;10; i++) { ... }</code> into <code>Parallel.For(0, 10, i =&gt; { ... });</code>.</p></li>\n</ol>\n\n<p>This second one is more advanced than what you are looking for and specifically asked, but very interesting nevertheless. You can still disregard it and look into only the first one.</p>\n\n<p>So your <code>CheckAdjacent</code> method could be:</p>\n\n<pre><code>private bool[,] CheckAdjacent(bool[,] grid) {\n int[,] newGrid = new int[gridX, gridY];\n Parallel.For(0, gridX, x =&gt; {\n Parallel.For(0, gridY, y =&gt; {\n if(grid[x,y]) {\n IncrementNeighbours(newGrid, x ,y);\n }\n });\n });\n bool[,] newGridBools = new bool[gridX, gridY];\n Parallel.For(0, gridX, x =&gt; {\n Parallel.For(0, gridY, y =&gt; {\n newGridBools[x,y] = IsCellAlive(newGridBools[x,y], grid[x,y]);\n });\n });\n return newGridBools;\n}\n\n// @Gangnus' code fits perfectly. YOINK! &lt;3\n// This can probably be improved; but what for, if it works perfect?\nstatic readonly int [8] dx={1,1,0,-1,-1,-1,0,1};\nstatic readonly int [8] dy={0,-1,-1,-1,0,1,1,1};\nprivate void IncrementNeighbours( int[,] newGrid, int x, int y ) {\n for(i=0; i&lt;8; i++){\n x1=x+dx[i];\n y1=y+dy[i];\n if(x1&gt;=0 &amp; x1&lt;100 &amp; y1&gt;=0 &amp; y1&lt;100){\n neighbours[x1,y1]++;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:45:55.087", "Id": "14059", "Score": "0", "body": "I especially like the Parallel.For(). Have been looking for something similar before, but regular threading, or even GPGPU didn't work. This will probably be a large improvement in speed!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T17:56:56.820", "Id": "14061", "Score": "0", "body": "Unfortunately, Unity doesn't seem to support .NET 4.0 :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T09:14:29.387", "Id": "14099", "Score": "0", "body": "Thank you for the compliment. I haven't even supposed the possibility to use booleans :-). Use of integers was so obvious for me, that I haven't declared it explicitly. Of course, it should be done. --- What is \"YOINK <3\", please ? --- I thint your idea of parallel computing would be the best realised on the graphic cards for this task. Uhm. not for this, of course, but if the desk will be 10000x10000." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T09:29:24.147", "Id": "14100", "Score": "0", "body": "@SimonVerbeke not supported? Ah well. But this `Parallel.For` seems really useful; I just learned about here somewhere here on codereview too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T09:59:21.167", "Id": "14102", "Score": "0", "body": "@Gangnus `YOINK <3` is a \"[yoink](http://www.urbandictionary.com/define.php?term=yoink)\" and a heart. An attempt at showing appreciation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:45:11.133", "Id": "14121", "Score": "0", "body": "Even more bad luck, tried to thread my Start() function, but a specific function I use there is only allowed to be called from the main thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T10:21:02.117", "Id": "14183", "Score": "0", "body": "@SimonVerbeke ah well. But threading is not too important until you aim for very large boards, I think. Until then, changing the way that things are calculated ought to be enough to speed the process up - no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:58:37.643", "Id": "14202", "Score": "0", "body": "Indeed :) and the Start() function being slow is apparently caused by testing the game in the editor. When I build it and run it separately, it works like a charm :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:41:31.417", "Id": "8969", "ParentId": "8946", "Score": "4" } } ]
{ "AcceptedAnswerId": "8947", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T19:23:26.657", "Id": "8946", "Score": "5", "Tags": [ "c#", "performance", "game-of-life" ], "Title": "Garbage collection loop in Game of Life" }
8946
<p>I need to count non-transparent pixels in a canvas. I am pretty sure there is a nice and elegant syntax for doing this. Note that the data returned by <code>getImageData</code> is not a regular array and cannot be sliced, for example, or it does not have a <code>reduce</code> method.</p> <pre><code>data = context.getImageData(0, 0, canvas.width, canvas.height).data count = 0 i = 0 for x in data if (i + 1) % 4 == 0 &amp;&amp; x &gt; 0 count++ i++ </code></pre>
[]
[ { "body": "<p>What about this?! </p>\n\n<pre><code>data = context.getImageData(0, 0, canvas.width, canvas.height).data\ncount = 0\ncount++ for x, i in data when (i+1) % 4 is 0 and x &gt; 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:35:12.570", "Id": "8981", "ParentId": "8957", "Score": "4" } } ]
{ "AcceptedAnswerId": "8981", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T05:47:14.923", "Id": "8957", "Score": "0", "Tags": [ "beginner", "coffeescript" ], "Title": "Count non-transparent pixels in a canvas" }
8957
<p>This is a script I wrote to find the <em>n</em> biggest files in a given directory (recursively):</p> <pre><code>import heapq import os, os.path import sys import operator def file_sizes(directory): for path, _, filenames in os.walk(directory): for name in filenames: full_path = os.path.join(path, name) yield full_path, os.path.getsize(full_path) num_files, directory = sys.argv[1:] num_files = int(num_files) big_files = heapq.nlargest( num_files, file_sizes(directory), key=operator.itemgetter(1)) print(*("{}\t{:&gt;}".format(*b) for b in big_files)) </code></pre> <p>It can be run as, eg: <code>bigfiles.py 5 ~</code>. </p> <p>Ignoring the complete lack of error handling, is there any obvious way to make this clearer, or at least more succinct? I am thinking about, eg, using <code>namedtuple</code>s in <code>file_sizes</code>, but is there also any way to implement <code>file_sizes</code> in terms of a generator expression? (I'm thinking probably not without having two calls to <code>os.path</code>, but I'd love to be proven wrong :-)</p>
[]
[ { "body": "<p>You could replace your function with:</p>\n\n<pre><code>file_names = (os.path.join(path, name) for path, _, filenames in os.walk(directory)\n for name in filenames)\n\nfile_sizes = ((name, os.path.getsize(name)) for name in file_names)\n</code></pre>\n\n<p>However, I'm not sure that really helps the clarity.</p>\n\n<p>I found doing this:</p>\n\n<pre><code>big_files = heapq.nlargest(\n num_files, file_names, key=os.path.getsize)\nprint(*(\"{}\\t{:&gt;}\".format(b, os.path.getsize(b)) for b in big_files))\n</code></pre>\n\n<p>Actually runs slightly quicker then your version. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T02:47:46.840", "Id": "14088", "Score": "0", "body": "That's an interesting result. How did you time it? You wouldn't think that twice as many syscalls would speed it up!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T03:59:33.457", "Id": "14089", "Score": "0", "body": "@lvc, I used `time python script.py`. Its not making twice as many sys calls because I'm only making the second call for the top 5 or so files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T05:06:16.653", "Id": "14092", "Score": "0", "body": "Ah, indeed, it will only be `num_files` extra syscalls. Presumably, what's happening is that constructing multiple tuples is more expensive - if that's the case, we could expect the difference to shrink and eventually go away as `num_files` approaches the number of files searched. But, when I look at it, I think I do prefer `key=os.path.getsize` over my many tuples for clarity, anyway." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T19:49:58.823", "Id": "8973", "ParentId": "8958", "Score": "4" } } ]
{ "AcceptedAnswerId": "8973", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T05:54:29.153", "Id": "8958", "Score": "6", "Tags": [ "python" ], "Title": "n largest files in a directory" }
8958
<p>This is my first 'large' JS project and I was hoping someone could have a quick look and suggest better coding practices, how it could be cleaner etc. It revolves around a one page web-site and contains some AJAX. </p> <pre><code> $(document).ready(function () { var curpoints; //int globals var sectionloaded = 'about'; var History = window.History; var vph = window.innerHeight; var vpw = window.innerWidth; //setup size $('#master').css('height', vph * 2); $('section').css('height', vph); $('#brief').addClass('inview'); //check url var urlquery = "&lt;?php echo $query; ?&gt;"; if (urlquery == "portfolio") { navi('portfolio', 200); } else if (urlquery == "resume") { navi('resume', 200); }; //prevent nav a s $('header a').click(function (e) { e.preventDefault(); }); $('article a').click(function (e) { e.preventDefault(); }); //resize $(window).resize(function () { vph = window.innerHeight; $('section').css('height', vph); $('body').css('height', vph); $('#master').css('height', vph * 2); if ($('#skills').hasClass('inview')) { $('#master').css('margin-top', -vph); }; }); //article container stuff $('#entrycontainer article').click(function () { curid = $(this).data('url'); navi('portfolio', 1000); }) $('body').mousedown(function (e) { if (e.button == 1) return false }); //NAV SECTION ///////////////// //Buttons $('#port').click(function () { navi('portfolio', 1000); }); $('#resu').click(function () { navi('resume', 1000); }); $('#firstli').click(function () { navi('about', 1000); }); $('#conatctbut').click(function () { navi('contact', 1000); }); ///////// //Back/Forward buttons ///////// window.addEventListener("popstate", function (e) { curstate = window.location.href; curstatereg = curstate.substring(7); var splituri = curstatereg.split('/'); var reg = /^mydomain\.com\/portfolio\/.*/; if (reg.test(curstatereg)) { $.get('../ajax1.php?page=' + splituri[2], function (data) { curid = data; navi('portfolio', 200); }); }; switch (curstate) { case 'http://mydomain.com/': navi('about', 200); break; case 'http://mydomain.com/resume': navi('resume', 200); break; case 'http://mydomain.com/contact': navi('contact', 200); break; }; }); function navi(pagetoload, speed) { if (pagetoload == 'about') { if (sectionloaded == 'about') { return } else { $('#master').stop(); $('#master').animate({ marginTop: 0 }, 1000); sectionloaded = pagetoload; History.pushState(null, pagetoload, '/'); } } else { if (sectionloaded == pagetoload) { $.getJSON('../ajax.php?id=' + curid, function (data) { if (data.tags == null) { return } else { tags = data.tags.split(','); taglen = tags.length; }; $('#tags').children('li').remove(); $("#portcontainer").fadeOut(300, function () { $('#textcontainer h1').html(data.title); $('#textcontainer p').html(data.body); $('#textcontainer a').attr('target', '_blank'); $('#textcontainer a').attr('href', '../live/' + data.points); $('#portbox img').attr('src', '../' + data.img); $('#tags').children('li').remove(); for (i = 0; i &lt; taglen; i++) { $('#tags').append("&lt;li&gt;" + tags[i] + "&lt;/li&gt;"); } }); $("#portcontainer").fadeIn(300); History.pushState(null, data.title, '/portfolio/' + data.points); curid = data.id; curpoints = data.points; }); } else if (sectionloaded == 'about') { $.get('../content.php?which=' + pagetoload, function (data) { $('#container').html(data); if (pagetoload == 'portfolio') { intport(); } else { History.pushState(null, data.title, '/' + pagetoload); }; $('#master').stop(); $('#master').animate({ marginTop: -vph }, speed); var link = $("&lt;link&gt;"); $('#dynamic').attr('href', '../' + pagetoload + '.css'); sectionloaded = pagetoload; }) } else { $.get('../content.php?which=' + pagetoload, function (data) { $('#container').fadeOut(500, function () { $('#container').html(data); if (pagetoload == 'portfolio') { intport(); } else { History.pushState(null, data.title, '/' + pagetoload); }; $('#dynamic').attr('href', '../' + pagetoload + '.css'); }); sectionloaded = pagetoload; $('#container').fadeIn(); }); }; }; }; // /////////////// //AJAX STUFF FOR PORTFOLIO ////////////// &lt;? php if (isset($portfolio)) { $data1 = mysql_query("SELECT ind FROM project WHERE points ='".$portfolio."'") or die(mysql_error()); $info1 = mysql_fetch_array($data1); echo 'var curid = '.$info1[ind].';'; echo "navi('portfolio',300);"; } else { echo 'var curid = 0;'; } ?&gt; function intport() { var rows; $.getJSON('../ajax.php?id=' + curid, function (data) { tags = data.tags.split(','); taglen = tags.length; rows = data.rows; $('#tags').children('li').remove(); $('#textcontainer h1').html(data.title); $('#textcontainer a').attr('href', '../live/' + data.points); $('#textcontainer a').attr('target', '_blank'); $('#textcontainer p').html(data.body); $('#portbox img').attr('src', '../' + data.img); $('#tags').children('li').remove(); for (i = 0; i &lt; taglen; i++) { $('#tags').append("&lt;li&gt;" + tags[i] + "&lt;/li&gt;"); } History.pushState(null, data.title, '/portfolio/' + data.points); curpoints = data.points; curid = data.id; }); $('#buttonr').click(function () { if (curid == rows - 1) { curid = 0; ajaxproj(); } else { curid++; ajaxproj(); } }); $('#buttonl').click(function () { if (curid == 0) { curid = rows - 1; ajaxproj(); } else { curid--; ajaxproj(); } }); function ajaxproj() { $.getJSON('../ajax.php?id=' + curid, function (data) { if (data.tags == null) { return } else { tags = data.tags.split(','); taglen = tags.length; }; $('#tags').children('li').remove(); $("#portcontainer").fadeOut(300, function () { $('#textcontainer h1').html(data.title); $('#textcontainer p').html(data.body); $('#textcontainer a').attr('target', '_blank'); $('#textcontainer a').attr('href', '../live/' + data.points); $('#portbox img').attr('src', '../' + data.img); $('#tags').children('li').remove(); for (i = 0; i &lt; taglen; i++) { $('#tags').append("&lt;li&gt;" + tags[i] + "&lt;/li&gt;"); } }); $("#portcontainer").fadeIn(300); History.pushState(null, data.title, '/portfolio/' + data.points); curid = data.id; curpoints = data.points; }); } }; }); </code></pre>
[]
[ { "body": "<p>Giving your code a quick look does not make me understand a single line.\nWill you understand it if you go away for two weeks?</p>\n\n<p>Giving it a second look, I notice you've added some short comments describing each block.\nThat tells me each block is an excellent candidate for its own function.</p>\n\n<p>Notice in the following example how the function given to $(document).ready() now reads like a small story instead of a lot of detailed jquery instructions.</p>\n\n<pre><code>(function() {\n\n var sectionLoaded;\n var history;\n var windowWidth, windowHeight;\n\n $(document).ready(function() {\n initializeGlobals();\n setupSize();\n checkUrl();\n // ...\n });\n\n function initializeGlobals() {\n sectionloaded = 'about'; \n history = window.history; \n windowHeight = window.innerHeight; \n windowWidth = window.innerWidth; \n }\n\n function setupSize() {\n $('#master').css('height', vph * 2); \n $('section').css('height', vph); \n $('#brief').addClass('inview'); \n }\n\n function checkUrl() {\n var urlquery = \"&lt;?php echo $query; ?&gt;\"; \n if (urlquery == \"portfolio\") { \n navi('portfolio', 200); \n } else if (urlquery == \"resume\") { \n navi('resume', 200); \n };\n\n})();\n</code></pre>\n\n<p>Secondly, check url does not tell me anything. Why check the url? And inside that, some function called navi is called. What's navi? I'm guessing navigate, but then why isn't it called navigate?</p>\n\n<p>Same goes for vph and vpw - what does vp stand for? Why not call them windowWidth and windowHeight?</p>\n\n<p>I'm also quite unsure what buttonr and button1 does.</p>\n\n<p>Guess you get my point by now. :)\nFunction names should scream out what they do. If they do, you don't need comments.</p>\n\n<p>You should also look into <a href=\"https://stackoverflow.com/questions/111102/how-do-javascript-closures-work\">closures</a> to have your globals scoped for this functionality instead of \"polluting\" the global namespace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T10:36:29.173", "Id": "14040", "Score": "0", "body": "Thanks Lars , some really sensible suggestions there . I shall implement them ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T11:34:32.667", "Id": "14043", "Score": "0", "body": ":) feel free to vote up or tag as answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T14:57:46.830", "Id": "14054", "Score": "0", "body": "Everything works great apart from the initializeGlobals function. If I try to invoke the function inside or out of the document ready it doesn't work. I Have to declare them outside the doc ready ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:24:01.510", "Id": "14056", "Score": "0", "body": "@Lars-Erik +1 excellent answer!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:24:08.763", "Id": "14057", "Score": "0", "body": "@FrankAstin initializeGlobals() must be outside of $(function(){ }) part, otherwise it cannot be accessed outside of the document ready scope" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:14:04.700", "Id": "14111", "Score": "0", "body": "@FrankAstin Look up javascript closures and scope on google. It's nice to keep common functionality in a closure, but you need to understand the scope things get when you do. You can access $(document).ready from inside a closure, but unless you return something from the closure, you can't access it outside." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:35:36.907", "Id": "14116", "Score": "0", "body": "@Lars-Erik Got ya , I missed that you declared them outside both the doc.ready and init.globals scope ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T23:03:17.757", "Id": "14156", "Score": "0", "body": "@FrankAstin I updated the sample with a closure around it. All it does is to declare a function within parenthesis and then call it. (The last ();)\nThis means anything outside the closure cannot access it, so you can make another set of functions with their own sectionLoaded global for instance. (Then it would not actually be global, but anyway. :) )" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T09:51:53.647", "Id": "8960", "ParentId": "8959", "Score": "6" } } ]
{ "AcceptedAnswerId": "8960", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T09:11:29.967", "Id": "8959", "Score": "2", "Tags": [ "javascript", "php", "jquery", "ajax" ], "Title": "Single-page personal portfolio site with AJAX navigation" }
8959
<p>I build a collection to ensure only valid entities in an array so I don't have to validate after every function / method call as I could rely on the collection to have only valid entities stored. </p> <pre><code>class WorldCollection implements Collection, ArrayAccess { private $container = array(); private $oValidator; public function __construct (Validator $oWorldValidator) { $this-&gt;oValidator = $oWorldValidator; } public function offsetExists ($offset) { return isset($this-&gt;container[$offset]); } public function offsetGet ($offset) { return isset($this-&gt;container[$offset]) ? $this-&gt;container[$offset] : null; } /** * READ ME */ public function offsetSet ($offset, $value) { $this-&gt;oValidator-&gt;validate($value) if (is_null ($offset)) { $this-&gt;container[] = $value; } else { $this-&gt;container[$offset] = $value; } } public function offsetUnset ($offset) { unset($this-&gt;container[$offset]); } } </code></pre> <p>As I want to separate concerns and follow dependency injection I inject the <code>Validator</code> in the constructor of the collection and validate in the <code>ofsetSet</code> method to ensure only valid values will be stored. </p> <pre><code>class WorldValidator implements Validator { public function validate($aWorld) { if (!is_array($aWorld)) { throw new WorldValidationException('invalid type', WorldValidationException::ERROR_CODE_INVALID_TYPE); } return true; } } </code></pre> <p>(The validator is simplified for example purpose.) </p> <ol> <li>Did I seperate it right? Or should I handle this kind of validation differently?</li> <li>Should I catch the validation exception to not disturb the program flow? If so should I store the exception and offer a <code>getErrors</code> method?</li> <li>Should I rename the collection <code>ValidWorldCollection</code> and extend from <code>WorldCollection</code>? </li> <li>Should the <code>InvalidWorldException</code> extend <code>RuntimeException</code> or <code>LogicException</code>? Same for <code>WorldValidationException</code> in the validator</li> <li>Should I create a World Class and exclude the <code>Validation</code> from the <code>Collection</code> using <code>instanceof</code> ?</li> <li>Should I have used a more appropriate Spl DataStructure? (SplObjectStorage?) Or is it all a waste of time?</li> </ol>
[]
[ { "body": "<h2>Design</h2>\n\n<p>Dependency injection is very useful when you have multiple implementations of a given dependency. If you don't plan implementing another <code>Validator</code>, then it's probably premature abstraction. I'll assume here that you have other <code>Validator</code> implementations.</p>\n\n<p>Let me answer your questions:</p>\n\n<ol>\n<li>The separation itself is good.</li>\n<li><p>An exception is meant to be catched \"whenever possible\", and it is not possible in <code>WorldCollection</code>, since you don't know how to handle it. You need to wonder what you want your application to do when the data does not validate.</p>\n\n<p>If you want <code>WorldCollection::offsetSet</code> to not do anything when the validation fails, then <code>WorldValidator::validate</code> should simply return true or false, and no exception should be thrown.</p>\n\n<p>If the exception is to be catched later on in the code, then don't do anything in <code>WorldCollection::offsetSet</code>, since another code will take care of the issue.</p>\n\n<p>You can easily mix those two approaches in order to catch some of the exception at some point, and other ones later on (which means <code>WorldValidator::validate</code> should always throw an exception, and return nothing).</p></li>\n<li><p>Only if you plan on having other <code>WorldCollection</code>s. I don't think so.</p></li>\n<li><code>LogicException</code> should only be launched if there is a flow in your program, ie. an exception that would never be thrown in a perfect program. <code>RuntimeException</code> is a base class used for errors such as OutOfBounds or Overflow. I'd use <a href=\"http://www.php.net/manual/en/class.invalidargumentexception.php\" rel=\"nofollow\">InvalidArgumentException</a>.</li>\n<li>I didn't understand the question. Note that <code>instanceof</code> is never good design, and exists to work around design errors.</li>\n<li>ArrayAccess is a reasonable choice, it lets you do foreach on your data easily, whereas with <code>Iterator</code> you would have to implement a ton of methods. <code>SplObjectStorage</code> could be used, but only if you don't need the keys <code>ArrayAccess</code> provides.</li>\n</ol>\n\n<h2>Implementation</h2>\n\n<ol>\n<li>Do you want only one exception with different types, such as <code>ERROR_CODE_INVALID_TYPE</code>?\n<ol>\n<li>Why don't you use multiple exceptions?</li>\n<li>If you want to stick with one exception, don't pass \"invalid type\" in the constructor, since it is always going to be the same message. Prefer to override <code>Exception::__toString()</code> to return \"invalid type\" when the type is <code>ERROR_CODE_INVALID_TYPE</code>.</li>\n</ol></li>\n<li>Use offsetExists in offsetGet instead of repeating yourself?</li>\n<li>Consider using <a href=\"http://ca3.php.net/manual/en/language.types.null.php\" rel=\"nofollow\"><code>NULL</code></a> instead of null, and <code>TRUE</code> instead of true, even if they are case-insensitive.</li>\n<li><code>$this-&gt;oValidator-&gt;validate($value)</code> forgot a semicolon?</li>\n<li>Don't use return if you're not going to check the return value.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T07:22:19.723", "Id": "16911", "Score": "0", "body": "**Implementation**\n4. i am with you, most of the class is just copy and paste from http://de3.php.net/manual/en/class.arrayaccess.php as is offsetExists \n\n3. thanks for the advice but i will not discuss coding convention in this topic\n\n4. true\n\n5. well there is always a return , if not a custom one then the return null \n\n**Design**\n5. the point was to limit the the collection by type \"world\" and to exclude validation from the collection (as it only accepts instance of \"World\") and let the \"World\" class handle this kind of stuff \n\nthx for everything!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T13:32:34.077", "Id": "9717", "ParentId": "8962", "Score": "1" } } ]
{ "AcceptedAnswerId": "9717", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T13:21:48.403", "Id": "8962", "Score": "4", "Tags": [ "php", "design-patterns", "collections" ], "Title": "Entity collection best practice (separation of concerns, dependency injection, ...)" }
8962
<p>I wrote code in python that works slow. Because I am new to python, I am not sure that I am doing everything right. My question is what I can do optimally? About the problem: I have 25 *.json files, each is about 80 MB. Each file just contain json strings. I need make some histogram based on data.</p> <p>In this part I want create list of all dictionaries ( one dictionary represent json object):</p> <pre><code>d = [] # filename is list of name of files for x in filename: d.extend(map(json.loads, open(x))) </code></pre> <p>then I want to create list <code>u</code> :</p> <pre><code>u = [] for x in d: s = x['key_1'] # s is sting which I use to get useful value t1 = 60*int(s[11:13]) + int(s[14:16])# t1 is useful value u.append(t1) </code></pre> <p>Now I am creating histogram:</p> <pre><code>plt.hist(u, bins = (max(u) - min(u))) plt.show() </code></pre> <p>Any thought and suggestions are appreciated. Thank you!</p>
[]
[ { "body": "<p>Python uses a surprisingly large amount of memory when reading files, often 3-4 times the actual file size. You never close each file after you open it, so all of that memory is still in use later in the program.</p>\n\n<p>Try changing the flow of your program to</p>\n\n<ol>\n<li>Open a file</li>\n<li>Compute a histogram for that file</li>\n<li>Close the file</li>\n<li>Merge it with a \"global\" histogram</li>\n<li>Repeat until there are no files left.</li>\n</ol>\n\n<p>Something like</p>\n\n<pre><code>u = []\nfor f in filenames:\n with open(f) as file:\n # process individual file contents\n contents = file.read()\n data = json.loads(contents)\n for obj in data:\n s = obj['key_1']\n t1 = 60 * int(s[11:13]) + int(s[14:16])\n u.append(t1)\n\n# make the global histogram\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n\n<p><code>with open as</code> automatically closes files when you're done, and handles cases where the file can't be read or there are other errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:11:06.000", "Id": "8964", "ParentId": "8963", "Score": "7" } }, { "body": "<p>I'd use this, as it avoids loading and keeping all of json data in memory:</p>\n\n<pre><code>u = []\nfor name in filename:\n d = json.load(open(name,\"r\"))\n for x in d:\n s = x['key_1']\n t1 = 60*int(s[11:13]) + int(s[14:16])\n u.append(t1)\n d = None\n\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:15:43.763", "Id": "14044", "Score": "0", "body": "Don't you want `json.load(open(name, \"r\"))` instead of `loads` since the latter takes a string as its argument?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:17:24.320", "Id": "14045", "Score": "0", "body": "@srgerg Yup. :/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:11:48.603", "Id": "8965", "ParentId": "8963", "Score": "1" } }, { "body": "<p>You might be able to save some run time by using a couple of <a href=\"http://docs.python.org/reference/expressions.html#generator-expressions\" rel=\"nofollow\">generator expressions</a> and a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>. For example:</p>\n\n<pre><code>def read_json_file(name):\n with open(name, \"r\") as f:\n return json.load(f)\n\ndef compute(s):\n return 60 * int(s[11:13]) + int(s[14:16])\n\nd = (read_json_file(n) for n in filename)\nu = list(compute(x['key_1']) for x in d)\n\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n\n<p>This should save on memory, since anything that isn't needed is discarded.</p>\n\n<p><strong>Edit:</strong> it's difficult to discern from the information available, but I think the OP's json files contain multiple json objects, so calling <code>json.load(f)</code> won't work. If that is the case, then this code should fix the problem</p>\n\n<pre><code>def read_json_file(name):\n \"Return an iterable of objects loaded from the json file 'name'\"\n with open(name, \"r\") as f:\n for s in f:\n yield json.loads(s)\n\ndef compute(s):\n return 60 * int(s[11:13]) + int(s[14:16])\n\n# d is a generator yielding an iterable at each iteration\nd = (read_json_file(n) for n in filename)\n\n# j is the flattened version of d\nj = (obj for iterable in d for obj in iterable)\n\nu = list(compute(x['key_1']) for x in j)\n\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:05:43.503", "Id": "14046", "Score": "0", "body": "your code gives error : ValueError: Extra data: line 2 column 1 - line 131944 column 1 (char 907 - 96281070)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:16:39.913", "Id": "14047", "Score": "0", "body": "I created a couple of test json files and ran this code in Python 2.7 and it worked fine for me. The error appears to be in reading the json file, but without seeing your actual code and the content of your json files, its very difficult for me to diagnose the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:24:55.803", "Id": "14048", "Score": "0", "body": "2srgerg it returns error from read_json_file function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:26:12.747", "Id": "14049", "Score": "0", "body": "here my code: def read_json_file(name):\n with open(name,'r') as f:\n return json.loads(f.read())\n \ndef compute_time(s):\n return 60 * int(s[11:13]) + int(s[14:16]) \n\nd = (read_json_file(n) for n in filename)\nu = list(map(compute_time, (x['time'] for x in d)))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:30:31.487", "Id": "14050", "Score": "0", "body": "I've edited my answer with what I *think* might solve the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:45:12.457", "Id": "14051", "Score": "0", "body": "could you explain this line please: j = (obj for iterable in d for obj in iterable) I think it should be just j = (obj for iterable in d)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:50:56.750", "Id": "14052", "Score": "0", "body": "The new `read_json_file(...)` function returns a list of objects loaded from the json file. That means that each element of `d` will be a list of objects, not a single object. To get an iterable of single objects we need to flatten `d` and that is what the line of code does. See [this other stack overflow question](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) for more detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T08:32:17.683", "Id": "14053", "Score": "1", "body": "There is a great piece about generators and doing this exact kind of work available here - http://www.dabeaz.com/generators/" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:30:36.957", "Id": "8966", "ParentId": "8963", "Score": "3" } } ]
{ "AcceptedAnswerId": "8966", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T03:51:37.250", "Id": "8963", "Score": "6", "Tags": [ "python", "json" ], "Title": "python: is my program optimal" }
8963
<p>I'm using manually implemented properties to handle sharing code between forms intended to edit a base object, and those intended to edit a derived version. My current setup works as long as everyone accesses the property and not the base object; but after spending an hour or so tracking down a bug that was due to manipulating <code>_editDataObject</code> in <code>DataObjectEditForm</code> in an application using <code>DataObjectEx</code> and <code>DataObjectExEditForm</code> I'm wondering if there's a way to enforce this more strongly than just adding a do not use comment on _editDataObject.</p> <p>For contractual reasons the simple option of creating a single form that is aware of both <code>DataObject</code> and <code>DataObjectEx</code> isn't permissible.</p> <pre><code>public class DataObject { //data members go here } public class DataObjectEx : DataObject { public DataObjectEx(DataObject dataObject) { //create DataObjectEx containing all of dataObject's state. } //additional data members go here } public class DataOjectEditForm : Form { ///&lt;Summary&gt; ///Do not use. Will break app if EditDataObject property is overridden. ///&lt;/Summary&gt; private _editDataObject; protected virtual EditDataObject { get { return _editDataObject; } set { _editDataObject = value; } } //Do stuff only dependent on DataObject } public class DataOjectExEditForm : DataObjectEditForm { private _editDataObjectEx; protected override EditDataObject { get { return _editDataObjectEx; } set { if (value == null) _editDataObjectEx = null; else _editDataObjectEx = value as DataObjectEx ?? new DataObjectEx(value); } } //Add stuff dependent on the additions in DataObjectEx } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:37:48.693", "Id": "14058", "Score": "0", "body": "Am I overlooking a tag that would be appropriate for inheritance problems?" } ]
[ { "body": "<p>Judging from the code you provided, the program is behaving as if you are using the new keyword. This causes your property to behave differently based upon whether your form is used in the context of type DataObjectEditForm versus type DataObjectExEditForm.</p>\n\n<p>To clarify:</p>\n\n<pre><code>var form = new DataObjectExEditForm ();\nform.EditDataObject = new DataObjectEx ();\n\nDataObjectEditForm baseForm = form;\nvar data = baseForm.EditDataObject; // data = null!?!\n</code></pre>\n\n<p>From the looks of it, you should instead be using virtual/override on your property. </p>\n\n<pre><code>public class DataOjectEditForm : Form\n{\n protected DataObject _editDataObject;\n\n protected virtual DataObject EditDataObject\n { \n get { return _editDataObject; }\n set { _editDataObject = value; }\n }\n\n //Do stuff only dependent on DataObject \n}\n\n\npublic class DataOjectExEditForm : DataObjectEditForm\n{\n protected override DataObject EditDataObject\n { \n get { return _editDataObject; }\n set \n {\n if (value == null)\n _editDataObject = null;\n else _editDataObject = value as DataObjectEx ?? new DataObjectEx(value);\n }\n }\n\n //Add stuff dependent on the additions in DataObjectEx\n}\n</code></pre>\n\n<p>Of course, that is only going to guarantee that the backing field used by the form is consistent. If the bug is the result of _editDataObject being used in some contexts while _editDataObjectEx was used in other contexts, then this will solve your issue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T18:26:19.527", "Id": "14062", "Score": "0", "body": "You're right about the virtual/override semantics. Not putting them in my example code was an oversight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T18:29:17.977", "Id": "14063", "Score": "0", "body": "I thought I tried using a single backing DataObject before but ran into problems somewhere. I'm don't recall the specifics and am trying to see if I can find what it was again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T18:13:42.613", "Id": "8971", "ParentId": "8968", "Score": "3" } } ]
{ "AcceptedAnswerId": "8971", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T16:36:36.947", "Id": "8968", "Score": "1", "Tags": [ "c#" ], "Title": "Change type of property in derived class" }
8968
<p>I've stripped this down to its bare bones removing stopping/cancellation logic etc... to keep it simple.</p> <p>The <code>Producer</code> is a very simple class containing a timer. At regular intervals the <code>TimerOnElapsed</code> will let the host now that it has another batch of items available. The onus is on the host to pull that next batch using <code>GetNextBatch()</code>.</p> <pre><code>public class Producer { public event EventHandler BatchAvailable; private readonly Timer timer; private int i; public Producer() { i = 1; timer = new Timer(5000); timer.Elapsed += TimerOnElapsed; } public void Start() { timer.Enabled = true; timer.Start(); } private void TimerOnElapsed(object sender, ElapsedEventArgs e) { if (BatchAvailable != null) BatchAvailable(sender , e); } public IEnumerable&lt;int&gt; GetNextBatch() { var range = Enumerable.Range(i, i + 50).ToList(); i = i + 50; return range; } } </code></pre> <p>The <code>Consumer</code> class uses a <code>Concurrent.BlockingCollection&lt;T&gt;</code> to pass objects to a Parallel <code>ForEach</code> loop. The <code>Consumer</code> is <strong>READY</strong> for the next batch each time it empties the blocking collection of the existing batch.</p> <pre><code>public class Consumer { private TaskFactory _factory; private readonly BlockingCollection&lt;int&gt; _entries; public Consumer() { _entries = new BlockingCollection&lt;int&gt;(); } public void Start() { _factory = new TaskFactory(); try { _factory.StartNew(() =&gt; { Parallel.ForEach( _entries.GetConsumingEnumerable(), new ParallelOptions() { MaxDegreeOfParallelism = 5 }, ProcessEntry ); }); } catch (OperationCanceledException oce) { } } public void Add(int entry) { _entries.Add(entry); } public bool Ready { get { return (_entries.Count == 0); } } private void ProcessEntry(int entry) { Console.WriteLine("Processing {0}", entry); Thread.Sleep(3000); } } </code></pre> <p>The <code>Host</code> is a class containing each of the above. It orchestrates communication between the two. Each time the <code>Producer</code> says it has another batch available, the host checks to see if the <code>Consumer</code> is ready, and if so, retrieves the batch and passes it on.</p> <pre><code>public class Host { private Producer _producer; private Consumer _consumer; public Host() { _producer = new Producer(); _producer.BatchAvailable += (s,e) =&gt; ProducerOnBatchAvailable(); _consumer = new Consumer(); } public void Start() { _producer.Start(); _consumer.Start(); } private void ProducerOnBatchAvailable() { if (!_consumer.Ready) return; Console.WriteLine("Producer is ready for another Batch..."); var batch = _producer.GetNextBatch().ToList(); batch.ForEach(_consumer.Add); } } </code></pre> <p>I've tested this a couple of times and it behaves as I'd expect. The throttling of batch sizes and the max parallelism in the P-<code>ForEach</code> loop also works. And in my larger example I have a number of other <code>Players</code> that hand entry along to the next step in the pipeline by way of more events and blocking collections.</p> <p>However, I'm a bit irked by the fact that I never need to call the <code>BlockCollection&lt;T&gt;.CompletedAdding()</code>. Is this bad practice? Do I have any potential problems leaving the blocking collection in the WAIT state for long periods of time?</p> <p>In the real example the producer will be querying a DB queue which could potentially have no work in it, so the <code>BlockingCollection</code> could sit there for hours overnight.</p>
[]
[ { "body": "<p>As a matter of being thread-safe, you should replace this:</p>\n\n<pre><code> private void TimerOnElapsed(object sender, ElapsedEventArgs e)\n {\n if (BatchAvailable != null)\n BatchAvailable(sender , e);\n }\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code> private void TimerOnElapsed(object sender, ElapsedEventArgs e)\n {\n var batchAvailable = this.BatchAvailable;\n\n if (batchAvailable != null)\n {\n batchAvailable(sender, e);\n }\n }\n</code></pre>\n\n<p>Reason being, accessing the event field \"raw\", you may wind up with it going <code>null</code> between the <code>if</code> and the invocation itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T20:25:13.947", "Id": "8975", "ParentId": "8972", "Score": "4" } }, { "body": "<p>I have never added a second answer before, but I feel it's somewhat different from the other one and a bit more complete to address your questions. I've added <code>Stop()</code> methods and process those as such in the both the producer, consumer and host as such:</p>\n\n<p>Producer:</p>\n\n<pre><code>public sealed class Producer : IDisposable\n{\n private readonly Timer timer = new Timer(5000);\n\n private int i = 1;\n\n private bool disposed;\n\n public event EventHandler BatchAvailable;\n\n public void Start()\n {\n this.timer.Elapsed += this.TimerOnElapsed;\n this.timer.Start();\n }\n\n public void Stop()\n {\n this.timer.Stop();\n this.timer.Elapsed -= this.TimerOnElapsed;\n }\n\n public void Dispose()\n {\n if (this.disposed)\n {\n return;\n }\n\n this.Stop();\n this.timer.Dispose();\n this.disposed = true;\n }\n\n public IEnumerable&lt;int&gt; GetNextBatch()\n {\n var range = Enumerable.Range(this.i, this.i + 50);\n\n this.i += 50;\n return range;\n }\n\n private void TimerOnElapsed(object sender, ElapsedEventArgs e)\n {\n var batchAvailable = this.BatchAvailable;\n\n if (batchAvailable != null)\n {\n batchAvailable(sender, e);\n }\n }\n}\n</code></pre>\n\n<p>Consumer:</p>\n\n<pre><code>public sealed class Consumer : IDisposable\n{\n private readonly BlockingCollection&lt;int&gt; entries = new BlockingCollection&lt;int&gt;();\n\n private readonly TaskFactory factory = new TaskFactory();\n\n private CancellationTokenSource tokenSource;\n\n private Task task;\n\n public void Start()\n {\n try\n {\n this.tokenSource = new CancellationTokenSource();\n this.task = this.factory.StartNew(\n () =&gt;\n {\n Parallel.ForEach(\n this.entries.GetConsumingEnumerable(),\n new ParallelOptions { MaxDegreeOfParallelism = 5, CancellationToken = tokenSource.Token },\n (i, loopState) =&gt;\n {\n if (!this.tokenSource.IsCancellationRequested)\n {\n ProcessEntry(i);\n }\n else\n {\n this.entries.CompleteAdding();\n loopState.Stop();\n }\n });\n },\n this.tokenSource.Token);\n }\n catch (OperationCanceledException oce)\n {\n System.Diagnostics.Debug.WriteLine(oce);\n }\n }\n\n public void Stop()\n {\n this.Dispose();\n }\n\n public void Add(int entry)\n {\n this.entries.Add(entry);\n }\n\n public void Dispose()\n {\n if (this.task == null)\n {\n return;\n }\n\n this.tokenSource.Cancel();\n while (!this.task.IsCanceled)\n {\n }\n\n this.task.Dispose();\n this.tokenSource.Dispose();\n this.task = null;\n }\n\n public bool Ready\n {\n get\n {\n return this.entries.Count == 0;\n }\n }\n\n private static void ProcessEntry(int entry)\n {\n Console.WriteLine(\"Processing {0}\", entry);\n Thread.Sleep(3000);\n }\n}\n</code></pre>\n\n<p>and Host:</p>\n\n<pre><code>public sealed class Host : IDisposable\n{\n private readonly Producer producer = new Producer();\n\n private readonly Consumer consumer = new Consumer();\n\n private bool disposed;\n\n public Host()\n {\n this.producer.BatchAvailable += (s, e) =&gt; this.ProducerOnBatchAvailable();\n }\n\n public void Start()\n {\n this.producer.Start();\n this.consumer.Start();\n }\n\n public void Stop()\n {\n this.producer.Stop();\n this.consumer.Stop();\n }\n\n public void Dispose()\n {\n if (this.disposed)\n {\n return;\n }\n\n this.Stop();\n this.producer.Dispose();\n this.consumer.Dispose();\n this.disposed = true;\n }\n\n private void ProducerOnBatchAvailable()\n {\n if (!this.consumer.Ready)\n {\n return;\n }\n\n Console.WriteLine(\"Producer is ready for another Batch...\");\n\n var batch = this.producer.GetNextBatch().ToList();\n\n batch.ForEach(this.consumer.Add);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T08:04:16.220", "Id": "14098", "Score": "0", "body": "This is incredibly similar to the full version I have. Like i said in the original post, I stripped out a lot of the stop, disposal & task cancellation code for brevity...\n\nHowever I see you didn't make any modification to the `BlockCollection<T>` population or enumeration. And that you haven't included any reference to the CompletedAdding Method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T13:30:52.400", "Id": "14106", "Score": "0", "body": "Read closer - there is indeed a reference to `CompleteAdding` in the main loop of the producer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T13:39:11.020", "Id": "14108", "Score": "0", "body": "aah... I see what you've done there... ok thanks. I'll go and integrate that change and do some more testing. Appreciate the feedback. Cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:39:14.487", "Id": "14113", "Score": "0", "body": "@EoinCampbell best of luck with it!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T21:21:57.353", "Id": "8976", "ParentId": "8972", "Score": "2" } } ]
{ "AcceptedAnswerId": "8976", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T18:25:43.170", "Id": "8972", "Score": "6", "Tags": [ "c#", "task-parallel-library", "producer-consumer" ], "Title": "Producer / Consumer implementation for Parallel Processing in the TPL" }
8972
<h2>The problem</h2> <hr /> <p>I'm trying to position a chosen element so that it's always horizontally aligned against the right-hand side of the page, and vertically aligned with the center of the web browser's vertical inner scrollbar, i.e. the part of the scrollbar that moves as you scroll up and down the page. The &quot;handlebar&quot;, if you will.</p> <p>I've been tweaking this code for so long that it's starting to do my head in, so would like a sanity check, i.e. am I going about this the right way?</p> <p>The key part of this function is the line beginning <code>offset = scroll_position ...</code></p> <h2>The code</h2> <pre><code>barFollower = function (e) { var target = $(e.data.target), scrollbar_button_height = 20, window_height = $(window).height(), window_height_adj = window_height - (scrollbar_button_height * 2), scroll_position = $(window).scrollTop(), body_height = $('body').height(), offset = scroll_position // The top of window + ((scroll_position / body_height) * window_height_adj) // The position of the top of scrollbar + (((window_height_adj / body_height) * window_height_adj) / 2) // Half the height of the scrollbar + scrollbar_button_height // The scrollbar button height (depends on browser chrome, unfortunately) - see notes below - element_offset; // offset for chosen 'position' based on element height - see notes below /* Some catches for when element height might mean it would get positioned outside the window */ if (body_height &lt; window_height) { // If there's no scrollbar. offset = (window_height / 2) + (target.height() / 2); // Position halfway down the window } else if (offset &lt; scroll_position) { // Top bounds offset = scroll_position; // Fix it to the top of the window } else if (offset &gt; scroll_position + window_height - target.height()) { // Bottom bounds offset = scroll_position + window_height - target.height(); // Fix it to the bottom of the window } target.css('top', offset); }; </code></pre> <h2>Notes</h2> <p><strong>Triggering</strong></p> <p>This function is triggered once on page load, and subsequently on every window scroll event.</p> <p><strong>Scrollbar button size</strong></p> <p>The tricky part here is that I can't find a way to determine the height of the scrollbar 'up' and 'down' buttons, so I have made an assumption (20px), although this will potentially vary from browser to browser, and depends the browser chrome. If anyone knows a way to accurately determine scrollbar button sizes, please let me know.</p> <p><strong>The <code>element_offset</code> variable</strong></p> <p>The <code>element_offset</code> is set outside this function, and can have one of three values to offset the element so that either the top, middle, or bottom of the element align with the middle of the vertical scrollbar. How it is set is not relevant at this point, so I've left it out to keep things simple.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T05:44:35.857", "Id": "14095", "Score": "0", "body": "Is this a typo: `settings.scrollbar_button_height` vs. just `scrollbar_button_height`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T19:55:52.773", "Id": "14209", "Score": "0", "body": "@PaulMartel: Yes - sorry - I've fixed it now!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T02:07:05.923", "Id": "14236", "Score": "0", "body": "Is there css something like `#myelement { position: fixed; right: 0;}`?" } ]
[ { "body": "<p>What is wrong with:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;body&gt;\n ...\n &lt;div id=\"myfloatingElement\"&gt;This is the element&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>css:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#myfloatingElement\n{\n position: fixed;\n right: 0;\n top: 50%;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:55:46.420", "Id": "14338", "Score": "0", "body": "So that will fix the element to the middle of the page as you scroll, which is fine, but that's not what I'm trying to do.\n\nI've just re-read my first paragraph, and perhaps it's not clear, but what I'm trying to do is position the element against the center of the inner scrollbar, i.e. the part of the scrollbar that moves as you scroll up and down the page.\n\nI'll edit the first paragraph to make it more clear - sorry for the ambiguity!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T00:11:11.727", "Id": "14344", "Score": "0", "body": "You mean the grey \"handlebar\" bit inside the scrollbar?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T02:28:16.777", "Id": "14351", "Score": "0", "body": "Yes - precisely. \"Handlebar\" works very well. Thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T02:11:53.890", "Id": "9075", "ParentId": "8977", "Score": "2" } }, { "body": "<p>I got mixed results from researching whether \"scroll bar\" properly refers to the movable part or the larger range. I had originally thought the latter, and had called the movable part a \"thumb\" -- that may be a java-ism. I opted to use the OP's original definition (movable part) for \"scroll bar\" -- for the \"handlebar\", if you prefer. And I used \"scroll bar area\" for the larger range -- the \"scrollbar\", if you prefer. Sorry for any confusion.</p>\n\n<p>Refactoring common expressions exposed some quirks in the OP.\nThe original formula for the no-scrollbar case used <code>+ target.height()</code> \nin place of the <code>- target.height()</code> used everywhere else, \nbut taller targets should <em>always</em> get <em>smaller</em> offsets, yes?</p>\n\n<p>Also, that case strangely ignored element_offset \n-- wouldn't that cause target to suddenly jump when the body or \nwindow is resized to make the scroll-bar appear/disappear?\nI brought element_offset and (largely as a result) bounds testing into this case.</p>\n\n<p>The window_height_adj value was an odd name for the scroll area height.\nIt was being mistaken for the simpler window_height in one calculation. \nI factored it into the more useful scroll_scale_factor to avoid such confusion. </p>\n\n<p>Scroll position plays two roles:</p>\n\n<ul>\n<li><p>a baseline for the mid-window position \ncalculation that gets scaled down to produce the relative \nmid-scrollbar position, and </p></li>\n<li><p>a baseline for the final offset.</p></li>\n</ul>\n\n<p>Calculating only relative offsets until the very end more clearly \nseparates out this second role and simplifies the bounds testing.</p>\n\n<pre><code>barFollower = function (e) {\n var target = $(e.data.target),\n scrollbar_button_height = 20, // (depends on browser chrome, unfortunately)\n window_height = $(window).height(),\n max_target_offset = window_height - target.height(),\n scroll_position = $(window).scrollTop(),\n body_height = $('body').height(),\n // ratio of full body height to full height of scroll area \n // which does not include the buttons.\n scroll_scale_factor = body_height / (window_height - (scrollbar_button_height * 2)),\n offset = 0;\n\n if (body_height &lt;= window_height) { // If there's no scrollbar.\n offset = max_target_offset / 2 - element_offset; // Position halfway down the window\n } else {\n offset = scrollbar_button_height \n + (scroll_position + window_height/2) / scroll_scale_factor; // mid-window position reduced to scroll area scale\n - element_offset; // offset for chosen 'position' based on element height - see notes below\n }\n\n /* Some catches for when element height might mean it would get positioned outside the window */\n if (offset &lt; 0) { // Top bounds\n offset = 0; // Fix it to the top of the window\n } else if (offset &gt; max_target_offset) { // Bottom bounds\n offset = max_target_offset; // Fix it to the bottom of the window\n }\n target.css('top', scroll_position + offset);\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T03:01:30.597", "Id": "9161", "ParentId": "8977", "Score": "1" } } ]
{ "AcceptedAnswerId": "9161", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T21:22:28.010", "Id": "8977", "Score": "2", "Tags": [ "javascript", "jquery", "css" ], "Title": "Anchoring an element to the browser's vertical scrollbar" }
8977
<p>I've written a DOM element selector engine that I'm really quite happy with, and I'd love to hear some opinions on it from my fellow JavaScripters :D</p> <p>It's called Atomic, and I've got a repository for it over at GitHub - and I've also included the code below...</p> <p>Check it out (if you're in the mood) and let me know what you think. I'd appreciate any and all feedback!</p> <pre><code>/* Atomic Elements Selector Engine v0.1 (Beta) Copyright (c) 2012 Craig Pierce &lt;craig@atomicjs.com&gt; http://www.atomicjs.com */ /* THIS SOFTWARE HAS BEEN RELEASED IN "AS IS" CONDITION, WITHOUT ANY WARRANTY, AND IS AVAILABLE UNDER THE AS YOU WISH PUBLIC LICENSE. */ /* As You Wish Public License Copyright (c) 2012 Craig Pierce &lt;craig@underctrl.com&gt; http://www.underctrl.com/as-you-wish/ Use and/or distribute exact copies of this license as you wish. Use and/or distribute exact copies of any works covered by this license as you wish. Modify any works covered by this license as you wish, so long as you: 0. Retain for attribution all applicable copyrights and/or authorship notices. 1. Use and/or distribute all resulting works under at least the same licenses as the originating work. */ ;(function buildAtomicEngine(global, undefined){ "use strict"; var version = "0.1", dom = global.document, domReady = false, readyTimer = setInterval(checkDomReady, 50), readyCallbacks = [], atomicCache = {}, cacheableRegex = /^(#document|body|html)$/i, readyStateRegex = /^(loaded|interactive|complete)$/i, commaSplitRegex = /\s*,\s*(?=(?:[^\)]|\([^\)]*\))*$)/, selectorReplaceRegex = new RegExp( "=([^'\"]+?)\\]|" + "\\[(.+?!=.+?)\\]|" + ":not\\((.+?,.+?)\\)|" + "^([&gt;~\\s\\+])|" + "([&gt;~\\s\\+])$|" + ":(even|odd|selected|text|password|checkbox|radio|button|submit|reset|image|file|hidden)" , "gi"); global.atomic = { version : version, options : { fallback : null, selectorOrder : false, useCache : true }, ready : function (callback){ domReady ? callback() : readyCallbacks.push(callback); }, clearCache : function (){ atomicCache = {}; }, get : function (selector, context, options){ var defaults = global.atomic.options; if (!context){ context = dom; }else if(!context.childNodes &amp;&amp; context.length == undefined){ options = context; context = dom; }; options = (options || {}); options.selectorOrder = (options.selectorOrder == undefined) ? defaults.selectorOrder : options.selectorOrder; options.useCache = (options.useCache == undefined) ? defaults.useCache : options.useCache; return getElements(selector.replace(selectorReplaceRegex, selectorReplace), context, options); } }; if (dom.addEventListener){ dom.addEventListener("DOMContentLoaded", handleDomReady, false); dom.addEventListener("load", handleDomReady, false); }else{ dom.attachEvent("DOMContentLoaded", handleDomReady); dom.attachEvent("onload", handleDomReady); }; function checkDomReady(){ if (!domReady &amp;&amp; readyStateRegex.test(dom.readyState)){ handleDomReady(); }; }; function handleDomReady(){ if (!domReady){ var x = -1, lenx = readyCallbacks.length; domReady = true; clearInterval(readyTimer); while (++x &lt; lenx){ readyCallbacks[x](); }; readyCallbacks = null; }; }; function selectorReplace(match, capture1, capture2, capture3, capture4, capture5, capture6){ var replacement = "", x = -1, lenx; if (capture1){ replacement = ("='" + capture1 + "']"); }else if (capture2){ replacement = ":not([" + capture2.replace("!=", "=") + "])"; }else if (capture3){ var capture3Split = capture3.split(commaSplitRegex), append = "):not("; lenx = capture3Split.length; while (++x &lt; lenx){ replacement += (capture3Split[x] + append); }; replacement = (":not(" + replacement.slice(0, -5)); }else if (capture4){ replacement = ("*" + capture4); }else if (capture5){ replacement = (capture5 + "*"); }else if (capture6){ capture6 = capture6.toLowerCase(); if (capture6 == "selected"){ replacement = "[selected]"; }else if (capture6 == "even" || capture6 == "odd"){ replacement = (":nth-child(" + capture6 + ")"); }else{ replacement = ("[type='" + capture6 + "']"); }; }; return replacement; }; function getElements(selector, context, options){ var atomicElements = [], selectors = selector.split(commaSplitRegex), x = -1, lenx = selectors.length, isDomOrder = (lenx == 1 || !options.selectorOrder), contextName = (context.nodeName || ""), isCacheable = cacheableRegex.test(contextName), useCache = (isCacheable &amp;&amp; options.useCache), cacheKey = (selector + contextName + (isDomOrder ? "" : "sorder")), cacheItem = (useCache) ? atomicCache[cacheKey] : null; if (cacheItem){ atomicElements = cacheItem; }else{ var fallback = global.atomic.options.fallback, y = -1, leny = context.length; if (isDomOrder){ if (contextName){ atomicElements = atomicDeduplicator(performSelection(selector, context, fallback)); }else{ while (++y &lt; leny){ atomicElements = atomicDeduplicator(performSelection(selector, context[y], fallback), atomicElements); }; atomicElements.sort(byDomOrder); }; }else{ if (contextName){ while (++x &lt; lenx){ var selectorX = selectors[x], cacheKeyX = (selectorX + contextName), cacheItemX = (useCache) ? atomicCache[cacheKeyX] : null, atomicElementsX = (cacheItemX) ? cacheItemX : performSelection(selectorX, context, fallback); atomicElements = atomicDeduplicator(atomicElementsX, atomicElements); if (isCacheable &amp;&amp; !cacheItemX){ atomicCache[cacheKeyX] = atomicDeduplicator(atomicElementsX).slice(0); }; }; }else{ context = atomicDeduplicator(context).sort(byDomOrder); while (++x &lt; lenx){ y = -1; while (++y &lt; leny){ atomicElements = atomicDeduplicator(performSelection(selectors[x], context[y], fallback), atomicElements); }; }; }; }; if (isCacheable){ atomicCache[cacheKey] = atomicElements.slice(0); }; }; return atomicElements.slice(0); }; function performSelection(selector, context, fallback){ try{ return context.querySelectorAll(selector); }catch (ex){ if (fallback){ return fallback(selector, context); }; throw ex; }; }; function atomicDeduplicator(newElements, existingElements){ var x = -1, lenx = newElements.length; if (existingElements &amp;&amp; existingElements.length){ var atomicElements = existingElements.slice(0), y, leny = atomicElements.length; loopx: while (++x &lt; lenx){ var element = newElements[x]; y = -1; while (++y &lt; leny){ if (element == atomicElements[y]){ continue loopx; }; }; atomicElements.push(element); }; return atomicElements; }else if (Object.prototype.toString.call(newElements).toLowerCase().indexOf("array") == -1){ var atomicElements = new Array(lenx); while (++x &lt; lenx){ atomicElements[x] = newElements[x]; }; return atomicElements; }else{ return newElements; }; }; function byDomOrder(x, y){ return (x.compareDocumentPosition) ? (3 - (x.compareDocumentPosition(y) &amp; 6)) : (x.sourceIndex - y.sourceIndex); }; })(this); </code></pre>
[]
[ { "body": "<p>Some things I noticed:</p>\n\n<ol>\n<li>You don't need a semicolon after almost any case you use it after a <code>}</code> (see <a href=\"https://stackoverflow.com/questions/2717949/javascript-when-should-i-use-a-semicolon-after-curly-braces\">https://stackoverflow.com/questions/2717949/javascript-when-should-i-use-a-semicolon-after-curly-braces</a> ) - remove it after the <code>}</code> character in ALL cases except <code>atomicCache = {};</code></li>\n<li>I personally prefer spaces between braces and items (e.g. use <code>} else {</code> instead of <code>}else{</code> ) - and many other people do too, I hope...</li>\n<li><code>options = (options || {});</code> can be simplified to <code>options |= {};</code></li>\n<li><code>lenx = readyCallbacks.length;</code> has incorrect tab spacing before it (typo)</li>\n<li>It might be more clear to name the parameters <code>capture1</code>, <code>capture2</code>, etc something more clear - or write some comments on the if/then lines explaining each case</li>\n<li>You might want to replace the <code>if (isCacheable)</code> items with <code>if (useCache)</code> to avoid populating your cache when it's not going to be used</li>\n</ol>\n\n<p>(EDIT: accidentally put <code>?=</code> instead of <code>|=</code> for #3)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T01:58:55.153", "Id": "9021", "ParentId": "8979", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T21:56:20.387", "Id": "8979", "Score": "6", "Tags": [ "javascript", "api" ], "Title": "Atomic elements selector engine" }
8979
<p>I need to allow incoming HTML in string parameters in my projects action methods, so we have disabled Input Validation. I have a good HTML sanitizer; the review I am interested in is the way I bound it into my project.</p> <p>I have the following Model Binder:</p> <pre><code> public class EIMBaseModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var boundValue = base.BindModel(controllerContext, bindingContext); return bindingContext.ModelType == typeof(string) ? HtmlCleaner.SanitizeHtml((string)boundValue) : boundValue; } protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { if (propertyDescriptor.PropertyType == typeof(string)) { var stringVal = value as string; value = stringVal.IsNullOrEmpty() ? null : HtmlCleaner.SanitizeHtml(stringVal); } base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); } } </code></pre> <p>I set it as my DefaultBinder in my set up and require that all custom model binders inherit from it. I know I can't completely defend against developers not following this rule, but we are a small team so I think we can police that well enough.</p> <p>I have some basic unit testing pushing both string primitive values and strings as property values through the binder and those work as expected. I will be asking the security team to do some penetration tests.</p> <p>Can anyone see either a better way to have hooked into the incoming data or a base I have missed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-16T23:22:24.907", "Id": "204468", "Score": "0", "body": "I've rolled back Rev 3 → 2, for editing away an issue that was helpfully pointed out in an answer." } ]
[ { "body": "<p>Can't comment on whether there is a better way or a better place in the framework to do this but some general remarks:</p>\n\n<ol>\n<li><p>This doesn't make much sense: <code>stringVal.IsNullOrEmpty()</code> - should be <code>string.IsNullOrEmpty(stringVal)</code>.</p></li>\n<li><p>You are inconsistent: In the first method you check the type and use a direct cast vs in the second method you check the type and then use <code>as</code> - either you trust the type is correct or you don't. Also in <code>SetProperty</code> you try to not pass <code>null</code> or empty strings to the sanitizer helper while in <code>BindModel</code> you don't. </p></li>\n<li><p>It would make sense if the helper method would support <code>null</code> and empty strings.</p></li>\n</ol>\n\n<p>With the above the cleaned up code for <code>SetProperty</code> should probably look like this:</p>\n\n<pre><code> protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)\n {\n if (propertyDescriptor.PropertyType == typeof(string))\n {\n value = HtmlCleaner.SanitizeHtml((string)value);\n }\n\n base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-16T23:04:48.700", "Id": "204461", "Score": "0", "body": "Well I never expected a response to this after 3.5 years...that should be worth a Tumbleweed badge. Apologies for the stringVal.IsNullOrEmpty; that is a reference to an extension method, which really isn't appropriate in a code review question unless it is central to the issue at hand. Will fix. Will consider the rest of your answer but I haven't looked at that code in Years." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-17T08:17:22.917", "Id": "204504", "Score": "0", "body": "@MatthewNichols: Just working the zombies :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-14T00:29:36.153", "Id": "110725", "ParentId": "8980", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:15:43.320", "Id": "8980", "Score": "7", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "ASP.NET MVC 3 ModelBinder with string sanitizing" }
8980
<p>While implementing auto refreshing div in jQuery that fetches updates on posts periodically as can be seen on Twitter, Facebook etc.</p> <p>I had to think about making the refresh as efficient as possible. I decided to send a request to the server every 30 seconds - 1 minute. And, the request will be sent only if the browser window is active.</p> <pre><code>var postUpdateIntervalID; var interval = 30000; $(window).load(function(){ if (!postUpdateIntervalID) { postUpdateIntervalID = setInterval(function() { updatePostsList(); }, interval); } }); $(window).focus(function(){ if (!postUpdateIntervalID) { updatePostsList(); postUpdateIntervalID = setInterval(function() { updatePostsList(); }, interval); } }); $(window).blur(function() { clearInterval(postUpdateIntervalID); postUpdateIntervalID = 0; }); function updatePostsList() { // Sends a request to the server to fetch new posts. } </code></pre> <ol> <li>On load, set interval of 30 seconds to call <code>updatePostsList</code>.</li> <li>On focus, call <code>updatePostsList</code> immediately. Then, set interval as above.</li> <li>On blur, reset the interval.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:47:54.317", "Id": "14079", "Score": "1", "body": "This seems like a sensible model, since you can't setup a proper Observer pattern. You could send out an AJAX request with no timeout, and have the server not respond until it needs too. That would be able the closest to an Observer pattern as you could get I would think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:49:29.857", "Id": "14080", "Score": "0", "body": "Is this for a simple web-page/site, or a more complex webapp integration?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:50:43.803", "Id": "14081", "Score": "0", "body": "For a complex webapp integration. Is that question to estimate the power of the webserver and the database server?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:55:56.063", "Id": "14082", "Score": "1", "body": "Focus/Blur isn't a solid bet. I'm willing to bet at least one user will use two monitors and leave your \"feed\" up on one screen, while using the other and wonder why it isn't working." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:55:56.993", "Id": "14083", "Score": "0", "body": "In firefox and IE the focus event will fire after the window has loaded so your code might be redundant.\n\nhttp://stackoverflow.com/questions/1408699/using-jquery-to-bind-focus-and-blur-functions-for-window-doesnt-work-in\n\nAlso, why are you calling the updatePostsList() directly in the focus handler but not in the load handler?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T23:01:25.477", "Id": "14084", "Score": "0", "body": "That's a very good point Robert. I call the updatePostsList directly as soon as the browser gets focus. SO that as soon as the user returns, an update happens. Its not a perfect solution but I consider it a work around. Do u have any suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T23:07:29.103", "Id": "14085", "Score": "0", "body": "Well, I clear the interval on blur. So when the user gets back, focus is fired. I handle the focus by calling updatePostsList. So that the user sees the updated list as soon as he gets back to the website. After that the normal interval thingy continues. That's why the function is called directly on focus but not on load. Plus, initially the data is displayed using the server-side language only. So, no need to call updatePostsList immediately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T23:18:22.690", "Id": "14087", "Score": "0", "body": "DeviantSeev -> Actually, the focus event is fired on window load on chrome as well. But my focus event handler does its thing only if the variable \"postUpdateIntervalID\" is not set. Load event handler sets it. So repetition does not occur. On blur, the variable is resetted. So, when the user comes back and focus event is fired, it does its thang!! ;)" } ]
[ { "body": "<p>If this is for a complex web application, I would recommend using some sort of MVC framework. Personally I prefer backbone.js. Here are some great resources that should help you develop a maintainable app, as well help with updating and refreshing views. </p>\n\n<p>MVC explanation: <a href=\"http://msdn.microsoft.com/en-us/library/ff649643.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ff649643.aspx</a></p>\n\n<p>Backbone.js: <a href=\"http://documentcloud.github.com/backbone/\" rel=\"nofollow\">http://documentcloud.github.com/backbone/</a></p>\n\n<p>Connection between the two: <a href=\"http://css.dzone.com/articles/backbonejs-mvc-javascript\" rel=\"nofollow\">http://css.dzone.com/articles/backbonejs-mvc-javascript</a></p>\n\n<p>As a more direct answer to your question, I believe the code you have looks fine. But if you have multiples modules in your application, running view refresh functions on timers is not a good idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:55:42.173", "Id": "8983", "ParentId": "8982", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T22:42:45.083", "Id": "8982", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Auto refreshing div in jQuery" }
8982
<p>What's a better and more elegant way of writing this:</p> <pre><code>$('#footer form').submit(function(event) { event.preventDefault(event); $('#footer form .preload').spin(opts); $.post('contact.php', $(this).serialize(), function(response) { $('#footer form .preload div').remove(); $('#footer form h5').remove(); $('#footer form .error').html(''); if (response == 1) { $('#footer form h3').after('&lt;h5&gt;Your message has been sent!&lt;/h5&gt;'); $('#footer form input[type=submit]').fadeOut(); } else if (response == 0) { $('#footer form h3').after('&lt;h5&gt;A problem occured. Please try again later.&lt;/h5&gt;'); $('#footer form input[type=submit]').fadeOut(); } else { var errors = $.parseJSON(response); $('label[for=name] .error').html(errors.name); $('label[for=email] .error').html(errors.email); $('label[for=message] .error').html(errors.message); } }); }); </code></pre>
[]
[ { "body": "<p>First thing I would do is cache some selectors, like the form:</p>\n\n<pre><code>$form = $('#footer form');\n</code></pre>\n\n<p>And then you can use it like:</p>\n\n<pre><code>$form.find('h3');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:59:11.940", "Id": "14117", "Score": "1", "body": "To clarify the reason for this: each call to e.g. $('#footer form') has an overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T01:56:28.743", "Id": "14167", "Score": "0", "body": "What do you mean by overhead?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T03:29:43.387", "Id": "8985", "ParentId": "8984", "Score": "2" } }, { "body": "<p>This answer is really just an experiment. I wanted to see if I could make it read better.</p>\n\n<p>I found that I had to process each line and ask \"what does this do?\". I wanted to eliminate that with named functions.</p>\n\n<p>I do like a few patterns of this solution:</p>\n\n<ol>\n<li>separation of the messages</li>\n<li>how the messages are found; and how easy it would be to add another </li>\n<li>displaying the loader and cleaning up element with the ajax call </li>\n<li>logging an error is separate and could be detached completely</li>\n</ol>\n\n<p>Here's the code:</p>\n\n<pre><code>$('#footer form').submit(function(event) {\n event.preventDefault(event);\n\nvar $this = $(this),\n messages = {\n '0': 'A problem occured. Please try again later.',\n '1': 'Your message has been sent!'\n }\n\n$.ajax({\n url: 'contact.php',\n data: $this.serialize(),\n type: 'POST',\n success: displayResponse,\n beforeSend: prepareForResponse,\n complete: hideLoader\n});\n\nfunction displayResponse(response) {\n key = response.toString();\n\n if (isMessage()) {\n displayMessage(messages[key]);\n $this.find('input[type=submit]').fadeOut();\n } else {\n logError(response);\n }\n\n function isMessage() {\n return key in messages\n }\n };\n\n function displayMessage(message) {\n var $h5 = $(\"&lt;h5 /&gt;\").text(message);\n $this.find('h3').after($h5);\n }\n\n function logError(error) {\n var errors = $.parseJSON(error);\n\n $('label[for=name] .error').html(errors.name);\n $('label[for=email] .error').html(errors.email);\n $('label[for=message] .error').html(errors.message);\n }\n\n function prepareForResponse() {\n showLoader();\n clearResponses();\n }\n\n function showLoader() {\n $this.find('.preload').spin(opts); \n }\n\n function clearResponses() {\n $this.find('form h5').remove();\n $this.find('.error').html('');\n }\n\n function hideLoader() {\n $this.find('.preload div').remove();\n }\n});\n</code></pre>\n\n<p>(nothing is tested)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T03:46:03.993", "Id": "10236", "ParentId": "8984", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T01:49:46.240", "Id": "8984", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "jQuery cleaner form submit function" }
8984
<p>I need to model an IP address and thought using a state machine (the state_machine gem) would be a good idea. </p> <p>An IP has the following characteristics:</p> <ol> <li>It is assigned to a server.</li> <li>It can be in state unbound (implies unprotected), bound (implies protected), reserved.</li> <li>It has several firewall rules which should be automatically activated/deactivated when binding/unbinding.</li> <li>It can be migrated from/to another server.</li> <li>All operations, such as (de)activating firewall rules and (un)binding, may fail or externally change their state (consider a machine reboot).</li> </ol> <p>Here is what I came up with so far:</p> <pre><code>require 'rubygems' require 'state_machine' require 'awesome_print' class Ip state_machine :state, :initial =&gt; :unbound do # idle states, i.e. only an event (either external or internal) will trigger a transition. state :unbound, :bound, :reserved # transitionary states, we expect a state change after a certain period of time. state :protected, :unprotected event :cycle do transition :unbound =&gt; :protected transition :protected =&gt; :bound transition :bound =&gt; :unprotected transition :unprotected =&gt; :unbound end event :reserve do transition :unbound =&gt; :reserved end event :release do transition :reserved =&gt; :unbound end before_transition any =&gt; any, :if =&gt; :refreshing? do |ip, transition| puts "refreshing, before_transition -&gt; state is: #{transition.from}, state will be: #{transition.to}" throw :halt unless ip.send("is_#{transition.to}?") end before_transition any =&gt; any do |ip, transition| puts "before_transition -&gt; state is: #{transition.from}, state will be: #{transition.to}" end before_transition any =&gt; :protected, :do =&gt; :activate_firewall_rules before_transition any =&gt; :unprotected, :do =&gt; :deactivate_firewall_rules before_transition any =&gt; :bound, :do =&gt; :bind_to_server before_transition any =&gt; :unbound, :do =&gt; :unbind_from_server after_transition any =&gt; any do |ip, transition| puts "after_transition -&gt; state was: #{transition.from}, state is: #{transition.to}" end end def bind! wait!(:bound) end def unbind! wait!(:unbound) end def migrate!(new_server) restore_state do unbind! self.server = new_server end end def refresh! return if reserved? self.state = self.class.new.state # set to initial state @refreshing = true nil while cycle @refreshing = false end def restore_state old_state = state yield wait!(old_state) end def wait!(desired_state) cycle! while !state?(desired_state) end def refreshing? @refreshing end def activate_firewall_rules puts "activate_firewall_rules..." @is_protected = true end def deactivate_firewall_rules puts "deactivate_firewall_rules..." @is_protected = false end def bind_to_server puts "bind_to_server..." @is_bound = true end def unbind_from_server puts "unbind_from_server..." @is_bound = false end def is_protected? puts "is_protected: #{@is_protected}" @is_protected end def is_unprotected? !is_protected? end def is_bound? puts "is_bound: #{@is_bound}" @is_bound end def is_unbound? !is_bound? end end </code></pre> <p>The public API should be something like this:</p> <pre><code>bind! (bring up firewall and bind address to server) unbind! (unbind address to server and bring down firewall refresh! (get real/external state and update internal state) migrate! (assign to new server, retain state) </code></pre> <p>Since this is my very first state machine I thought I'd like to ask what you think about it. Do you think using a state machine makes sense here at all? Am I using it correctly or am I doing something wrong? What and why? </p>
[]
[ { "body": "<p><em>Better late than never.</em></p>\n\n<p>Yes, a state machine makes sense here. You've chosen good names and your coding style is good.</p>\n\n<p>A few comments:</p>\n\n<p>The \"puts\" lines appear to be for debugging. If that is so, <em>and</em> they are going to remain in the code, I would consider writing to an IO object rather than $stdout. This will make tests much nicer to run, since when passing, you won't be bothered by all the debugging information. For example:</p>\n\n<pre><code>attr_accessor :debug_io\n...\nafter_transition any =&gt; any do |ip, transition|\n @debug_io.puts \"after_transition -&gt; state was: #{transition.from}, state is: #{transition.to}\"\nend\n</code></pre>\n\n<p>And because you want it to still work even if the caller has not set debug_io, give it a default. \"No output\" is a good default:</p>\n\n<pre><code>class NullIO\n def puts ; end\nend\n\ndef initialize\n super\n @debug_io = NullIO.new\nend\n</code></pre>\n\n<p>The return value of <code>is_protected?</code> depends only upon the state, being true if in the <em>bound</em> or <em>protected</em> state. Remove:</p>\n\n<pre><code>before_transition any =&gt; :protected, :do =&gt; :activate_firewall_rules\nbefore_transition any =&gt; :unprotected, :do =&gt; :deactivate_firewall_rules\n</code></pre>\n\n<p>and the methods they call, and change <code>is_protected?</code> to:</p>\n\n<pre><code>def is_protected?\n [:protected, :bound].include?(state)\nend\n</code></pre>\n\n<p>Similarly, remove:</p>\n\n<pre><code>before_transition any =&gt; :bound, :do =&gt; :bind_to_server\nbefore_transition any =&gt; :unbound, :do =&gt; :unbind_from_server\n</code></pre>\n\n<p>and the methods they call, and change <code>is_bound?</code> to:</p>\n\n<pre><code>def is_bound?\n [:bound, :unprotected].include?(state)\nend\n</code></pre>\n\n<p>Ruby predicates usually leave off the \"is_\" prefix. Consider changing <code>is_bound?</code> to <code>bound?</code> and <code>is_protected?</code> to <code>protected?</code>. The is_ prefix comes from languages which do not allow question marks in identifiers.</p>\n\n<p>Mark as \"private\" methods which are for the use of the class only, and should not be called by the class's user. This will help prevent accidental misuse of the class, but more importantly, document the class's public signature, which helps in understanding and is a big help when refactoring. Methods such as <code>bind_to_server</code> and <code>unbind_from_server</code> are private (or were, before they were removed).</p>\n\n<p>It's not clear what this line is for:</p>\n\n<pre><code>throw :halt unless ip.send(\"is_#{transition.to}?\")\n</code></pre>\n\n<p>If it's not for debugging, it seems like an odd bit of hidden coupling between the class and the rest of the program; I would try to find another way to do this that makes it clearer why the :halt is being thrown.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T13:41:48.243", "Id": "38630", "ParentId": "8988", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T08:26:50.427", "Id": "8988", "Score": "6", "Tags": [ "ruby", "state" ], "Title": "Usage of state machine to model lifetime of an IP address" }
8988
<p>I have a <code>Dictionary&lt;string,string&gt;</code> and want to flatten it out with this pattern:</p> <pre><code>{key}={value}|{key}={value}|{key}={value}| </code></pre> <p>I tried with a LINQ approach at first but couldn't solve it, so I ended up writing an extension method like this:</p> <pre><code>public static string ToString(this Dictionary&lt;string,string&gt; source, string keyValueSeparator, string sequenceSeparator) { if (source == null) throw new ArgumentException("Parameter source can not be null."); var str = new StringBuilder(); foreach (var keyvaluepair in source) str.Append(string.Format("{0}{1}{2}{3}", keyvaluepair.Key, keyValueSeparator, keyvaluepair.Value, sequenceSeparator)); var retval = str.ToString(); return retval.Substring(0,retval.Length - sequenceSeparator.Length); //remove last seq_separator } </code></pre> <p>Is it possible to solve this with LINQ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T17:47:38.933", "Id": "53980", "Score": "0", "body": "I would recommend declaring the concerned parameter in the Exception as follows: `throw new ArgumentException(\"Parameter can not be null.\", \"source\")`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-22T05:16:19.810", "Id": "266333", "Score": "0", "body": "@LoSauer good but even better is `throw new ArgumentException(\"Parameter can not be null.\", nameof(source));`" } ]
[ { "body": "<p>Something like this should work:</p>\n\n<pre><code>public static string ToString(this Dictionary&lt;string,string&gt; source, string keyValueSeparator, string sequenceSeparator)\n{\n if (source == null)\n throw new ArgumentException(\"Parameter source can not be null.\");\n\n var pairs = source.Select(x =&gt; string.Format(\"{0}{1}{2}\", x.Key, keyValueSeparator, x.Value));\n\n return string.Join(sequenceSeparator, pairs);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T11:37:50.097", "Id": "14103", "Score": "0", "body": "ah, the .Select method returns an IEnumerable<T>. any idea of performance on this one versus the good ol' stringbuilder? thank you, btw." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T12:42:37.783", "Id": "14105", "Score": "0", "body": "String.format uses StringBuilder, but in this case it creates a new instance for each enumeration. Trevor's solution is of course faster, but I dont think you need to worry about performance here unless your dictionary is wickedly large :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T21:24:46.170", "Id": "14475", "Score": "1", "body": "You do not need a String.Format for simple string concatenation and your code is faster without it. Just do `x.Key + keyValueSeparator + x.Value` which the compiler turns into a String.Concat() which only allocates a single new string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T23:15:47.120", "Id": "14486", "Score": "0", "body": "@Mattias Just for your reference and not that it really matters but you seem to be missing an end bracket on the var pairs line probably before the ToArray() call..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T12:23:07.557", "Id": "24665", "Score": "0", "body": "@Mattias have you tested your code before posting here? It gives compilation error on .NET 4." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T11:26:32.450", "Id": "8993", "ParentId": "8992", "Score": "23" } }, { "body": "<p>How about this?</p>\n\n<p>Firstly, if you haven't already created the ForEach extension method, add one:</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; items, Action&lt;T&gt; action)\n {\n foreach (var item in items)\n {\n action(item);\n }\n }\n}\n</code></pre>\n\n<p>Then add an extension method for your dictionary:</p>\n\n<pre><code>public static class DictionaryExtensions\n{\n public static string ToString&lt;TKey, TValue&gt;(\n this IDictionary&lt;TKey, TValue&gt; dictionary, string keyValueSeparator, string sequenceSeparator)\n {\n var stringBuilder = new StringBuilder();\n dictionary.ForEach(\n x =&gt; stringBuilder.AppendFormat(\"{0}{1}{2}{3}\", x.Key.ToString(), keyValueSeparator, x.Value.ToString(), sequenceSeparator));\n\n return stringBuilder.ToString(0, stringBuilder.Length - sequenceSeparator.Length);\n }\n}\n</code></pre>\n\n<p>Then to call it:</p>\n\n<pre><code>var dictionary = new Dictionary&lt;string, string&gt;();\ndictionary.Add(\"key1\", \"value1\");\ndictionary.Add(\"key2\", \"value2\");\ndictionary.Add(\"key3\", \"value3\");\n\nSystem.Console.WriteLine(dictionary.ToString(\"=\", \"|\"));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:10:56.313", "Id": "14110", "Score": "0", "body": "The List<T> class already has ForEach, by the way. :)\nSo whatever.ToList().ForEach is already implemented in the BCL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:22:08.267", "Id": "14112", "Score": "0", "body": "@Lars-Erik - The reason to use an extension method on IEnumerable<T> is to avoid having to create and populate a list instance just to gain access to the ForEach method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:44:23.963", "Id": "14114", "Score": "0", "body": "@TrevorPilley If performance really is an issue, I agree. And if so, I believe you have to consider a few more things - when does it execute, what if you camouflage an IQueryable etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T11:40:47.363", "Id": "8994", "ParentId": "8992", "Score": "1" } }, { "body": "<p>The pure LINQ way of doing it is with the <code>Aggregate</code> extension method:</p>\n\n<pre><code>public static string ToStringLinq&lt;TKey, TValue&gt; (this Dictionary&lt;TKey, TValue&gt; source, string keyValueSeparator, string sequenceSeparator)\n{\n return source.Aggregate(string.Empty, (acc, pair) =&gt; string.Format(\"{0}{1}{2}{3}{4}\", acc, sequenceSeparator, pair.Key, keyValueSeparator, pair.Value));\n}\n</code></pre>\n\n<p>The downside of the above method is that it will put a sequence separator at the start of your string.</p>\n\n<p>Alternatively:</p>\n\n<pre><code>public static string ToStringLinq&lt;TKey, TValue&gt; (this Dictionary&lt;TKey, TValue&gt; source, string keyValueSeparator, string sequenceSeparator)\n{\n return source.Aggregate(string.Empty, (acc, pair) =&gt; string.Format(\"{0}{1}{2}{3}{4}\", acc, pair.Key, keyValueSeparator, pair.Value, sequenceSeparator));\n}\n</code></pre>\n\n<p>This will place a separator at the end instead of the beginning.</p>\n\n<p>If it is important not to have a leading or trailing separator, you can certainly update the lambda to account for a case with an empty accumulator, or you could add code to seed with a string for the first element and then aggregate over the rest of the dictionary, as shown below:</p>\n\n<pre><code>public static string ToStringLinq&lt;TKey, TValue&gt; (this Dictionary&lt;TKey, TValue&gt; source, string keyValueSeparator, string sequenceSeparator)\n{\n var first = source.First();\n var seed = string.Format(\"{0}{1}{2}\", first.Key, keyValueSeparator, first.Value);\n\n return source.Skip(1).Aggregate(seed, (acc, pair) =&gt; string.Format(\"{0}{1}{2}{3}{4}\", acc, sequenceSeparator, pair.Key, keyValueSeparator, pair.Value));\n}\n</code></pre>\n\n<p>Of course, this suffers the same problem of Mattias' answer, where it does more object creation as a result of the repeat <code>string.Format</code> calls, but for situations where performance is not an issue, a single aggregate function call can be a very compact means of solving the problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T18:47:40.603", "Id": "9005", "ParentId": "8992", "Score": "0" } }, { "body": "<p>You can actually inline all this with the Aggregate method from LINQ.</p>\n\n<pre><code>return d.Aggregate(new StringBuilder(), (sb, x) =&gt; sb.Append(x.Key + keySep + x.Value + pairSep), sb =&gt; sb.ToString(0, sb.Length - 1));\n</code></pre>\n\n<p>Assuming you can read LINQ, it is probably the cleanest. But it isn't the fastest. I tried all the proposed solutions, and the answer by Mattias is actually the fastest proposed so far.</p>\n\n<p>I have one that is faster though.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nforeach (var x in d)\n{\n sb.Append(x.Key);\n sb.Append(keySep);\n sb.Append(x.Value);\n sb.Append(pairSep);\n}\n\nreturn sb.ToString(0, sb.Length - 1);\n</code></pre>\n\n<p>It is faster to call Append multiple times, and it is also faster to run it expanded like this rather than in my Aggregate (changed to do multiple appends).</p>\n\n<p>Of course the performance difference between all of these is negligible. So choose the one that reads the clearest to you and will be best understood by someone else looking at the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-17T18:56:57.713", "Id": "122217", "Score": "1", "body": "This assumes that `pairSep` is only one character long. To account for different lengths, you should change it to `return sb.ToString(0, sb.Length - pairSep.Length);`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T21:47:16.777", "Id": "9246", "ParentId": "8992", "Score": "9" } }, { "body": "<p>Do you need it as a string in particular or just want to store a dictionary as a setting in the \"Application Settings\" section of the project properties? If you simply need to store a dictionary in the settings file, the following code may suit your needs as well:</p>\n\n<pre><code>public static string Serialize(object obj)\n {\n MemoryStream memorystream = new MemoryStream();\n BinaryFormatter bf = new BinaryFormatter();\n bf.Serialize(memorystream, obj);\n byte[] mStream = memorystream.ToArray();\n string slist = Convert.ToBase64String(mStream);\n return slist;\n }\n\npublic static object Unserialize(string str)\n {\n byte[] mData = Convert.FromBase64String(str);\n MemoryStream memorystream = new MemoryStream(mData);\n BinaryFormatter bf = new BinaryFormatter();\n Object obj = bf.Deserialize(memorystream);\n return obj;\n }\n</code></pre>\n\n<p>Pass your dictionary (or list, queue, stack, whatever) to Serialize and the function returns a string representing that object, like this:</p>\n\n<pre><code> string mystr = Serialize(mydict);\n</code></pre>\n\n<p>To return the object from the string created by the <code>Serialize</code> function, pass that string to <code>Unserialize</code> and it will return an object. You will need to cast back to your original type, such as:</p>\n\n<pre><code> Dictionary&lt;string,string&gt; mydict = (Dictionary&lt;string,string&gt;)Unserialize(string mystr);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:00:53.230", "Id": "9248", "ParentId": "8992", "Score": "2" } }, { "body": "<p>Pure LINQ way using StringBuilder is also possible:</p>\n\n<pre><code> public static string ToStringLinq&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; source, string keyValueSeparator, string sequenceSeparator)\n {\n return source.Aggregate(new StringBuilder(),\n (acc, pair) =&gt; acc.AppendFormat(\"{0}{1}{2}{3}\", pair.Key, keyValueSeparator, pair.Value, sequenceSeparator),\n builder =&gt; builder.Length &gt; sequenceSeparator.Length ?\n builder.ToString(0, builder.Length - sequenceSeparator.Length)\n : String.Empty\n );\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:41:34.007", "Id": "9249", "ParentId": "8992", "Score": "0" } }, { "body": "<p><em>Chris Sainty</em>'s answer is probably the <a href=\"https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java\">fastest</a>, but here's the <strong>shortest</strong> - using <em>Linq</em> as requested:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\npublic static class DictionaryExtension \n{ \n public static string ToStringFlattened(this Dictionary&lt;string, string&gt; source, string keyValueSeparator=\"=\", char sequenceSeparator='|')\n {\n return source == null ? \n \"\" : source.Aggregate(\"\", (str, v) =&gt; \n str + v.Key \n + keyValueSeparator \n + v.Value \n + sequenceSeparator)\n .TrimEnd(sequenceSeparator);\n }\n}\n\nstatic void Main()\n{\n Console.WriteLine(\n new Dictionary&lt;string, string&gt;() \n { { \"key1\", \"val1\" }, { \"key2\", \"value2\" }, }.ToStringFlattened()\n );\n}\n</code></pre>\n\n<p>In .Net Framework >= 4.0 you can just use <em>Zip</em>:</p>\n\n<pre><code>public static string ToStringFlattened(this Dictionary&lt;string, string&gt; source, string keyValueSeparator=\"=\", string sequenceSeparator=\"|\")\n{\n return source == null ? \"\" : string.Join(sequenceSeparator, source.Keys.Zip(source.Values, (k, v) =&gt; k + keyValueSeparator + v));\n}\n</code></pre>\n\n<p><em>Note: If you want to keep the sequenceSeparator at the end, remove the <strong>Trim</strong> from the first method, and add ('+') the sequenceSeparator to the return value of the second example.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-22T05:18:34.420", "Id": "266334", "Score": "0", "body": "good but `str += v.Key` should be `str + v.Key` since we are not modifying str, we are just propagating a new value for it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T05:12:44.937", "Id": "267673", "Score": "0", "body": "Thanks Aluan! Principally you are right. Practically, in this case, there is hardly any difference: \nThe resulting compiled IL Code, in your case would be a quadruple string declaration passed to `string.Concat(string, string, string, string)`, and in the stated case a quadruple string array with subsequent call to `string.Concat(string[])`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T06:30:26.133", "Id": "267682", "Score": "0", "body": "Indeed it's clearer that way since the mutation is irrelevant. I don't have the reputation to edit but you've introduced a bug in the example using `=` instead of plus." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T07:01:28.720", "Id": "267685", "Score": "0", "body": "Of course. Thanks. With the typo it should show in a concerning speed difference as well. Otherwise as indicated, there is none." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:04:10.083", "Id": "33707", "ParentId": "8992", "Score": "6" } }, { "body": "<p>From Mattias solution:</p>\n\n<ul>\n<li><code>string.Concat()</code> is faster then <code>string.Format()</code></li>\n<li>No need to build up an array before <code>string.Join()</code></li>\n</ul>\n\n\n\n<pre><code>public static string ToString(this Dictionary&lt;string,string&gt; source, string keyValueSeparator, string sequenceSeparator)\n{\n if (source == null) throw new ArgumentException(\"Parameter source can not be null.\");\n\n var pairs = source.Select(x =&gt; string.Concat(x.Key, keyValueSeparator, x.Value));\n\n return string.Join(sequenceSeparator, pairs);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:52:01.280", "Id": "33710", "ParentId": "8992", "Score": "0" } } ]
{ "AcceptedAnswerId": "8993", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T11:05:47.983", "Id": "8992", "Score": "28", "Tags": [ "c#", "strings", "linq", "hash-map" ], "Title": "LINQ approach to flatten Dictionary to string" }
8992
<pre><code>/** * Implements hook_field_validate(). * * @param string $entity_type * @param object $entity * @param array $field * @param array $instance * @param array $langcode * @param array $items * @param array $errors * * @return void */ function field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &amp;$errors) { foreach ($items as $delta =&gt; $item) { if (!empty($item['active'])) { /* ... */ } } } </code></pre> <p>The code above works well enough, but I would like to apply some static analysis on it. Enter <a href="http://www.icosaedro.it/en-index.html" rel="nofollow">phplint</a>, which doesn't like the <code>$item['active']</code> check. It says:</p> <blockquote> <p>Warning: can't check usage of `[' applied to a value of type mixed.</p> </blockquote> <p>The warning makes sense, if I don't declare more details about my array, PHPLint won't know if the <code>[]</code>'s are applicable. My problem comes up when I read the <a href="http://www.icosaedro.it/phplint/manual.html?p=arrays" rel="nofollow">array documentation</a> for PHPLint. I don't understand how I'm supposed to change the doc-block to properly describe the array.</p> <p>Array structure with example data:</p> <pre><code>0 =&gt; array('active' =&gt; 1) 1 =&gt; array('active' =&gt; 0) 2 =&gt; array('active' =&gt; 1) 3 =&gt; array('active' =&gt; 0) </code></pre>
[]
[ { "body": "<p>Ok, did not noticed that, then:</p>\n\n<p>@param int[int][string] $items</p>\n\n<p>foreach($items as $k => $e){...}</p>\n\n<p>here $k is int, $e is int[string].</p>\n\n<p>In the general case, if</p>\n\n<p>@param T[I1][I2][I3] $items</p>\n\n<p>then</p>\n\n<p>foreach($items as $k => $e){...}</p>\n\n<p>yields $k of type I1 and $e of type T[I2][I3].</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T17:51:11.207", "Id": "14204", "Score": "0", "body": "Thank you very much. That worked, and also helped me understand the logic. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T10:16:08.147", "Id": "9034", "ParentId": "8995", "Score": "1" } } ]
{ "AcceptedAnswerId": "9034", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T12:13:31.080", "Id": "8995", "Score": "1", "Tags": [ "php" ], "Title": "What docblock definition on this function will satisfy PHPLint?" }
8995
<p>I'm a newbie to Python, and I was wondering whether anyone could give me any pointers on improving the following code:</p> <pre><code>import pygame, sys, time from pygame.locals import * # Define defaults bg = (0,0,0) # background colour spl = (255,255,255) # splash colour ver = "INDEV v1.0" # current version img = "icn.png" # corner icon (UNUSED) cur = "cur.png" # cursor icon player = "player.png" # player logo = "pixl.png" # splash logo currtile_x = 0 currtile_y = 0 # Player details px = 20 py = 20 speedy = 25 up = False down = False left = False right = False singlerun = 1 # Load Map with open('townhall.map', 'r') as f: for line in f: for character in line: if character == "\n": print "Newline" else: if character == "x": print "WALL" else: if character == "a": print "LAND" # Other completed = 0 clock = pygame.time.Clock() splashboot = 0 # Initialise screen pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode((640, 420)) pygame.display.set_caption('The Missing Piece ' + ver) # Unused #icon = pygame.image.load(img).convert_alpha() #pygame.display.set_icon(icon) # Initialise sprites try: cursor = pygame.image.load(cur).convert_alpha() logo = pygame.image.load(logo).convert_alpha() player = pygame.image.load(player).convert_alpha() except: print "Unexpected error loading sprites!" raw_input("Press ENTER to exit") pygame.quit() raise # Splash screen while splashboot != 25: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() splash = pygame.Surface(screen.get_size()) splash = splash.convert() splash.fill(spl) x, y = screen.get_size() gx = x - 600 yx = (y / 2) - 25 font = pygame.font.Font(None, 20) splashver = font.render(ver, 20, (0, 0, 0)) screen.blit(splash, (0, 0)) screen.blit(logo, (gx,yx)) screen.blit(splashver, (520, yx + 50)) pygame.display.update() splashboot += 1 time.sleep(0.1) print splashboot # Fill background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill(bg) # Define instructions font = pygame.font.Font(None, 20) ver = font.render("The Missing Piece " + ver, 20, (0, 0, 0)) conl1 = font.render("W = UP", 20, (0, 0, 0)) conl2 = font.render("A = LEFT", 20, (0, 0, 0)) conl3 = font.render("S = DOWN", 20, (0, 0, 0)) conl4 = font.render("D = RIGHT", 20, (0, 0, 0)) # Event loop while completed != 1: dt = clock.tick(60) speed = speedy / float(dt) for event in pygame.event.get(): if event.type == QUIT: completed = 1 pygame.quit() if event.type == KEYDOWN: if event.key == K_LEFT: left = True if event.key == K_RIGHT: right = True if event.key == K_UP: up = True if event.key == K_DOWN: down = True if event.key == K_a: left = True if event.key == K_d: right = True if event.key == K_w: up = True if event.key == K_s: down = True if event.type == KEYUP: if event.key == K_LEFT: left = False if event.key == K_RIGHT: right = False if event.key == K_UP: up = False if event.key == K_DOWN: down = False if event.key == K_a: left = False if event.key == K_d: right = False if event.key == K_w: up = False if event.key == K_s: down = False # direction scripts if up: py -= speed if down: py += speed if left: px -= speed if right: px += speed # cursor settings mousex,mousey = pygame.mouse.get_pos() mousex -= cursor.get_width()/2 mousey -= cursor.get_height()/2 x, y = screen.get_size() gx = x - 200 # draw background screen.blit(background, (0, 0)) #pygame.draw.rect(screen, (255,255,255), (10,10,200,200), 0) # testbox pygame.draw.rect(screen, (255,255,255), (gx,0,200,y), 0) # sidebar # draw player screen.blit(player, (px, py)) # draw version screen.blit(ver, (gx,1)) # draw instructions screen.blit(conl1, (gx+2,20)) screen.blit(conl2, (gx+2,32)) screen.blit(conl3, (gx+2,44)) screen.blit(conl4, (gx+2,56)) # draw cursor screen.blit(cursor, (mousex, mousey)) pygame.display.update() </code></pre> <p>I have been given one or two suggestions about snippets of the code, but I would like to know how I can make my code more efficient and simpler. I seem to have gone the long / difficult way around.</p>
[]
[ { "body": "<pre><code>import pygame, sys, time\nfrom pygame.locals import *\n\n# Define defaults\nbg = (0,0,0) # background colour\nspl = (255,255,255) # splash colour\nver = \"INDEV v1.0\" # current version\nimg = \"icn.png\" # corner icon (UNUSED)\ncur = \"cur.png\" # cursor icon\nplayer = \"player.png\" # player\nlogo = \"pixl.png\" # splash logo\n</code></pre>\n\n<p>According to python convention, global constants should be in ALL_CAPS. I would also suggest not using these really short abbreviations. Spell out your words.</p>\n\n<pre><code>currtile_x = 0\ncurrtile_y = 0\n\n# Player details\npx = 20\npy = 20\nspeedy = 25\nup = False\ndown = False\nleft = False\nright = False\nsinglerun = 1\n</code></pre>\n\n<p>You shouldn't store all of this in global variables. You should really put them all in classses. This'll work for now but it gets more and more problematic as the complexity grows.</p>\n\n<pre><code># Load Map\nwith open('townhall.map', 'r') as f:\n for line in f:\n for character in line:\n if character == \"\\n\":\n print \"Newline\"\n else:\n if character == \"x\":\n print \"WALL\"\n else: \n if character == \"a\":\n print \"LAND\"\n</code></pre>\n\n<p>I'm guessing this is temporary until you actually implementing loading the map. But there are some improvements that can be made. </p>\n\n<p>Firstly, we can make use of <code>elif</code> which will make the code simpler: </p>\n\n<pre><code> if character == \"\\n\":\n print \"Newline\"\n elif character == \"x\":\n print \"WALL\"\n elif character == \"a\":\n print \"LAND\"\n</code></pre>\n\n<p>We can also use a dictionary:</p>\n\n<pre><code>MAP_TYPES = {\n '\\n' = \"NEWLINE\",\n 'x' = \"WALL\",\n 'a' = \"LAND\"\n}\n\nfor line in f:\n for character in line:\n print MAP_TYPES[character]\n</code></pre>\n\n<p>Which I think further simplifies the situation.</p>\n\n<pre><code># Other\ncompleted = 0\nclock = pygame.time.Clock()\nsplashboot = 0\n\n# Initialise screen\npygame.init()\npygame.mouse.set_visible(False)\nscreen = pygame.display.set_mode((640, 420))\npygame.display.set_caption('The Missing Piece ' + ver)\n\n# Unused\n#icon = pygame.image.load(img).convert_alpha()\n#pygame.display.set_icon(icon)\n</code></pre>\n\n<p>Learn to use version control, and then delete unused code.</p>\n\n<pre><code># Initialise sprites\ntry:\n cursor = pygame.image.load(cur).convert_alpha()\n logo = pygame.image.load(logo).convert_alpha()\n player = pygame.image.load(player).convert_alpha()\nexcept:\n print \"Unexpected error loading sprites!\"\n raw_input(\"Press ENTER to exit\")\n pygame.quit()\n raise\n</code></pre>\n\n<p>Hmm... I'm not sure you bothered catching this error. You end-up-reraising the exception anyway, so what did you gain by asking for the user to push enter?</p>\n\n<pre><code># Splash screen\nwhile splashboot != 25:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n splash = pygame.Surface(screen.get_size())\n splash = splash.convert()\n splash.fill(spl)\n</code></pre>\n\n<p>Typically, this would be done outside of the loop. That way you don't have to recreate it all the time. You probably don't even need this splash, just call fill on the screen.</p>\n\n<pre><code> x, y = screen.get_size()\n</code></pre>\n\n<p><code>x</code> and <code>y</code> usually imply coordinates. Using them to mean sizes is odd.</p>\n\n<pre><code> gx = x - 600\n yx = (y / 2) - 25\n</code></pre>\n\n<p>Very crypitic names, pick something more meaningful.</p>\n\n<pre><code> font = pygame.font.Font(None, 20)\n splashver = font.render(ver, 20, (0, 0, 0))\n</code></pre>\n\n<p>The 20 you are passing is supposed to be a true or false value. Are you trying to tell it the size again?</p>\n\n<pre><code> screen.blit(splash, (0, 0))\n screen.blit(logo, (gx,yx))\n screen.blit(splashver, (520, yx + 50))\n pygame.display.update()\n</code></pre>\n\n<p>Your display doesn't change during this loop. You should draw once before you start the loop. \n splashboot += 1</p>\n\n<p>Use a for loop, <code>for splashboot in xrange(25):</code> rather then the while loop. Then you don't need to increment the loop here.</p>\n\n<pre><code> time.sleep(0.1)\n print splashboot\n\n\n# Fill background\nbackground = pygame.Surface(screen.get_size())\nbackground = background.convert()\nbackground.fill(bg)\n</code></pre>\n\n<p>I don't this helps or is neccessary. Just fill the screen.</p>\n\n<pre><code># Define instructions\nfont = pygame.font.Font(None, 20)\nver = font.render(\"The Missing Piece \" + ver, 20, (0, 0, 0))\nconl1 = font.render(\"W = UP\", 20, (0, 0, 0))\nconl2 = font.render(\"A = LEFT\", 20, (0, 0, 0))\nconl3 = font.render(\"S = DOWN\", 20, (0, 0, 0))\nconl4 = font.render(\"D = RIGHT\", 20, (0, 0, 0))\n\n\n# Event loop\nwhile completed != 1:\n</code></pre>\n\n<p>Why isn't completed True/Falses instead of 1/0?</p>\n\n<pre><code> dt = clock.tick(60)\n speed = speedy / float(dt)\n for event in pygame.event.get():\n if event.type == QUIT:\n completed = 1\n pygame.quit()\n if event.type == KEYDOWN:\n if event.key == K_LEFT:\n left = True\n if event.key == K_RIGHT:\n right = True \n if event.key == K_UP:\n up = True\n if event.key == K_DOWN:\n down = True\n if event.key == K_a:\n left = True\n if event.key == K_d:\n right = True \n if event.key == K_w:\n up = True\n if event.key == K_s:\n down = True\n</code></pre>\n\n<p>Use <code>if event.key == K_s or event.key == K_DOWN</code> or <code>if event.key in (K_s, K_DOWN)</code> to avoid have cases that do the same thing.</p>\n\n<pre><code> if event.type == KEYUP:\n if event.key == K_LEFT:\n left = False\n if event.key == K_RIGHT:\n right = False \n if event.key == K_UP:\n up = False\n if event.key == K_DOWN:\n down = False\n if event.key == K_a:\n left = False\n if event.key == K_d:\n right = False \n if event.key == K_w:\n up = False\n if event.key == K_s:\n down = False\n</code></pre>\n\n<p>You spend a lot of code worrying about flipping up/down/left/right variable. Instead you could do something like</p>\n\n<p>pressed_keys = set()</p>\n\n<p>if event.type == KEY_DOWN:\n pressed_keys.add(event.key)\nelif event.type == KEY_UP:\n pressed_keys.remove(event.key)</p>\n\n<p>Then you use <code>if KEY_s in pressed_keys:</code> to determine whether a key is currently pressed.</p>\n\n<pre><code> # direction scripts\n\n if up:\n py -= speed\n if down:\n py += speed\n if left:\n px -= speed\n if right:\n px += speed\n\n # cursor settings\n mousex,mousey = pygame.mouse.get_pos()\n mousex -= cursor.get_width()/2\n mousey -= cursor.get_height()/2\n x, y = screen.get_size()\n gx = x - 200\n\n # draw background\n screen.blit(background, (0, 0))\n\n #pygame.draw.rect(screen, (255,255,255), (10,10,200,200), 0) # testbox\n pygame.draw.rect(screen, (255,255,255), (gx,0,200,y), 0) # sidebar\n\n # draw player\n screen.blit(player, (px, py))\n\n # draw version\n screen.blit(ver, (gx,1))\n\n # draw instructions\n screen.blit(conl1, (gx+2,20))\n screen.blit(conl2, (gx+2,32))\n screen.blit(conl3, (gx+2,44))\n screen.blit(conl4, (gx+2,56))\n\n # draw cursor\n screen.blit(cursor, (mousex, mousey))\n\n pygame.display.update()\n</code></pre>\n\n<p>Here's my reworking of your game:</p>\n\n<pre><code>import pygame, sys, time\nfrom pygame.locals import *\nVERSION = \"INDEV v1.0\" # current version\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\nBACKGROUND_COLOR = BLACK\nSPLASH_COLOR = WHITE\n\ndef setup_graphics():\n pygame.init()\n pygame.mouse.set_visible(False)\n screen = pygame.display.set_mode((640, 420))\n pygame.display.set_caption('The Missing Piece ' + VERSION)\n return screen\n\ndef load_image(name):\n return pygame.image.load(name).convert_alpha()\n\n\ndef draw_text(surface, text, coordinates):\n text_surface = FONT.render(text, True, BLACK)\n surface.blit(text_surface, coordinates)\n\nclass SplashScreen:\n def __init__(self):\n self.time = 25.0 # show for 25 seconds\n\n def draw(self, screen):\n screen.fill(SPLASH_COLOR)\n screen.blit(LOGO, (40, 185))\n draw_text(screen, VERSION, (520, 235))\n\n def update(self, game, time):\n self.time -= time\n if self.time &lt; 0:\n game.current_screen = GameScreen()\n\nclass GameScreen:\n PLAYER_SPEED = 25\n\n def __init__(self):\n self.player_x = 0\n self.player_y = 0\n\n def draw(self, screen):\n screen.fill(BACKGROUND_COLOR)\n\n pygame.draw.rect(screen, (255,255,255), (440,0,200,420), 0) # sidebar\n\n\n # draw player\n screen.blit(PLAYER_IMAGE, (self.player_x, self.player_y))\n\n # draw instructions\n draw_text(screen, \"The Missing Piece \" + VERSION, (441, 1))\n draw_text(screen, \"W = UP\", (442, 20))\n draw_text(screen, \"A = LEFT\", (442, 32))\n\n draw_text(screen, \"S = DOWN\", (442, 44))\n draw_text(screen, \"D = RIGHT\", (442, 56))\n\n mouse_x,mouse_y = pygame.mouse.get_pos()\n mouse_x -= CURSOR.get_width()/2\n mouse_y -= CURSOR.get_height()/2\n\n screen.blit(CURSOR, (mouse_x, mouse_y) )\n\n def update(self, game, time):\n speed = self.PLAYER_SPEED / time\n if K_s in game.keys_pressed or K_DOWN in game.keys_pressed:\n self.player_y += speed\n elif K_w in game.keys_pressed or K_UP in game.keys_pressed:\n self.player_y -= speed\n elif K_a in game.keys_pressed or K_LEFT in game.keys_pressed:\n self.player_x -= speed\n elif K_d in game.keys_pressed or K_RIGHT in game.keys_pressed:\n self.player_x += speed\n\n\nclass Game:\n def __init__(self, screen, current_screen):\n self.keys_pressed = set()\n self.clock = pygame.time.Clock()\n self.screen = screen\n self.current_screen = current_screen\n\n def run(self):\n while True:\n time = self.clock.tick(60)\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n elif event.type == KEYDOWN:\n self.keys_pressed.add(event.key)\n elif event.type == KEYUP:\n self.keys_pressed.remove(event.key)\n\n self.current_screen.update(self, time)\n self.current_screen.draw(self.screen)\n pygame.display.update()\n\n\nscreen = setup_graphics()\nCURSOR = load_image(\"cur.png\")\nPLAYER_IMAGE = load_image(\"player.png\")\nLOGO = load_image(\"pixl.png\")\nFONT = pygame.font.Font(None, 20)\n\ngame = Game(screen, SplashScreen())\ngame.run()\n</code></pre>\n\n<p>If you don't know classes and functions, you are really going to want to learn them. It'll be difficult doing anything beyond a very simple project without them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T19:20:28.877", "Id": "14127", "Score": "0", "body": "Thankyou so much for spending your time writing that, I understand my problems and will fix them. I will add your name somewhere in the games's credits :) TY" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:21:16.013", "Id": "14143", "Score": "0", "body": "+1. Yet there are a lot of cryptic numbers in the code like 442 vs. constants like SIDEBAR_INDENTED_TEXT_X. ---\nDo not recalculate fixed background details in the loop.\nDraw them once onto a pygame surface. In the loop, blit the surface to the screen before the player and cursor.\nMore efficient and clearer on what changes and what is fixed.\n---\nThe `speed` variable seems wrong. It's a `step` or `distance`, not a speed. `PLAYER_SPEED` **is** a speed, but to get constant player speed, *multiply* `PLAYER_SPEED` by the elapsed time (vs. dividing) to get the `distance` (change in x and/or y)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:46:45.627", "Id": "14151", "Score": "0", "body": "@PaulMartel, all true. I did notice most of those problems, but compared to the bigger issues I though it would better to let them slide." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T11:46:26.607", "Id": "14184", "Score": "0", "body": "The player cannot go diagonal, how would I make it work?\n\nNevermind, I have fixed it by changing the elif's to ifs" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:44:41.180", "Id": "9003", "ParentId": "8996", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T13:32:47.997", "Id": "8996", "Score": "1", "Tags": [ "python", "performance", "beginner", "game", "console" ], "Title": "Moving a game character around the screen" }
8996
<p>I am trying to finish the K&amp;R book on C. Below is an exercise which took a long time to finish. I would like some feedback on optimization or any blatant issues with the code.</p> <blockquote> <p><strong>Exercise 1-21</strong></p> <p>Write a program <code>entab</code> that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Assume a fixed number of tabstops.</p> </blockquote> <pre><code>#include&lt;stdio.h&gt; #define TABSTOP 8 #define TABCHAR '\t' #define SPACECHAR '#' void entab(char input[]); void printchars(char c, int times); void printruler(); int main(int argc, char const *argv[]) { /*char input[] = "this is an aw some piec of code.\n";*/ char input[] = "this is an aw some piec of code.\nright o bro!\n"; printruler(); printf("%s", input); entab(input); printruler(); return 0; } void entab(char input[]) { int c; for (size_t i = 0, pos = 1, spaces = 0; (c = input[i]) != '\0'; ++i){ if (c == ' '){ //else increment the number of spaces ++spaces; //if we have spaces equal to 1 tab width print the tab if(pos % TABSTOP == 0){ putchar('\t'); spaces = 0; } } else{ //if the current character is not a space print the spaces and the character printchars(SPACECHAR, spaces); putchar(c); spaces = 0; } if( c == '\n' ) pos = 1; else pos += 1; } } void printchars(char c, int times){ for (size_t i = 0; i &lt; times; ++i){ putchar(c); } } void printruler(){ for (int i = 1; i &lt; 100; ++i){ if(i%TABSTOP == 0) putchar('|'); else putchar('_'); } putchar('\n'); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:00:46.550", "Id": "14118", "Score": "0", "body": "Small comment. It does not handle strings with spaces and tabs already intermixed correctly. \"A \\tB\" Should be encoded as \"A\\tB\" but it is not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:08:39.420", "Id": "14119", "Score": "0", "body": "I think you're misusing `size_t` where you should be using `int`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:34:48.367", "Id": "14120", "Score": "0", "body": "@Ant: I don;t think there is misuse here (though I would also use int in most situations (but size_t will make sure it works for very long strings)). size_t just means it will be non negative" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T18:09:25.597", "Id": "14122", "Score": "0", "body": "@Loki: Take a look at the signature for printchars(). It accepts `times` as an `int` and then iterates to that value using `size_t`; at least one of those is incorrect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T18:59:55.107", "Id": "14124", "Score": "0", "body": "@Ant: Good point. Create an answer below and I will vote that up. Being consistent with types is important." } ]
[ { "body": "<p>Be consistent with you style:<br>\nIn yout first two function you use the style of putting the brace on the next line.</p>\n\n<pre><code>int main(int argc, char const *argv[])\n{\n\nvoid entab(char input[])\n{\n</code></pre>\n\n<p>While the second two functions you use the style of the trailing '{'</p>\n\n<pre><code>void printchars(char c, int times){\n\nvoid printruler(){\n</code></pre>\n\n<p>People can have big religious wars about the two. Personally I prefer the first one in my code but its not a big deal if a coding standard says use the second one (I don't care enough to argue about it). <strong>BUT</strong> everybody agrees that consistency is important so pick one and stick to it.</p>\n\n<p>Also note the second style of putting the '{' is usually only used for non function scope blocks and that most people use the '{' on the next line for functions (but this is a style thing so not a big deal). Just want to emphasis that consistency is the key.</p>\n\n<p>If you are going to claim that it is <code>aw some</code> (then make sure you have spell checking turned on)</p>\n\n<pre><code> char input[] = \"this is an aw some piec of code.\\nright o bro!\\n\";\n</code></pre>\n\n<p>In the function entab:<br>\nYou don't detect and thus compensate for '\\t' characters in the middle of a string of spaces</p>\n\n<p>Thus \"A \\tB\" is encoded as \"A \\tB\" it should be encoded as \"A\\tB\"</p>\n\n<p>In C (unless you are explicitly using C99) you should not use // style comments. A lot of C compilers are not C99 compliant but a lot are not C99 compliant and support //. You need to be careful on this usage if you want to be portable.</p>\n\n<p>Then is easier written as:</p>\n\n<pre><code> if( c == '\\n' )\n pos = 1; \n else\n pos += 1;\n\n // In my opinion this is clearer (though to beginners it may not be)\n // The intent is to make sure pos is defined (this is not clear with an if\n // unless you read the whole conditional).\n pos = (c == '\\n') ? 1 : pos + 1;\n</code></pre>\n\n<p>Avoid not using braces. It may seem like a waste of time. But get used to using them they will save you from bugs now and then and they do no harm when not needed.</p>\n\n<pre><code> if( c == '\\n' ) {\n pos = 1;\n } \n else {\n pos += 1;\n }\n</code></pre>\n\n<p>Same thing below:</p>\n\n<pre><code> if(i%TABSTOP == 0)\n putchar('|');\n else\n putchar('_');\n\n // Or\n putchar( (i%TABSTOP == 0) ? '|' : '_' );\n</code></pre>\n\n<p>This is also a perfect example of where is dangerous not to use '{}' around the conditional blocks. <code>putchar</code> is not actually a function call (even though it looks like one). Its a macro that will be expanded inline (luckily here putchar is so commonly used that it is written well). But in C there are a lot of macros that look like functions and if they are not well written they will screw up what looks like perfectly good code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T04:27:52.277", "Id": "14179", "Score": "0", "body": "Thank you for such a detailed response, learnt a lot from it. I am using the c99 flag for my compiler." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T17:24:58.257", "Id": "9001", "ParentId": "9000", "Score": "2" } }, { "body": "<p>Be careful to keep your types consistent. Here's your printchars() method:</p>\n\n<pre><code>void printchars(char c, int times){\n for (size_t i = 0; i &lt; times; ++i){\n putchar(c);\n }\n}\n</code></pre>\n\n<p>You're expecting <code>times</code> to be passed as an <code>int</code>, but then you treat it like a <code>size_t</code> in the for loop. You should choose one type and stick with it.</p>\n\n<p>Personally I think you should be using <code>int</code> rather than <code>size_t</code> to ensure your that types reflect their usage and make your code somewhat self-documenting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T19:29:52.797", "Id": "9008", "ParentId": "9000", "Score": "3" } }, { "body": "<h3>Bugs</h3>\n\n<ul>\n<li>If a line ends with spaces, those spaces get discarded. That might be tolerable for many purposes, but you never know when trailing spaces might be significant, as in format=flowed e-mail (<a href=\"http://www.rfc-editor.org/rfc/rfc3676.txt\" rel=\"nofollow\">RFC 3676</a> §4.1).</li>\n<li>If the input already contains tab characters, you interpret them as a single-unit-width characters rather than advancing to the next tab stop.</li>\n</ul>\n\n<h3>Interface</h3>\n\n<ul>\n<li>Your function prints the transformed text to standard output. For greater flexibility and reusability, it should stick to transforming the text; this is known as the single-responsibility principle. Since the output will be no longer than the input, it would be convenient to write the result into the same buffer that contained the input. This is acceptable practice in C, as long as you document the fact that it's an in+out parameter. (I would also return the length of the resulting string.)</li>\n<li>The tab stop width could be parameterized, and therefore probably should be.</li>\n</ul>\n\n<h3>Style</h3>\n\n<ul>\n<li>There's a lot going on in the for-loop header. I would move the initializers for <code>pos</code> and <code>spaces</code> out of the loop, since they don't participate in the condition and update portions of the loop. With that change, the loop is mainly just about <code>i</code>, with the side-effect of setting <code>c</code>.</li>\n<li>It's common to define helper functions first and <code>main()</code> last, so that you don't have to pre-declare your functions.</li>\n<li>I suggest renaming <code>pos</code> to <code>col</code> for clarity, because <code>pos</code> might be an array index, whereas <code>col</code> is definitely a column number on screen.</li>\n</ul>\n\n<p>Here's what I came up with:</p>\n\n<pre><code>/**\n * Replaces spaces with tab characters in buf such that the visual layout\n * is retained. The result is written in buf, and the length of the resulting\n * string is returned.\n */\nsize_t entab(char buf[], int tabstop) {\n size_t j = 0;\n char c;\n int col = 0, spaces = 0;\n\n for (size_t i = 0; (c = buf[i]) != '\\0'; ++i) {\n col++;\n\n switch (c) {\n case ' ':\n ++spaces;\n\n /* We have enough spaces to reach a tab stop, so output a tab. */\n if (col % tabstop == 0) {\n buf[j++] = '\\t';\n spaces = 0;\n }\n break;\n\n case '\\t':\n spaces = 0;\n col += tabstop - (col % tabstop);\n buf[j++] = c;\n break;\n\n case '\\n':\n col = 0;\n /* Flow through... */\n default:\n /* Flush any buffered spaces */\n while (spaces &gt; 0) { buf[j++] = ' '; spaces--; }\n buf[j++] = c;\n }\n }\n while (spaces &gt; 0) { buf[j++] = ' '; spaces--; }\n buf[j] = '\\0';\n return j;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-18T01:02:01.443", "Id": "37643", "ParentId": "9000", "Score": "2" } } ]
{ "AcceptedAnswerId": "9001", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T16:53:24.830", "Id": "9000", "Score": "3", "Tags": [ "optimization", "c", "strings" ], "Title": "Entabbing a string" }
9000
<p>I've tomcat running on my Macbook pro and a web application. Making a request to a servlet (below i'm showing post method code) and tipping top command in terminal show a java process with 200/300% cpu usage. The servlet make a request to a mongo database to retrieve 389 documents and then iterate over this documents,process the text with a language detector and Stanford ner classifier, and index it to a local solr server. Is it normal? Can i improve code or something else to reduce cpu load?</p> <p>this is the code</p> <pre><code>@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SolrServer server = null; try { server = new CommonsHttpSolrServer(conf.getString("solr.url")); } catch (Exception e) { e.printStackTrace(); } if (req.getParameter("delete") != null) { try { server.deleteByQuery("*:*"); server.commit(); } catch (SolrServerException e) { e.printStackTrace(); } } BasicDBObject findUsersQuery = new BasicDBObject(); findUsersQuery.put("indexed", false); DBCursor cur = uColl.find(findUsersQuery); int i = 0; while (cur.hasNext()) { Collection&lt;SolrInputDocument&gt; usersProfiles = new ArrayList&lt;SolrInputDocument&gt;(); // String containing comma separated entities like places, organizations String namedEntities = ""; // String containing other terms associated to facebook user String bagOfWords = ""; CrowdUser user = Converter.toObject(CrowdUser.class, cur.next()); log.debug("Indexing User:" + user.getFacebook().getFacebookID() + " " + user.getFacebook().getFacebookUser().getFirstName() + " " + user.getFacebook().getFacebookUser().getLastName()); FacebookUser fu = user.getFacebook().getFacebookUser(); // Hometown if (fu.getHometown() != null) { String name = fu.getHometown().getName(); log.debug("Location:" + name); if (name != null) { namedEntities += name + " "; } } // Location if (fu.getLocation() != null) { String name = fu.getLocation().getName(); log.debug("Hometown:" + name); if (name != null) { namedEntities += name + " "; } } // Work for (FacebookWork work : fu.getWork()) { log.debug("Works:"); String description = work.getDescription(); String lang = ""; if (description != null) lang = detector.detectLang(description); if (description != null &amp;&amp; "en".equals(lang)) { log.debug("Language detected: " + lang); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(description, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } if (work.getEmployer() != null &amp;&amp; work.getEmployer().getName() != null) namedEntities += work.getEmployer().getName() + " "; if (work.getPosition() != null &amp;&amp; work.getPosition().getName() != null) namedEntities += work.getPosition().getName() + " "; if (work.getLocation() != null &amp;&amp; work.getLocation().getName() != null) namedEntities += work.getLocation().getName() + " "; } // Education for (FacebookEducation education : fu.getEducation()) { log.debug("Education:"); if (education.getSchool() != null &amp;&amp; education.getSchool().getName() != null) namedEntities += education.getSchool().getName() + " "; if (education.getDegree() != null &amp;&amp; education.getDegree().getName() != null) namedEntities += education.getSchool().getName() + " "; if (education.getConcentration() != null) { for (FacebookDataType concentration : education.getConcentration()) { namedEntities += concentration.getName() + " "; } } } String about = fu.getAbout(); if (about != null) { String[] strings = about.split("\\n"); for (String string : strings) { log.debug("About: " + string); String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } String bio = fu.getBio(); if (bio != null) { String[] strings = bio.split("\\n"); for (String string : strings) { log.debug("Bio: " + string); String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } String quotes = fu.getQuotes(); if (quotes != null) { String[] strings = quotes.split("\\n"); for (String string : strings) { log.debug("Quote: " + string); String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } String political = fu.getPolitical(); log.debug("Political : " + political); if (political != null) namedEntities += political + " "; String religion = fu.getReligion(); log.debug("Religion : " + religion); if (religion != null) namedEntities += religion + " "; if (fu.getWebsite() != null) { String HTMLtext = URLUtils.getURLContent(user.getFacebook().getFacebookUser() .getWebsite()); if (HTMLtext != null) { String parsedText = Jsoup.parse(HTMLtext).text(); log.debug("Web Site Content: " + parsedText); // log.debug("Language detected: " + detector.detectLang(parsedText)); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(parsedText, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } ArrayList&lt;FacebookDocument&gt; pages = (ArrayList&lt;FacebookDocument&gt;) MongoUtils .getDocumentsByFacebookID(dColl, user.getFacebook().getFacebookUser() .getFacebookPages_id()); for (FacebookDocument doc : pages) { FacebookPage page = (FacebookPage) doc; log.debug("Page: " + page.getFacebook_id() + " " + page.getName()); if (page.getCategory() != null) bagOfWords += page.getCategory() + " "; if (page.getDescription() != null) { String[] strings = page.getDescription().split("\\n"); for (String string : strings) { log.debug("Page description: " + string); String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { string = Jsoup.parse(string).text(); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } String name = page.getName(); if (name != null) { log.debug("Page name: " + name); String lang = detector.detectLang(name); log.debug("Language detected: " + lang); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(name, serializedClassifier); if ("en".equals(lang)) { namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } else { namedEntities += result.get(1); } } HashMap&lt;String, String&gt; others = page.getOthers(); for (String key : others.keySet()) { try { log.debug("Key: " + key + " Value: " + others.get(key)); if (key.equals("location")) { try { ObjectMapper mapper = new ObjectMapper(); JsonNode location = mapper .readValue(others.get(key), JsonNode.class); if (location.get("state") != null) namedEntities += location.get("state").getTextValue() + " "; if (location.get("country") != null) namedEntities += location.get("country").getTextValue() + " "; if (location.get("city") != null) namedEntities += location.get("city").getTextValue() + " "; } catch (Exception e) { log.debug("Parsing Error"); } } else if (!key.equals("founded") &amp;&amp; !key.equals("is_published") &amp;&amp; !key.equals("hours") &amp;&amp; !key.equals("username")) { String[] strings = others.get(key).split("\\n"); for (String string : strings) { String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { string = Jsoup.parse(string).text(); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } } catch (NullPointerException e) { e.printStackTrace(); } } } ArrayList&lt;FacebookDocument&gt; groups = (ArrayList&lt;FacebookDocument&gt;) MongoUtils .getDocumentsByFacebookID(dColl, user.getFacebook().getFacebookUser() .getFacebookGroups_id()); for (FacebookDocument doc : groups) { FacebookGroup group = (FacebookGroup) doc; log.debug("Group: " + group.getFacebook_id() + " " + group.getName()); if (group.getDescription() != null) { String[] strings = group.getDescription().split("\\n"); for (String string : strings) { log.debug("Group description: " + string); String lang = detector.detectLang(string); log.debug("Language detected: " + lang); if ("en".equals(lang)) { string = Jsoup.parse(string).text(); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } } String name = group.getName(); if (name != null) { log.debug("Group name: " + name); String lang = detector.detectLang(name); log.debug("Language detected: " + lang); ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(name, serializedClassifier); if ("en".equals(lang)) { namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } else { namedEntities += result.get(1); } } if (group.getDiscussions() != null) { String discussion = ""; for (FacebookDiscussion disc : group.getDiscussions()) { String message = disc.getMessage(); log.debug("Discussion: " + message); if (message != null &amp;&amp; "en".equals(detector.detectLang(message))) { discussion += message + ".\n"; } if (disc.getComments() != null) { for (String comment : disc.getComments()) { log.debug("Comment:" + comment); if ("en".equals(detector.detectLang(comment))) { discussion += comment + ".\n"; } } } } ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(discussion, serializedClassifier); namedEntities += result.get(1); bagOfWords += result.get(0) + " "; } } log.debug("NamedEntities: " + namedEntities); log.debug("bagOfWords: " + bagOfWords); SolrInputDocument doc1 = new SolrInputDocument(); doc1.addField("id", user.getFacebook().getFacebookID(), 1.0f); doc1.addField("name", user.getFacebook().getFacebookUser().getFirstName() + " " + user.getFacebook().getFacebookUser().getLastName(), 1.0f); doc1.addField("bagofwords", bagOfWords, 1.0f); doc1.addField("namedentities", namedEntities); usersProfiles.add(doc1); try { server.add(usersProfiles); server.commit(); user.setIndexed(true); MongoUtils.updateUserData(uColl, user); } catch (SolrServerException e) { // TODO Auto-generated catch block e.printStackTrace(); log.debug("Not committed"); } i++; log.debug("Indexed Profile Number:" + i); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:38:30.483", "Id": "14135", "Score": "0", "body": "No, it's not normal to get more CPU usage than the machine can provide (200-300%?). And I don't know about anything else, but _please_ break this up into smaller methods - among other things, it'll allow more targeted profiling." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:26:15.477", "Id": "14146", "Score": "0", "body": "@X-Zero: It's normal if you have more than one CPU core." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:45:46.740", "Id": "14150", "Score": "0", "body": "@palacsint - On windows at least, total output always maxes out at 100%. Two cores would max out at 50% (of total) each." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:59:30.727", "Id": "14155", "Score": "0", "body": "@X-Zero: Yes, you're right. Macbook Pro also could run Windows, but top usually a Unix/Linux command :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T09:57:02.833", "Id": "14181", "Score": "0", "body": "yes it's normal on unix, but i'm asking if (in your opinion) it is normal for this kind of code" } ]
[ { "body": "<p>Some tips:</p>\n\n<ol>\n<li><p>Use <code>StringBuilder</code> instead of string concatenation. (<code>namedEntities</code>, <code>bagOfWords</code>)</p></li>\n<li><p>Maybe you should close the cursor at the end of the method.</p></li>\n</ol>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>Handle exceptions. Why don't you log them with the <code>log</code> object as well? Or should they have proper handling?</p></li>\n<li><p>Do not reuse variables. The <code>string</code> variable in the following snippet is confusing:</p>\n\n<pre><code>for (String string : strings) {\n log.debug(\"Group description: \" + string);\n String lang = detector.detectLang(string);\n log.debug(\"Language detected: \" + lang);\n if (\"en\".equals(lang)) {\n string = Jsoup.parse(string).text();\n ArrayList&lt;String&gt; result = NERUtils.getNamedEntities(string,\n serializedClassifier);\n namedEntities += result.get(1);\n bagOfWords += result.get(0) + \" \";\n }\n\n}\n</code></pre>\n\n<p>Declare a new variable inside the condition:</p>\n\n<pre><code>final String string = Jsoup.parse(string).text();\n</code></pre></li>\n<li><p>Use meaningful variable names. <code>string</code> is not readable as a variable name.</p>\n\n<pre><code>String[] strings = others.get(key).split(\"\\\\n\");\nfor (String string : strings) {\n</code></pre>\n\n<p>What does it store? It could be <code>keyLine</code>, for example.</p></li>\n<li><p>As <em>@X-Zero</em> already mentioned, extract out some methods with descriptive names. It would improve readability a lot.</p></li>\n<li><pre><code>ArrayList&lt;String&gt; result ...\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>List&lt;String&gt; result ...\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java\">Type List vs type ArrayList in Java</a></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T23:04:42.810", "Id": "9018", "ParentId": "9004", "Score": "2" } } ]
{ "AcceptedAnswerId": "9018", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T18:02:27.637", "Id": "9004", "Score": "1", "Tags": [ "java" ], "Title": "CPU under full load java web app (tomcat)" }
9004
<p>It works pretty well, but I suspect there's too many variables, and I wonder what else.</p> <p>I'm using this library: <a href="http://apt.alioth.debian.org/python-apt-doc/library/index.html" rel="nofollow">Python APT</a>.</p> <pre><code>#!/usr/bin/env python3 import argparse import apt def getdeps(deptype, pkg, otherpkg): deps = list() name = otherpkg.shortname otherpkg = otherpkg.candidate for deplist in otherpkg.get_dependencies(deptype): for dep in deplist.or_dependencies: if dep.name == pkg.shortname: deps.append(name) return deps def reverse_dependencies(pkg): """Which packages have some kind of dependency on the given package""" cache = apt.cache.Cache() try: pkg = cache[pkg] except KeyError as e: print(str(e).strip('"')) return 1 dependents = dict() recommends = list() suggests = list() replaces = list() enhances = list() depends = list() for key in cache.keys(): otherpkg = cache[key] depends.append(getdeps("Depends", pkg, otherpkg)) recommends.append(getdeps("Recommends", pkg, otherpkg)) suggests.append(getdeps("Suggests", pkg, otherpkg)) replaces.append(getdeps("Replaces", pkg, otherpkg)) enhances.append(getdeps("Enhances", pkg, otherpkg)) dependents["Depends"] = depends dependents["Recommends"] = recommends dependents["Suggests"] = suggests dependents["Replaces"] = replaces dependents["Enhances"] = enhances for deptype, deps in dependents.items(): deps_output = list() for match in deps: if match: for item in match: deps_output.append(item) if deps_output: print(deptype.upper(), end=": ") print(" ".join(deps_output)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("pkg", help="pkg to describe") args = parser.parse_args() reverse_dependencies(args.pkg) </code></pre> <p>Example terminal session:</p> <pre><code>$ ./rdeps.py python3-apt DEPENDS: python3-apt-dbg wajig ENHANCES: python-apt-common </code></pre>
[]
[ { "body": "<pre><code>#!/usr/bin/env python3\n\nimport argparse\nimport apt\n\ndef getdeps(deptype, pkg, otherpkg):\n</code></pre>\n\n<p>I recommend not using abbrivates like dep or pkg.</p>\n\n<pre><code> deps = list()\n</code></pre>\n\n<p>We usually create lists with <code>[]</code> not <code>list()</code></p>\n\n<pre><code> name = otherpkg.shortname\n otherpkg = otherpkg.candidate\n</code></pre>\n\n<p>I wouldn't do this. You only use it once, so its actually best to just <code>otherpkg.candidate.get_dependencies</code> Generally, I recommend against replacing one variable with another because often it increases confusion.</p>\n\n<pre><code> for deplist in otherpkg.get_dependencies(deptype):\n for dep in deplist.or_dependencies:\n if dep.name == pkg.shortname:\n deps.append(name)\n\n return deps\n</code></pre>\n\n<p>Why does this function return a list? It seems to me that you are checking whether otherpkg depends on pkg. If so, this function really ought to return True or False.</p>\n\n<pre><code>def reverse_dependencies(pkg):\n \"\"\"Which packages have some kind of dependency on the given package\"\"\"\n\n cache = apt.cache.Cache()\n try:\n pkg = cache[pkg]\n except KeyError as e:\n print(str(e).strip('\"'))\n return 1\n</code></pre>\n\n<p>You don't do anything with this return value. you should pass it to <code>sys.exit()</code></p>\n\n<pre><code> dependents = dict()\n</code></pre>\n\n<p>We usually create dicts with <code>{}</code></p>\n\n<pre><code> recommends = list()\n suggests = list()\n replaces = list()\n enhances = list()\n depends = list()\n</code></pre>\n\n<p>These are all basically the same thing which means they shouldn't be seperate variables. </p>\n\n<pre><code> for key in cache.keys():\n otherpkg = cache[key]\n depends.append(getdeps(\"Depends\", pkg, otherpkg))\n recommends.append(getdeps(\"Recommends\", pkg, otherpkg))\n suggests.append(getdeps(\"Suggests\", pkg, otherpkg))\n replaces.append(getdeps(\"Replaces\", pkg, otherpkg))\n enhances.append(getdeps(\"Enhances\", pkg, otherpkg))\n</code></pre>\n\n<p>This would be better as iteration over a list of the dependency types. Also you are putting lists into lists. It'd be cleaner if you just had lists.</p>\n\n<pre><code> dependents[\"Depends\"] = depends\n dependents[\"Recommends\"] = recommends\n dependents[\"Suggests\"] = suggests\n dependents[\"Replaces\"] = replaces\n dependents[\"Enhances\"] = enhances\n\n for deptype, deps in dependents.items():\n deps_output = list()\n for match in deps:\n if match:\n</code></pre>\n\n<p>There's no point in doing this, because the loop will be executed 0 times if match is empty</p>\n\n<pre><code> for item in match:\n deps_output.append(item)\n</code></pre>\n\n<p>Use <code>dep_output.extend(match)</code> it has the same effect as this loop</p>\n\n<pre><code> if deps_output:\n print(deptype.upper(), end=\": \")\n print(\" \".join(deps_output))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"pkg\", help=\"pkg to describe\")\n args = parser.parse_args()\n reverse_dependencies(args.pkg)\n</code></pre>\n\n<p>My reworking of your code:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport argparse\nimport apt\nimport sys\n\nDEPENDENCY_TYPES = [\n \"Depends\",\n \"Recommends\",\n \"Suggests\",\n \"Replaces\",\n \"Enhances\",\n]\n\ndef extract_dependencies(package, dependency_type):\n \"\"\"\n Generator that produce all the dependencies of a particular type\n \"\"\"\n for dependency_list in package.candidate.get_dependencies(dependency_type):\n for dependency in dependency_list.or_dependencies:\n yield dependency.name\n\ndef reverse_dependencies(pkg):\n \"\"\"Which packages have some kind of dependency on the given package\"\"\"\n\n cache = apt.cache.Cache()\n try:\n pkg = cache[pkg]\n except KeyError as error:\n print(error.args[0])\n sys.exit(1)\n\n dependents = { name : [] for name in DEPENDENCY_TYPES }\n\n for key in cache.keys():\n other_package = cache[key]\n for dependency_type, specific_dependents in dependents.items():\n if pkg.shortname in extract_dependencies(other_package, dependency_type):\n specific_dependents.append(other_package.shortname)\n\n for dependency_type, specific_dependents in dependents.items():\n if specific_dependents:\n print(dependency_type.upper(), \": \", \" \".join(specific_dependents))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"pkg\", help=\"pkg to describe\")\n args = parser.parse_args()\n reverse_dependencies(args.pkg)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T20:34:06.293", "Id": "14128", "Score": "0", "body": "I really like your new names, stuff like `extract_dependencies` and `extract_dependencies`. You also exposed me to the fact I didn't fully understand my code. Thanks also for writing a fully-working version of your own alternative, especially since I didn't quite get some of your suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T20:35:51.240", "Id": "14129", "Score": "1", "body": "\"We usually create lists with [] not list()\" but Alex Martelli does not like that (I cannot find the link though)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T20:47:56.790", "Id": "14130", "Score": "0", "body": "@Leonid http://stackoverflow.com/a/2745292" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:35:58.900", "Id": "14147", "Score": "0", "body": "@Tshepang, some exceptions exist, but `[]` is generally more common then `list()`. But its an issue of style, and you can go either way." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T19:38:17.937", "Id": "9009", "ParentId": "9006", "Score": "3" } } ]
{ "AcceptedAnswerId": "9009", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T18:53:10.583", "Id": "9006", "Score": "2", "Tags": [ "python", "linux" ], "Title": "Calculating reverse dependencies of a Debian package" }
9006
<p>I'm just trying to see if anyone disagrees with the way I'm handling my logic for this. Something doesn't feel right with it but I don't quite know what it is.</p> <p>Just wanted to add that the <code>new_password_key</code> is NOT a password for the user to log in with. As of right now I was going to have them directed to a page from a link in an email where they can enter a new password.</p> <pre><code>function forgot_password_submit() { $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean'); if (!$this-&gt;form_validation-&gt;run()) { echo json_encode(array('error' =&gt; 'yes', 'message' =&gt; 'There was a problem submitting the form! Please refresh the window and try again!')); } else { if (!is_null($user_data = $this-&gt;users-&gt;get_user_by_username($this-&gt;input-&gt;post('username')))) { if (!isset($user_data-&gt;new_password_key) &amp;&amp; (!isset($user_data-&gt;new_password_requested))) { if(!strtotime($user_data-&gt;new_password_requested) &lt;= (time() - 172800)) { echo json_encode(array('error' =&gt; 'yes', 'message' =&gt; 'You have to wait 2 days before a new temp password can be emailed!')); } else { if ($this-&gt;kow_auth-&gt;forgot_password($this-&gt;input-&gt;post('username'))) { $this-&gt;kow_auth-&gt;send_email('forgot_password', 'KOW Manager Forgot Password Email', $user_data); echo json_encode(array('success' =&gt; 'yes', 'message' =&gt; 'A temporary password has been emailed to you!')); } else { echo json_encode(array('error' =&gt; 'yes', 'message' =&gt; 'A temporary password could not be created for you!')); } } } else { echo json_encode(array('success' =&gt; 'yes', 'message' =&gt; 'Check your email for your temporary password!')); } } else { echo json_encode(array('error' =&gt; 'yes', 'message' =&gt; 'User does not exist in the database!')); } } } </code></pre> <p><strong>EDIT:</strong> What I'm reallying wondering about how to use the functionality of this setting this temporary new password for when it expires.</p> <p>Library Function:</p> <pre><code>/** * Generate reset code (to change password) and send it to user * * @return string * @return object */ function forgot_password($username) { if (strlen($username) &gt; 0) { if (!is_null($user_data = $this-&gt;ci-&gt;users-&gt;get_user_by_username($username))) { $data = new stdClass; $data-&gt;user_id = $user_data-&gt;user_id; $data-&gt;username = $user_data-&gt;username; $data-&gt;email = $user_data-&gt;email; $data-&gt;new_password_key = md5(rand().microtime()); $data-&gt;first_name = $user_data-&gt;first_name; $data-&gt;last_name = $user_data-&gt;last_name; $this-&gt;ci-&gt;users-&gt;set_password_key($user_data-&gt;user_id, $data-&gt;new_password_key); return $data; } } return NULL; } </code></pre> <p>Model: </p> <pre><code>/** * Set new password key for user. * This key can be used for authentication when resetting user's password. * * @param int * @param string * @return bool */ function set_password_key($user_id, $new_password_key) { $this-&gt;db-&gt;set('new_password_key', $new_password_key); $this-&gt;db-&gt;set('new_password_requested', date('Y-m-d H:i:s')); $this-&gt;db-&gt;where('user_id', $user_id); $this-&gt;db-&gt;update('users'); return $this-&gt;db-&gt;affected_rows() &gt; 0; } </code></pre> <p><strong>EDIT 2:</strong></p> <p>This is what I'm going to use for the controller. There just seems to be some logic issues I have with it because what if it gets down to the if statement if (<code>$already_sent_password</code>) and for some reason they didn't get it. Then what? Or what if it gets down to if (<code>!strtotime($user_data-&gt;new_password_requested) &lt;= (time() - 172800)</code>) which is starting to sounds stupid to me because why make them have to wait two days to get a new password key. </p> <pre><code>function forgot_password_submit() { $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean'); if (!$this-&gt;form_validation-&gt;run()) { $this-&gt;kow_auth-&gt;output('There was a problem submitting the form! Please refresh the window and try again!', FALSE); return; } $user_data = $this-&gt;users-&gt;get_user_by_username($this-&gt;input-&gt;post('username')); if ($user_data === NULL) { $this-&gt;kow_auth-&gt;output('User does not exist in the database!', FALSE); return; } $already_sent_password = (isset($user_data-&gt;new_password_key) &amp;&amp; isset($user_data-&gt;new_password_requested)); if ($already_sent_password) { $this-&gt;kow_auth-&gt;output('Check your email for your temporary password!'); return; } if (!strtotime($user_data-&gt;new_password_requested) &lt;= (time() - 172800)) { $this-&gt;kow_auth-&gt;output('You have to wait 2 days before a new temp password can be emailed!', FALSE); } else { if ($this-&gt;kow_auth-&gt;forgot_password($this-&gt;input-&gt;post('username'))) { $this-&gt;kow_auth-&gt;send_email('forgot_password', 'KOW Manager Forgot Password Email', $user_data); $this-&gt;kow_auth-&gt;output('A temporary password has been emailed to you!'); } else { $this-&gt;kow_auth-&gt;output('A temporary password could not be created for you!', FALSE); } } } </code></pre> <p>Anybody have any more ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:36:09.800", "Id": "14134", "Score": "2", "body": "They can only ask for a new password every two days? I'd remove the restriction. Otherwise, it becomes fairly trivial to DOS any customers who forget their passwords. I'd probably try to break up this method into a series of smaller methods (I don't know the framework, and am out of practive with php, so I'm a bit fuzzy on exactly what though). And you're not just overwriting it in the database are you? Otherwise, you allow hostile password resets (yes, the customer gets the password, but...). Also, consider caching temp passwords per customer until expired or used." } ]
[ { "body": "<p>I see nothing that's wrong with your code. My first reaction though is that you repeat the echo quite a bit. I would turn all the</p>\n\n<pre><code>echo json_encode(array());\n</code></pre>\n\n<p>into something like this:</p>\n\n<pre><code>function output($message, $success = TRUE) {\n $status = $success ? array('succes' =&gt; 'yes') : array('error' =&gt; 'yes');\n echo json_encode($status, $message);\n}\n</code></pre>\n\n<p>The two other things I would have preferred to do differently, is avoiding the deep intendation, and moving some logic out from the if()'s. This is perhaps just a matter of taste, but I find this much easier to read and follow.</p>\n\n<pre><code>function forgot_password_submit() {\n $this-&gt;form_validation-&gt;set_rules('username', 'Username', 'trim|required|xss_clean');\n\n if (!$this-&gt;form_validation-&gt;run()) {\n output('There was a problem submitting the form! Please refresh the window and try again!', FALSE);\n return;\n }\n\n $user_data = $this-&gt;users-&gt;get_user_by_username($this-&gt;input-&gt;post('username'));\n if ($user_data === NULL) {\n output('User does not exist in the database!', FALSE);\n return;\n }\n\n $already_sent_password = (isset($user_data-&gt;new_password_key) &amp;&amp; isset($user_data-&gt;new_password_requested));\n if ($already_sent_password) {\n output('Check your email for your temporary password!');\n return;\n }\n\n if (!strtotime($user_data-&gt;new_password_requested) &lt;= (time() - 172800)) {\n output('You have to wait 2 days before a new temp password can be emailed!', FALSE);\n } else {\n if ($this-&gt;kow_auth-&gt;forgot_password($this-&gt;input-&gt;post('username'))) {\n $this-&gt;kow_auth-&gt;send_email('forgot_password', 'KOW Manager Forgot Password Email', $user_data);\n output('message' =&gt; 'A temporary password has been emailed to you!');\n } else {\n output('A temporary password could not be created for you!', FALSE);\n }\n }\n}\n\nfunction output($message, $success = TRUE) {\n $status = $success ? array('succes' =&gt; 'yes') : array('error' =&gt; 'yes');\n echo json_encode($status, $message);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:51:50.057", "Id": "14139", "Score": "0", "body": "This is a great response and something I will definitely use, however, why how can I handle the password issue differently because of a temporary password expiring. I'm going to update my post above with the library function and model." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:58:15.333", "Id": "14140", "Score": "0", "body": "I updated it. As well as can I move the output function to my library then and send the messages inside the forgot_password_submit function to the the output in the library?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:15:09.753", "Id": "14142", "Score": "0", "body": "I moved the function to my library because I\"m going to use it for other controllers and it says <p>Message: json_encode() expects parameter 2 to be long, string given</p>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:50:39.867", "Id": "14153", "Score": "0", "body": "Check out EDIT 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T23:39:36.793", "Id": "14157", "Score": "0", "body": "Anymore ideas on this?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T21:41:21.260", "Id": "9012", "ParentId": "9010", "Score": "1" } }, { "body": "<p>You can browse over some of my code, it may/not help you out but this is generally how I would approach it.</p>\n\n<p><strong>libraries/Webs3_Auth.php</strong></p>\n\n<pre><code>/**\n * create_token\n * generate json object token with expires\n *\n * @param string $expires time the token will expire\n * @return object\n */\n public static function create_token($expires=3600) {\n return json_encode(array(\n 'token' =&gt; self::generate_rand_string((int) 9),\n 'expires' =&gt; date('h:iA', strtotime('now') + $expires)\n ));\n }\n\n /**\n * _generate_rand_string\n * generate a unique string\n *\n * @param integer the length of the string to return\n * @return string unique string\n */\n public static function generate_rand_string($len=8) {\n $random = '';\n $char_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $char_list .= 'abcdefghijklmnopqrstuvwxyz';\n $char_list .= '0123456789~%.:_-'; //numeric + permitted uri chars\n\n for ($i = 0; $i &lt; $len; $i++) {\n $random .= substr($char_list, (rand() % (strlen($char_list))), 1);\n }\n return $random;\n }\n</code></pre>\n\n<p><strong>libraries/MY_Encrypt.php</strong>\n<em>need to make the encryptions URI safe</em></p>\n\n<pre><code>function encode($string, $key=\"\", $url_safe=TRUE)\n {\n $ret = parent::encode($string, $key);\n\n if ($url_safe)\n {\n $ret = strtr(\n $ret,\n array(\n '+' =&gt; '.',\n '=' =&gt; '-',\n '/' =&gt; '~'\n )\n );\n }\n\n return $ret;\n }\n\n\n function decode($string, $key=\"\")\n {\n $string = strtr(\n $string,\n array(\n '.' =&gt; '+',\n '-' =&gt; '=',\n '~' =&gt; '/'\n )\n );\n\n return parent::decode($string, $key);\n }\n</code></pre>\n\n<p><strong>controllers/Auth.php</strong></p>\n\n<pre><code>public function forgot_password_form(){\n $this-&gt;load-&gt;view('templates/public', array(\n 'robots' =&gt; 'noindex, nofollow',\n 'canonical' =&gt; site_url(),\n 'title' =&gt; 'Forgot Password Form',\n 'content' =&gt; 'auth/forgot_password_form'\n ));\n }\n\npublic function forgot_password_check(){\n\n\n if($this-&gt;form_validation-&gt;run('forgot_password'))\n {\n $request = '';\n $type= $this-&gt;input-&gt;post('login');\n if (preg_match('/^.*\\@.*$/i', $type) &gt; 0) {\n $request = User::find_by_email($type);\n } else {\n $request = User::find_by_alias($type);\n }\n\n $token = Webs3_Auth::create_token();\n $token_bits[] = (array)json_decode($token);\n\n\n if($request-&gt;update_attributes(array(\n 'password_token' =&gt; $token,\n 'last_ip' =&gt; $this-&gt;input-&gt;ip_address()\n )))\n {\n $uid = $this-&gt;encrypt-&gt;encode($request-&gt;id, $this-&gt;config-&gt;item('encryption_key'), true); //uri safe\n\n $link = '&lt;a href=\"'.site_url('reset_password/'.$uid.'/'.$token_bits[0]['token'].'').'\" style=\"background:#76a233;padding:9px;text-align:center;text-decoration:none;border:1px solid #608627;color:#fafafa;display:block;margin-bottom:18px;width:20%;\" target=\"_blank\"&gt;Reset my password&lt;/a&gt;';\n\n $emaildata = array(\n 'token' =&gt; $token_bits[0]['token'],\n 'expires' =&gt; $token_bits[0]['expires'],\n 'link' =&gt; $link\n );\n if(Mailer::sendIt($emaildata, 'forgot_password.html', $request-&gt;email, 'Password Reset'))\n {\n $this-&gt;session-&gt;set_flashdata('success', 'You got mail! Follow the instructions to reset your password');\n redirect('/');\n }\n else\n {\n $this-&gt;session-&gt;set_flashdata('error', 'Could not send password information to you at this time, contact an admin');\n redirect('/');\n }\n }\n else\n {\n $this-&gt;session-&gt;set_flashdata('error', 'A password request could not be made at this time, contact an admin');\n redirect('/');\n }\n\n }\n else\n {\n $this-&gt;forgot_password_form();\n }\n }\n\npublic function reset_password_form($uid=null, $token=null){\n\n $token_secured = FALSE;\n $user_id = $this-&gt;encrypt-&gt;decode($uid, $this-&gt;config-&gt;item('encryption_key'));\n $user = User::find($user_id);\n $now = date('h:iA', strtotime('now'));\n $tokens[] = (array)json_decode($user-&gt;password_token);\n\n $token_secured = ($tokens) ? TRUE : FALSE;\n $token_secured = ($tokens[0]['token'] != rawurldecode($token)) ? TRUE : FALSE;\n $token_secured = ($tokens[0]['expires'] &gt;= $now) ? TRUE : FALSE;\n\n\n if($token_secured === TRUE)\n {\n $this-&gt;load-&gt;view('templates/public', array(\n 'robots' =&gt; 'noindex, nofollow',\n 'canonical' =&gt; site_url(),\n 'title' =&gt; 'Reset password Form',\n 'content' =&gt; 'auth/reset_password_form',\n 'user_id' =&gt; $uid\n ));\n }\n else\n {\n $this-&gt;session-&gt;set_flashdata('info', 'Token is invalid or has expired');\n redirect('/');\n }\n\n }\n\n public function reset_password_check(){\n\n\n if($this-&gt;form_validation-&gt;run('reset_password'))\n {\n $user = User::find($this-&gt;encrypt-&gt;decode($this-&gt;input-&gt;post('user_id'), $this-&gt;config-&gt;item('encryption_key')));\n $data = array(\n 'password' =&gt; Webs3_Auth::prep_password($this-&gt;input-&gt;post('password')),\n 'password_token' =&gt; '',\n 'last_ip' =&gt; $this-&gt;input-&gt;ip_address()\n );\n\n if($user-&gt;update_attributes($data))\n {\n\n $this-&gt;session-&gt;set_flashdata('success', 'Your password has been changed! You may now login with your new password');\n redirect('login');\n }\n else\n {\n $this-&gt;session-&gt;set_flashdata('error', 'There was an error updating our records, try again shortly!');\n redirect('/');\n }\n\n\n }\n else\n {\n $this-&gt;reset_password_form();\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T11:06:46.697", "Id": "9692", "ParentId": "9010", "Score": "1" } } ]
{ "AcceptedAnswerId": "9012", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T20:11:31.527", "Id": "9010", "Score": "3", "Tags": [ "php", "codeigniter" ], "Title": "Forgotten password logic" }
9010
<p>I created my first gem for Rails today. <a href="https://github.com/Fivell/activeresource-response" rel="nofollow">https://github.com/Fivell/activeresource-response</a>. This gem adds possibility to access http response object from result of activeresource call.</p> <ul> <li>I don't know how to create test for this gem.</li> <li>Also I want to ask if there is more simply and elegant way to do this?</li> <li>Is it really thread-safe?</li> <li>Other ways to write this functionllity except <code>alias_method</code>?</li> </ul> <p>Here is source of library.</p> <pre><code>require "activeresource-response/version" module ActiveresourceResponse module Connection def self.included(base) base.class_eval &lt;&lt;-EOS alias_method :origin_handle_response, :handle_response attr_reader :http_response def handle_response(response) @http_response= response origin_handle_response(response) end EOS end end module AddResponseMethod def self.included(base) base.extend ClassMethods end module ClassMethods def add_response_method(method_name = 'http_response') class_eval &lt;&lt;-EOS class &lt;&lt; self alias_method :origin_find, :find def find(*arguments) result = origin_find(*arguments) result.class_eval("attr_reader :#{method_name}") result.instance_variable_set(:"@#{method_name}", connection.http_response) result end end EOS end end end end ActiveResource::Connection.send :include, ActiveresourceResponse::Connection ActiveResource::Base.send :include, ActiveresourceResponse::AddResponseMethod </code></pre> <p>UPDATE</p> <p>I made some refactoring, please look at github sources. </p>
[]
[ { "body": "<p>First thing, it unnecessary to use the <code>included</code> hook methods. Since your purpose is to redefine some methods in <code>ActiveresourceResponse::Connection</code> and <code>Activeresource::Base</code>, why not just do so directly?</p>\n\n<pre><code># if ActiveResource has not been loaded yet, Rails' const_missing hook\n# will load it automatically\nActiveResource::Connection.class_eval do\n alias_method :__handle_response__ :handle_response\n # ... and so on\nend\nActiveResource::Base.instance_eval do\n alias_method :__find__ :find\n # ... and so on\nend\n</code></pre>\n\n<p>By using <code>instance_eval</code> in the second case, we can redefine class methods with 1 less line of code, because <code>class &lt;&lt; self</code> is unnecessary.</p>\n\n<p>In <code>add_response_method</code>, it is unnecessary to pass <code>'http_response'</code> as an argument. That code will never be run with any other value, so why use an argument? Just use a literal value, it's clearer and easier to read.</p>\n\n<p><em>Every</em> time a model object is returned from <code>ActiveResource::Base.find</code>, you define the <code>http_response</code> method on it with <code>class_eval</code>. This is very inefficient -- I think you should just define a <code>http_response</code> instance method on <code>ActiveResource::Base</code>, and all model classes derived from <code>ActiveResource::Base</code> will inherit it. (Think of the work which is done to define a method -- the Ruby parser has to run on the code, it has to be compiled to bytecode, then an entry has to be made in a method table...)</p>\n\n<p>I just benchmarked <code>Object#instance_variable_set</code>, and it's very fast, faster than using <code>instance_eval</code> or <code>instance_exec</code>. So I think that should stay, but don't generate a new symbol using <code>:\"#{}\"</code> each time. Just use something like <code>:@__http_response__</code>. (Why the \"special\" name? Because when you are adding instance variables to a user-defined class, you want to reduce the chances of a collision with a user-defined variable.) Of course, this will mean you can't use <code>attr_reader</code>, but that's no problem. You can just do something like: <code>def http_response; @__http_response__; end</code></p>\n\n<p>For tests, why don't you look at how <code>ActiveResource</code> itself is tested? I'm sure all that code is open-source and should be available from a public repo.</p>\n\n<p>EDIT: I just looked at the GitHub repo and noticed that you changed to a thread-local variable to try to make the code thread-safe. My question is: is a single <code>ActiveResource::Connection</code> object shared by the whole application? Or each time you make a request, does it create a new <code>Connection</code> object? If it creates a new <code>Connection</code> object for each request, then using thread-local variables is unnecessary, and an instance variable would be better. If the whole application is sharing only one <code>Connection</code> object, then using the thread-local variable is a good idea.</p>\n\n<p>EDIT 2: I just found a bug. If a user tries to use <code>add_response_method</code> to add an alias for <code>http_response</code>, subsequent calls to <code>find</code> will go into an infinite loop. Try it and you will see.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T15:39:05.907", "Id": "14555", "Score": "0", "body": "Thanks for you comment!!! I made debug and connection returned the same object_id so I think yes this object is shared. \n\"In add_response_method, it is unnecessary to pass 'http_response' as an argument\" => user can define method name if he want to use different one. Also I can't defind http_response instance method on ActiveResource::Base because result of find and get methods can be array or even hash." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T17:13:58.300", "Id": "14566", "Score": "0", "body": "@Fivell, what difference does it make if `find` and `get` return arrays, hashes, or some other type of object? Whatever the case, each ActiveRecord model needs a `http_response` method, and the body is the same in each case: `def http_response; @http_response; end`. (That's what `attr_reader` generates for you.) Why do you want to generate this method dynamically *every time* `find` is executed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T17:16:11.200", "Id": "14568", "Score": "0", "body": "I think it is better if you just call the method `http_response`. If the user wants to use a different name, that is what `alias` and open classes are for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T17:18:44.670", "Id": "14569", "Score": "1", "body": "Also, even if you want to make the name of the `http_response` method configurable, you don't need to create a symbol dynamically (using `:\"#{}\"`) on each execution. You can just do something like this: `define_method(method_name) do @__http_response__ end`. Then assign the value with `instance_variable_set(@__http_response__, connection.http_response)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T17:23:18.893", "Id": "14570", "Score": "0", "body": "About the idea of allowing the user to pass a string to define the name of the `http_response` method, note that when the user `require`s your file, `http_response` will automatically be defined. So the best they can do by calling `add_response_method` is to add *another* identical method with a different name. But that's what `alias` is for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T21:36:41.500", "Id": "14585", "Score": "0", "body": "thanks I like idea about define_method! about generating method everytime I don't understand... I just add instance variable to result (result can be array hash or Activeresource object) and reader (with user defined name - argument of add_response_method method )for it, no matter what it is. Can you explain what do you mean exactly ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T21:54:58.700", "Id": "14586", "Score": "0", "body": "@Fivell, I understand now why you want to add a reader to the object returned by `find`. I don't understand how this code could actually work, though, because `class_eval` only works when called on modules and classes. Anyways, when you `class_eval \"attr_reader :method_name\"`, you are defining a method, the same as when you do `def method_name; end`. This is rather inefficient. Even more inefficient is the fact that you are `eval`ing a string. *Every time* you do this, the Ruby parser has to run on that string, and it has to be compiled to bytecode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T21:56:31.737", "Id": "14587", "Score": "0", "body": "I benchmarked, and on my computer (running MRI 1.9.2p290), defining the reader takes 4ms to execute 100 times. In a production application which might use `find` thousands of times per second, this could eat up a measurable % of total CPU time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T21:58:19.190", "Id": "14589", "Score": "0", "body": "If the result can be an Array, Hash, *or* ActiveResource::Base, just define `http_response` on those 3 classes, and then you don't have to keep adding the reader dynamically *every time* `find` is called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T22:03:19.033", "Id": "14590", "Score": "0", "body": "If you really want to keep adding the `http_response` method over and over again every time `find` is called, I found it is 4x faster if you `class_eval` a block rather than a string. Use `to_sym` to convert the method name string to a symbol." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T07:49:22.633", "Id": "14610", "Score": "0", "body": "didn't know that cass_eval faster with block so much, thanks. About http_method. The main idea is to define method in object (anonimous class of object) not in class, so no matter what object will be return from find method it will have method to access its http response (but not all objects of current class). \nyou said that don't know if this code could actually work, though, because class_eval only works when called on modules and classes.\nThis works because object.class_eval works as object.singleton_class for me in ruby 1.9.3 , I don't really know if it's normal, need go deeper in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T07:54:42.377", "Id": "14611", "Score": "1", "body": "OK, I see. I am running Ruby 1.9.2, so that's why it works for you but not for me. If you want to make this code compatible with earlier versions of Ruby, why don't you do something like: `def result.http_response; @__http_response__; end`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T09:53:28.573", "Id": "14619", "Score": "0", "body": "Alex, can you show me trace or something, because I switched my rvm to ruby-1.9.2-p180 and it still works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T09:56:14.730", "Id": "14620", "Score": "0", "body": "even for 1.8.7 \n => #<Net::HTTPOK 200 OK readbody=true> \n1.8.7 :009 > Supplier.get(2).http_response\n => #<Net::HTTPOK 200 OK readbody=true> \n1.8.7 :010 > Supplier.find(2).http_response\n => #<Net::HTTPOK 200 OK readbody=true> \n1.8.7 :011 > Supplier.all.http_response\n => #<Net::HTTPOK 200 OK readbody=true>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T09:57:02.513", "Id": "14621", "Score": "1", "body": "`>> [].class_eval \"attr_reader :http_response\"\nNoMethodError: undefined method `class_eval' for []:Array\n from (irb):1\n from C:/Ruby192/bin/irb:12:in `<main>'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:10:10.923", "Id": "14623", "Score": "0", "body": "oh I noticed it works from rails console and doesn't work from irb. That means that rails do some magic" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:18:42.800", "Id": "14625", "Score": "0", "body": "OK, then it should be fine. Sorry about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:21:29.520", "Id": "14627", "Score": "0", "body": "I'll fix this anyway, in case it will used out of rails" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:29:45.090", "Id": "14629", "Score": "0", "body": "You're welcome! Please let me know if you push changes to GitHub. Also, did you fix the bug I mentioned with `add_response_method`? See the last part of my edited answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:41:44.707", "Id": "14630", "Score": "0", "body": "I didn't notice your last part. Can you show example of code with that you tried to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:47:20.360", "Id": "14632", "Score": "0", "body": "also I found that I can't use alias_method in instance_eval as you wrote.\n1.8.7 :070 > ActiveResource::Base.instance_eval do\n1.8.7 :071 > alias_method :__find__, :find\n1.8.7 :072?> end\nNameError: undefined method `find' for class `ActiveResource::Base'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:54:09.607", "Id": "14633", "Score": "0", "body": "I just tried the same thing. I don't know why `alias_method` doesn't work, but `alias` seems to work fine. Note that with `alias`, you don't need a comma. (It is built in to the language.) So: `alias :__find__ :find`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T10:57:37.920", "Id": "14634", "Score": "0", "body": "@Fivell, just from what I can see here, `add_response_method` contains a classic alias chaining mistake which I have made many times before. Have you tried calling `add_response_method` more than once in the same program on `ActiveResource::Base`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T11:56:04.613", "Id": "14641", "Score": "0", "body": "I tried but can't reproduce infinite loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T14:03:10.097", "Id": "14652", "Score": "0", "body": "An example: `>> class Finder; def self.find; end end\n=> nil\n>> class Finder; def self.add_method; class << self; def find; result = __find__; puts \"hi\"; result; end end end end\n=> nil\n>> Finder.add_method\n=> nil\n>> Finder.add_method\n=> nil\n>> Finder.find\nSystemStackError: stack level too deep\n from C:/Ruby192/lib/ruby/1.9.1/irb/workspace.rb:80\nMaybe IRB bug!!`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T14:03:56.463", "Id": "14653", "Score": "0", "body": "Did you try calling `ActiveResource::Base.add_response_method` twice in a row, and then using `ActiveResource::Base.find`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T16:18:26.320", "Id": "14682", "Score": "0", "body": "can reproduce it even if i call add_method more 10 times...very strange.. it's out of my understanding now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T11:55:33.890", "Id": "14738", "Score": "0", "body": "should I remove previously methods before defining them second time?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T16:23:39.010", "Id": "14766", "Score": "0", "body": "The problem is that you are calling `alias_method` *every time* `add_response_method` is called. You should only alias `find` once, when the file is loaded." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T17:06:43.157", "Id": "14769", "Score": "0", "body": "you mean do it globally ? But then it will touch all inherited classes from ActiveResource , even if it not needed .. Is it good ? I thought that it is very flexible when you can redefine methods with aliases obly for specific classes... but when you showed me this problem I don't know how to resolve this conflict." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T17:13:31.840", "Id": "14770", "Score": "0", "body": "what if I'll check before class_eval unless methods.include?(\"original_find\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:43:58.740", "Id": "14780", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2605/discussion-between-alex-d-and-fivell)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T09:03:01.620", "Id": "14903", "Score": "0", "body": "Just one more: hash lookups are faster with a symbol key than with a string. So why don't you use a symbol key for your thread-local variables, rather than a string?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T17:38:55.103", "Id": "14941", "Score": "0", "body": "will do this i nenxt release" } ], "meta_data": { "CommentCount": "34", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T14:42:38.660", "Id": "9269", "ParentId": "9013", "Score": "1" } } ]
{ "AcceptedAnswerId": "9269", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:01:15.360", "Id": "9013", "Score": "3", "Tags": [ "ruby", "multithreading", "ruby-on-rails", "thread-safety", "library-design" ], "Title": "Activeresource-response gem" }
9013
<p>Is my destructor correct? Does it properly deallocate the subtrees?</p> <pre><code>#ifndef HEADER_GUARD__TREE #define HEADER_GUARD__TREE #include &lt;deque&gt; namespace Sandbox { class Node { public: Node(); Node( Node* parent ); virtual ~Node(); Node* GetFirstChild(); Node* GetChild( int index ); Node* GetLastChild(); void AppendChild( Node* child ); void AddChild( Node* child ,int index ); void RemoveChild( int index ); int GetIndex() { return _index; } void SetIndex( unsigned int index ) { _index = index; }; protected: private: Node* _parent; int _index; std::deque&lt;Node*&gt;* _children; }; } #endif // HEADER_GUARD__TREE Node::Node(): _parent(NULL), _index(NULL), _children(NULL){ _children = new std::deque&lt;Node*&gt;; _index = 0; } Node::Node( Node* parent ): _parent(parent), _index(NULL), _children(NULL){ _children = new std::deque&lt;Node*&gt;; _index = 0; _parent-&gt;AppendChild( this ); } Node* Node::GetFirstChild(){ return _children-&gt;front(); } Node* Node::GetChild( int index ){ return _children-&gt;at(index); } Node* Node::GetLastChild() { return ( _children-&gt;back() ); } void Node::AppendChild( Node* child ) { _children-&gt;push_back( child ); unsigned int index = _children-&gt;size(); child-&gt;SetIndex( index ); } void Node::AddChild( Node* child ,int index ) { std::deque&lt;Node*&gt;::iterator i = _children-&gt;begin(); i = i + index; _children-&gt;insert( i, child ); child-&gt;SetIndex( index ); } void Node::RemoveChild( int index ) { std::deque&lt;Node*&gt;::iterator i = _children-&gt;begin(); i = i + index; _children-&gt;at(index)-&gt;~Node(); _children-&gt;erase( i ); } Node::~Node() { _parent = NULL; _index = 0; for(int i = 0; i &gt;= _children.size(); i++ ) { _children-&gt;at(index)-&gt;~Node(); } _children-&gt;clear(); delete _children; } </code></pre>
[]
[ { "body": "<p>This is not real C++ code.<br>\nThis is C written with a couple of classes.</p>\n\n<p>Pointers are dangerous and should rarely be used in code. C++ has moved away from C in this regard over the last decade and all pointers should be either wrapped in a smart pointer or be part of a container structure.</p>\n\n<p>For this a technique called RAII has been introduced. This is the concept that creation and destruction of an object are linked within the objects lifetime thus allowing you to control resources even in the face of exceptions.</p>\n\n<p>There are a couple of ways to fix the code.<br>\nThe simplest technique is to just use std::unique_ptr (or std::auto_ptr if you are using C++03).</p>\n\n<pre><code> Node( Node* parent );\n</code></pre>\n\n<p>Are you passing ownership of the parent?<br>\nNo. You have a seprat constructor for no parent and ownership is not being passed as a result you should pass the parent by reference (if it has a parent it must not be NULL and must exist).</p>\n\n<pre><code> Node( Node&amp; parent );\n</code></pre>\n\n<p>All these methods that return pointer.<br>\nShould they?</p>\n\n<pre><code> Node* GetFirstChild();\n Node* GetChild( int index );\n Node* GetLastChild();\n</code></pre>\n\n<p>If there is a possibility of NULL then yes, otherwise return a reference. </p>\n\n<p>Here you are adding a child:</p>\n\n<pre><code> void AppendChild( Node* child );\n void AddChild( Node* child ,int index );\n</code></pre>\n\n<p>But there is no indication you are passing ownership. The person reading the code has to know how the internals of how your class works. Otherwise they do not know if the pointer passed should be dynamically allocated or not. You need to make this knowledge explicit in the interface. Here I would pass a unique_ptr to indicate that you are passing ownership of the pointer into the node.</p>\n\n<p>OK. Parent is allowed to be a pointer.</p>\n\n<pre><code> Node* _parent;\n</code></pre>\n\n<p>You do not own the object and it is possible to be NULL. There is no responsibility for this node to clean up its parent.</p>\n\n<p><code>_children</code> should not be a pointer. It should be an object. Thus allows automatic cleanup and no requirement to manually create it. Also this simplifies the copy construction and assignment operator (that you have currently failed to define).</p>\n\n<p>Secondly the container should not be holding pointer. Here you have an option either it should be a container of smart pointers, or it should be a container designed specifically to hold ownership of pointers (so that it can be done safely).</p>\n\n<pre><code> // Option 1:\n std::deque&lt;std::uniqur_ptr&lt;Node&gt;&gt; _children;\n\n // Option 2:\n boost::ptr_deque&lt;Node&gt; _children;\n</code></pre>\n\n<p>Personally I prefer option 2. As the contain provides access to the pointers as if they were normal objects. This makes writing functors and the interacting with the standard algorithms much easier.</p>\n\n<p>Also I would question the use of deque over vector but that is a minor detail.\n };\n}</p>\n\n<h3>Secondary Comments:</h3>\n\n<p>Do initialization in the initialization list. You sort of try to NULL everything in the initialization list. It is best to actually initialize them and have an empty body.</p>\n\n<pre><code>Node::Node(): _parent(NULL), _index(NULL), _children(NULL){\n ^^^^ OK ^^^^ Questionable ^^^^^^^^ Should be an object\n\nNode::Node( Node* parent ): _parent(parent), _index(NULL), _children(NULL){\n ^^^^^^ OK ^^^^ Questionable\n</code></pre>\n\n<p>In the constructor that takes a parent you don't check your input for NULL</p>\n\n<pre><code>// If somebody passes a NULL parent then this is no good.\n_parent-&gt;AppendChild( this );\n</code></pre>\n\n<p>The use of your functions should be consistent.</p>\n\n<p>Getting the first and last children can be badly defined if the node has no children. But the generic GetChild() function will throw an exception if you try and retrieve a child from an invalid index. These two different behaviors makes using your code hard to be consistent. I would change these so that they all or none throw an exception.</p>\n\n<pre><code>Node* Node::GetFirstChild(){\n return _children-&gt;front();\n}\nNode* Node::GetLastChild() {\n return ( _children-&gt;back() );\n}\nNode* Node::GetChild( int index ){\n return _children-&gt;at(index);\n}\n</code></pre>\n\n<p>Manually calling the destructor is wrong here:</p>\n\n<pre><code>_children-&gt;at(index)-&gt;~Node();\n</code></pre>\n\n<p>Unless you allocated the memory in some other way the used 'Placement New' you should not be calling the destructor manually. But nothing in your interface indicates that. So this should be a normal call to delete.</p>\n\n<pre><code>delete _children-&gt;at(index);\n</code></pre>\n\n<p>When inserting a child into the middle is it intentional to only set the index of the inserted child?</p>\n\n<pre><code>void Node::AddChild( Node* child ,int index ) {\n std::deque&lt;Node*&gt;::iterator i = _children-&gt;begin();\n i = i + index;\n _children-&gt;insert( i, child );\n\n // You set this node\n // But what about the nodes from index+x to the end.\n // Currently their internal index is unchanged.\n // This could be intentional but it is hard to tell without a comment.\n child-&gt;SetIndex( index );\n}\n</code></pre>\n\n<h3>I would try something like this:</h3>\n\n<pre><code>#ifndef HEADER_GUARD__TREE\n#define HEADER_GUARD__TREE\n\n#include &lt;boost/ptr_container/ptr_deque.hpp&gt;\n\nnamespace Sandbox {\n class Node;\n class Node {\n public:\n Node();\n // Removed the constructor that passes a parent\n // this has problems when you need to define who owns the object.\n // Thus safer to just remove the interface.\n virtual ~Node() {}\n\n Node&amp; GetFirstChild();\n Node&amp; GetChild( int index );\n Node&amp; GetLastChild();\n\n Node&amp; AppendChild(std::auto_ptr&lt;Node&gt; child );\n Node&amp; AddChild(std::auto_ptr&lt;Node&gt; child ,int index );\n void RemoveChild( int index );\n\n int GetIndex() { return _index; }\n void SetIndex( unsigned int index ) { _index = index; };\n protected:\n\n private:\n Node* _parent;\n int _index;\n boost::ptr_deque&lt;Node&gt; _children;\n };\n}\n\n#endif // HEADER_GUARD__TREE\n\nusing namespace Sandbox;\n\nNode::Node()\n : _parent(NULL)\n , _index(0)\n{\n}\n\n// All node child node access fails with an exception if the child is not there.\n// Thus we always return a reference to the node\nNode&amp; Node::GetFirstChild()\n{\n return _children.at(0);\n}\n\nNode&amp; Node::GetChild( int index )\n{\n return _children.at(index);\n}\n\nNode&amp; Node::GetLastChild()\n{\n return _children.at(_children.size() - 1);\n}\n\n// Inserting a node will return a reference to the node after insertion.\n// The nodes are passed by std::auto_ptr to indicate transfer or ownership into the tree\n// Note an empty auto_ptr inserted into the boost_deque will result in an exception so\n// the node must have been created.\nNode&amp; Node::AppendChild(std::auto_ptr&lt;Node&gt; child )\n{\n _children.push_back( child );\n unsigned int index = _children.size();\n\n _children[index].SetIndex(index);\n return _children[index]; \n}\n\nNode&amp; Node::AddChild(std::auto_ptr&lt;Node&gt; child ,int index )\n{\n boost::ptr_deque&lt;Node&gt;::iterator i = _children.begin();\n i = i + index;\n\n _children.insert( i, child );\n _children[index].SetIndex( index );\n return _children[index];\n}\n\nvoid Node::RemoveChild( int index )\n{\n boost::ptr_deque&lt;Node&gt;::iterator i = _children.begin();\n i = i + index;\n\n _children.erase( i );\n}\n// Destruction is done automatically no code here.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T01:54:18.573", "Id": "14165", "Score": "0", "body": "really long answer so give me a minute to review but it looks awesome so far" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T01:55:50.023", "Id": "14166", "Score": "0", "body": "the constructor taking a parent is there so i can assign a node to a given parent" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:01:31.607", "Id": "14168", "Score": "0", "body": "// You set this node\n // But what about the nodes from index+x to the end.\n // Currently their internal index is unchanged.\n // This could be intentional but it is hard to tell without a comment. \n \nCompletely Unintentional" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:03:50.510", "Id": "14169", "Score": "0", "body": "such a seemingly simple problem i might attempt to reimplement as a tree where the tree owns all the children and subchildren to eliminate things like parent pointers and such but idrk" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:08:43.707", "Id": "14170", "Score": "0", "body": "the reason i Null out everything is more of a byproduct of me originally having another constructor that took both a parent and an index but i totally see your point" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:12:31.590", "Id": "14171", "Score": "0", "body": "your also completely right about the way i called the destructor i guess i had a brain fart but none the less it did compile roflmao" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:16:12.710", "Id": "14172", "Score": "0", "body": "the reason i used a deque instead of a vector is that when inserting into the middle its faster than a vector(or at least thats what i was told, srry cant site the reference)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:18:34.940", "Id": "14173", "Score": "0", "body": "so if in your implementation the tree owns the data wouldnt that leak memory because at most the deck is deallocated and not the deck of the subtrees or am i misunderstanding your implementation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:23:00.917", "Id": "14174", "Score": "0", "body": "the reason i used a pointer to a deck instead of the deck itself is in the case of the leaf it doesnt need a deck iirc a deck allocates a non 0 number of objects(basically to avoid reallocing on first use of the deck) and in that case there is extra memory being used for no reason" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:35:44.133", "Id": "14175", "Score": "0", "body": "what you were saying about the index being updated wrong could lead to a case where 2 nodes point to the same index (yikes!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:51:49.993", "Id": "14176", "Score": "0", "body": "ugh... so my insert method will take O(N - index) where n is the number of elements in the deck instead of constant time so to make that run fast i would have to implement some sore of binary search algorithm..... complexity here we come" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:32:46.493", "Id": "14197", "Score": "0", "body": "@WorrynAshtrod: My implementation will not leak. All object will automatically clean up after themselves correctly destroying any dynamically allocated (owned ) object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:37:11.477", "Id": "14198", "Score": "0", "body": "@WorrynAshtrod: The deque supports constant time insertion at the front/back but insertion into the middle is linear. See: http://www.sgi.com/tech/stl/Deque.html and http://stackoverflow.com/q/181693/14065" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:43:03.183", "Id": "14199", "Score": "0", "body": "@WorrynAshtrod: Worrying about the leaf not needing to hold children makes your code ten times more complicated. And the saving of space will be about 8 bytes (three pointers in deque - the pointer you are adding to point the deque => 12 - 4 = 8). Not a good trade." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:44:21.310", "Id": "14200", "Score": "0", "body": ".. Cont: If you really want to do that optimization I would wrap the children in their own class to handle the dynamic allocation. Its called the [`Seporation of Concerns`](http://en.wikipedia.org/wiki/Separation_of_concerns) This basically means a class handles resource management or business logic **NOT** both. Applied to this case it means the `Node` class handles the tree and its interaction you need a seprate class to manage the resources associated with dynamic memory management. A simple rule of thumb: A class should contain no more than **ONE** owned pointer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:52:36.943", "Id": "14201", "Score": "0", "body": "@WorrynAshtrod: The most important thing is to learn how to write code in a C++ style. This mean no RAW owned pointers in your class. Read about the concept of RAII. All owned pointers should be wrapped inside a smart pointer (or container) type class. A good place to start reading is std::shard_pointer/std::unique_ptr etc" } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T00:35:56.373", "Id": "9020", "ParentId": "9015", "Score": "3" } }, { "body": "<p>One thing Loki Astari hasn't covered is <a href=\"http://www.parashift.com/c++-faq-lite/const-correctness.html\" rel=\"nofollow\">const correctness</a>, which your code is sorely lacking. You should make anything that isn't going to change <code>const</code>, and mark all non-static member functions that don't modify the object they operate on as <code>const</code>, too.</p>\n\n<p>For example, the declaration <code>Node( Node* parent );</code> should actually be <code>Node(Node const* parent);</code>, and the definition <code>int GetIndex() { return _index; }</code> should be <code>int GetIndex() const { return _index; }</code>.</p>\n\n<p>Further, I'm not sure making <code>_index</code> private is all that good an idea. Are these nodes going to be used by one class, or many? If only one class needs to be aware of them, you could choose to make them a nested class and expose more of them. It probably won't matter for performance after inlining, though. On the other hand, I see no reason at all to keep <code>_index</code> around, as it is only ever set to 0 when an instance is created, and then never touched again (until the destructor, but that's mostly redundant).</p>\n\n<p>You should also watch out for variables that start with an underscore: if the underscore is followed by a copital letter, the name is reserved, and you should not use it. If you insist on marking your member variables somehow, consider a <code>m_</code> prefix or an underscore suffix.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T17:28:58.257", "Id": "9047", "ParentId": "9015", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T22:14:00.380", "Id": "9015", "Score": "3", "Tags": [ "c++", "memory-management", "tree" ], "Title": "Tree Node class - deallocation in the destructor" }
9015
<p>I wrote a program to copy a <code>.doc</code> template, add some text to it, then save and close it. I have to do this many times, and saving and closing a word document is slow. I decided to use multi-threading, but I'm a noob at this stuff and just wrote what came to me. Any feedback would be greatly appreciated (on any aspect, not just the multi-threading).</p> <p>Here is my code for a task:</p> <pre><code>public Task { public string Value; public bool HasRun; public Task(string value) { Value = value; HasRun = false; } } </code></pre> <p>I create a list of Tasks that is a class level variable, accessible by all threads:</p> <pre><code>Tasks = db.table.select(a =&gt; new Task(a.value)).ToList(); </code></pre> <p>Next, I run the following in each thread:</p> <pre><code>while(tasks.Any(a =&gt; a.HasRun == false)) { var value = ""; lock(tasks) { var task = tasks.Where(a =&gt; a.HasRun == false).First(); value = task.Value; task.HasRun = true; } CreateNewDocumentAppendValueAndSave(value); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T23:32:34.527", "Id": "14161", "Score": "0", "body": "Are you sure you can't do this inside Word with MailMerge? It's not (even close to) limited to inserting addresses. If memory serves, you can use MailMerge to insert virtually anything from a database, for example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T00:13:14.373", "Id": "14162", "Score": "2", "body": "Instead of `x == false`, you can use `!x`. It's more clear in my opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T00:37:29.387", "Id": "14163", "Score": "2", "body": "Was your aim with multi threading to un-freeze the GUI of the app or was it to run the tasks faster by doing multiple tasks at the same time?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T00:41:46.753", "Id": "14164", "Score": "0", "body": "What version of .Net are you using?" } ]
[ { "body": "<p>Until we know your answers to Alex and svick's questions, here's a recommendation I have. I would change your loop slightly to this so that you only get the next task to run once per loop instead of twice.</p>\n\n<p>I also normally name my variables used in LINQ expressions based on the variable being iterated through, so in this loop I've also renamed the a to t. I find it easier to read when the inner variable reflects what the outer variable is.</p>\n\n<pre><code>var task = tasks.FirstOrDefault(t =&gt; !t.HasRun);\nwhile (task != null)\n{\n var value = \"\";\n lock (tasks)\n {\n value = task.Value;\n task.HasRun = true;\n }\n\n CreateNewDocumentAppendValueAndSave(value);\n\n task = tasks.FirstOrDefault(t =&gt; !t.HasRun);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T12:26:42.027", "Id": "9040", "ParentId": "9019", "Score": "0" } }, { "body": "<p>Let the framework do multithreading for you:</p>\n\n<pre><code>List&lt;string&gt; tasks = new List&lt;string&gt;();\nforeach (string value in db.table.select(a =&gt; a.value))\n{\n tasks.Add(Task.Factory.StartNew(() =&gt; CreateNewDocumentAppendValueAndSave(value)));\n}\nTask.WaitAll(tasks.ToArray());\n</code></pre>\n\n<p>Where <code>Task</code> is <code>System.Threading.Tasks.Task</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T15:59:07.543", "Id": "15087", "Score": "0", "body": "This is very interesting, I was not aware of this method, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T15:32:05.193", "Id": "9372", "ParentId": "9019", "Score": "1" } } ]
{ "AcceptedAnswerId": "9372", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T23:05:40.573", "Id": "9019", "Score": "2", "Tags": [ "c#", "multithreading" ], "Title": "Tips on my multi-threading intuition?" }
9019
<p>I'm interested in finding the most elegant and 'correct' solution to this problem. I'm new to JS/PHP and I'm really excited to be working with it. The goal is to compare the size of a given image to the size of a 'frame' for the image (going to be a <code>&lt;div&gt;</code> or <code>&lt;li&gt;</code> eventually) and resize the image accordingly. Users will be uploading images of many sizes and shapes and there are going to be many sizes and shapes of frames. The goal is to make sure that any given image will be correctly resized to fit any given frame. Additionally, images will be cropped with <code>overflow:hidden;</code> so they'll never be distorted. Final implementation will be in PHP, but I'm working out the logic in JS. Here's what I have: </p> <pre><code>//predefined variables generated dynamically from other parts of script, these are example values showing the 'landscape in landscape' ratio issue var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300; //check image orientation if ( $imageHeight == $imageWidth ) { var $imageType = 1; // square image } else if ( $imageHeight &gt; $imageWidth ) { var $imageType = 2; // portrait image } else { var $imageType = 3; // landscape image }; //check frame orientation and compare to image orientation if ( $height == $width) { //square frame if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) { $deferToHeight = true; } else { $deferToHeight = false; }; } else if ( $height &gt; $width ) { //portrait frame if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) { $deferToHeight = true; } else { if (($imageHeight / $height) &lt; 1) { $deferToHeight = true; } else { $deferToHeight = false; }; }; } else { //landscape frame if ( ( $imageType === 1 ) || ( $imageType === 2 ) ) { $deferToHeight = false; } else { if (($imageWidth / $width) &gt; 1) { $deferToHeight = true; } else { $deferToHeight = false; }; }; }; //set values to match (null value scales proportionately) if ($deferToHeight == true) { //defer image size to height of frame $imageWidth = null; $imageHeight = $height; } else { //defer image size to width of frame $imageWidth = $width; $imageHeight = null; }; </code></pre> <p>I've tested it with a bunch of different values and it <em>works</em>, but I have a suspicion that I could have implemented a much more elegant solution. What could I have done better?</p>
[]
[ { "body": "<p><em>Note: I will be referring to each top level commit as a section.</em></p>\n\n<p>First off, in section 3: </p>\n\n<pre><code>if ($imageHeight / $height) &lt; 1) {\n $deferToHeight = true;\n} else {\n $deferToHeight = false;\n}\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>$deferToHeight = ($imageHeight &lt; $height);\n</code></pre>\n\n<p>Next, we can reorder section 3 into:</p>\n\n<pre><code>if ( $imageType === 1 ){\n if ( $height == $width ) { //square frame\n $deferToHeight = true;\n } else if ( $height &gt; $width ) { //portrait frame\n $deferToHeight = true;\n } else { //landscape frame\n $deferToHeight = false;\n }\n} else if //... etc\n</code></pre>\n\n<p>which will allow us to then condense it further into:</p>\n\n<pre><code>if($imageType === 1){\n $deferToHeight = ($height &gt;= $width);\n} else if ($imageType === 2){\n $deferToHeight = ($height &gt; $width &amp;&amp; $imageHeight &lt; $height) \n} else if ($imageType === 3){\n $deferToHeight = ($height &gt;= $width || $imageWidth &gt; $width)\n}\n</code></pre>\n\n<p>Now let us merge section 2 and 3 and Voilà!</p>\n\n<pre><code>var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300;\n\nif ( $imageHeight == $imageWidth ) {\n var $deferToHeight = (height &gt;= width);\n} else if ( $imageHeight &gt; $imageWidth ) {\n var $deferToHeight = ($height &gt; $width &amp;&amp; $imageHeight &lt; $height) \n} else {\n var $deferToHeight = ($height &gt;= $width || $imageWidth &gt; $width)\n}\n\n//And lets even make the last section a little shorter:\n$imageWidth = ($deferToHeight ? null : $width);\n$imageHeight = ($deferToHeight ? $height : null);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T15:42:42.793", "Id": "14194", "Score": "0", "body": "Thank you, this looks really good. I'll need to play with to really understand it. Quick question, by setting a variable to `($height > $width)` you're effectively building a boolean test?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T16:30:08.643", "Id": "14196", "Score": "0", "body": "How would you account for cases in which the ratio of the image width to the frame width is greater than that of the image height to the frame height? For example, in the supplied values we end up with an image that fills the frame horizontally, but not vertically. In those cases, we must defer to the height. If I'm reading your version correctly, we'll end up deferring to the width." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T17:38:17.250", "Id": "14203", "Score": "0", "body": "Yes. `if(x > y){ a = true } else { a = false }` is the same as `a = (x > y)`. \n\nAs for the width issue, I do believe you are correct. Either way, my version generates the same result as your version, so something is wrong with the general formula. See my [second answer](http://codereview.stackexchange.com/a/9048/10797) for a different approach to this problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T05:36:45.817", "Id": "9025", "ParentId": "9022", "Score": "1" } }, { "body": "<p>If we move past rewriting the boolean expressions and instead rework the formulas, I think we can get something a little easier to manage. </p>\n\n<p>If I understand correctly, your goal is to have the image <em>cover</em> the frame. That is to say, for the frame to be filled and the image cropped.</p>\n\n<p>In that case, All we need to do is scale the image to the frame.</p>\n\n<pre><code>var imageHeight = 150, imageWidth = 310, height = 240, width = 300;\n\n//Find the larget discrepancy between frame size and corresponding image size\nvar scaleRatio = Math.max( height/imageHeight, width/imageWidth );\n\n//Apply the scale to the whole image.\nimageHeight *= scaleRatio;\nimageWidth *= scaleRatio;\n</code></pre>\n\n<p>If instead your desire it to have the image <em>fit</em> in the frame, then all we need to do is replace <code>Math.max</code> with <code>Math.min</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T17:31:59.347", "Id": "9048", "ParentId": "9022", "Score": "2" } } ]
{ "AcceptedAnswerId": "9048", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T02:25:25.000", "Id": "9022", "Score": "3", "Tags": [ "javascript" ], "Title": "Most elegant image to image frame comparison algorithm" }
9022
<p>I need your opinion. Which way do you think is right?</p> <p>The definition of <code>message</code> in this code bothers me because it is a single method that has two separate behaviors. Depending on how many arguments are passed the method will do different things--that stinks. </p> <p>On the other hand, calling <code>message</code> in the block just feels right. It is subtle. But the difference of assigning the message with or without the <code>=</code> seems more significant than it should. I feel guilty for really wanting to code this way.</p> <p>Here's a code example:</p> <pre><code>class Queue attr_accessor :id def initialize(id, &amp;block) if block_given? instance_eval(&amp;block) end end def message=(value) @message = value end # if no value is given then it reports the value def message(value=nil) value.nil? ? @message : @message = value end end Queue.new :test_queue do message "This is a test" end </code></pre> <p>Alternatively, I could use another method for it.</p> <pre><code>set_message "This is a test" </code></pre> <p>This also doesn't have the same effect.</p> <p>Opinions? Other options?</p>
[]
[ { "body": "<p>It looks like you're building a small <a href=\"http://en.wikipedia.org/wiki/Domain-specific_language\" rel=\"nofollow\">DSL</a>, in which event <code>message \"Hello\"</code> is analogous to, say, Rails' <code>belongs_to :user</code>. The difference is that while <code>belongs_to</code> is only, in a sense, a setter (it can't be called without an argument, and doesn't return any useful value), you've built <code>message</code> as a getter and a setter.</p>\n\n<p>I think this is about context. In your example:</p>\n\n<pre><code>Queue.new :test_queue do\n message \"This is a test\"\nend\n</code></pre>\n\n<p>..the use of <code>message</code> feels \"right.\" But in this example, it doesn't:</p>\n\n<pre><code>q = Queue.new :test_queue\n\nq.message \"This is a test\"\n</code></pre>\n\n<p>..at least not as much. <code>q.message = \"...\"</code> makes more sense here.</p>\n\n<p>You could just leave it as-is, i.e. allow assignment both ways, using whichever you prefer and letting others use whichever they prefer. The other option would be to make it work one way inside the constructor block and another way on an instance object. <a href=\"http://www.themomorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-part-2-line-by-line-with-machinist-rails\" rel=\"nofollow\">Here's an article</a> that's relevant to this approach, with an apropos shout-out to Factory Girl, which itself contains a great DSL.</p>\n\n<p>Hope that helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T22:06:34.287", "Id": "14219", "Score": "0", "body": "it is different than belongs_to but I can see your point from that perceptive. `message` isn't a class method that defines instance variables. The block here is used to help build the Queue object. Much like FactoryGirl (as you pointed out) or EventMachine or Mail. I think that you answered with that you don't mind if the method does both." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T06:17:54.017", "Id": "9031", "ParentId": "9023", "Score": "2" } }, { "body": "<p>If it's a queue, wouldn't <code>queueMessage</code> and <code>getNextMessage</code> be more appropriate names for methods?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T14:47:36.367", "Id": "14190", "Score": "0", "body": "I feel that a short name like `message` is more Rubyish. `queueMessage` and `getNextMessage` would be typical for Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T15:16:02.353", "Id": "14193", "Score": "0", "body": "IMHO, function names should communicate their purpose in any language. Just because you write Ruby, you shouldn't call a function \"disk\" if its purpose is \"formatDisk\", \"file\" if \"deleteFile\" etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T22:16:02.060", "Id": "14221", "Score": "0", "body": "@Lars-Erik I think that ruby's ability to use '=' in the method definition for `message` is equivalent to using getMessage and setMessage in java. To a ruby programmer get is without and set is with the '='. So, it seems, like me, you would cringe when message() returns is the getter and message(\"something\") is the setter. This pattern feels more jQuery-like. I am torn." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:10:11.143", "Id": "14232", "Score": "0", "body": "Then it should at least be consistent. If you don't pass it a value, set the private to nothing. Anything else is error prone. So `q.message = \"Hello\"` and `whatever = q.message()` exclusively, or if you really want to do `q.message(\"x\")` and `q.message(nil)`, set the message to nil in case 2. (Although, I don't get the feeling this is a queue by this example. ;) )" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T10:18:08.157", "Id": "9035", "ParentId": "9023", "Score": "1" } }, { "body": "<p>One solution is to make your syntax situational. It does seem odd in ruby to collapse your accessor and setter into one method, but you only want that behavior in certain specific situations.</p>\n\n<p>So suppose you have one of these:</p>\n\n<pre><code>class AccessorMultiplexer\n\n def initialize(target)\n @target = target\n end\n\n def method_missing(method, *args)\n method = \"#{method}=\" unless args.empty?\n @target.send method, *args\n end\n\nend\n</code></pre>\n\n<p>This doodad can wrap any object, receive a method like <code>#message</code>, and invoke either <code>#message</code> or <code>#message=</code> on the object that it wraps, situationally, based on criteria like \"are there arguments?\"</p>\n\n<p>So now you can write your Queue with normal getters and setters (freeing you to use <code>attr_accessor</code> for your message), and use the multiplexer only when you want that fancy syntax, like in your <code>initialize</code> block:</p>\n\n<pre><code>class Queue\n attr_accessor :id, :message\n\n def initialize(id, &amp;block)\n if block_given?\n AccessorMultiplexer.new(self).instance_eval(&amp;block)\n end\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T22:09:36.670", "Id": "14220", "Score": "0", "body": "This approach is very interesting. I really didn't think to do it this way. But the issue still exists. If you call `message(\"this is the message\")` do you expect it to assign the message variable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T20:30:05.900", "Id": "14267", "Score": "0", "body": "Well, in normal Ruby, no I don't think you do. But in your DSL, it does make some sense. And as someone else mentioned, there are precedents for it, like the FactoryGirl DSL, or even the now-obsolete ActionMailer DSL in Rails. Depends on what you're doing, but what I like about this solution is that you get to limit the unusual syntax to the areas where you want it, without polluting your general API." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T15:47:17.253", "Id": "9045", "ParentId": "9023", "Score": "2" } } ]
{ "AcceptedAnswerId": "9045", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T03:48:00.477", "Id": "9023", "Score": "0", "Tags": [ "ruby" ], "Title": "Method naming and violating single responsibility" }
9023
<p>I have two threads, called <code>Fun</code> and <code>Boring</code>. Each thread takes the same read-only data and runs some calculations over it and returns a <code>[0.0, 1.0]</code> result.</p> <p>In the current setup, <code>Fun</code> acts as the main thread. It gathers, prepares, and stores the data in a global variable; a memory barrier is used. It then signals (via an event) the <code>Boring</code> thread that there is data to work on. <code>Fun</code> and <code>Boring</code> now both operate on the data.</p> <p>Here is code which illustrates the set up:</p> <pre><code>struct Data { void* someData; } g_data; struct Results { float fun; float boring; } g_results; Fun::Run() { g_data = somePointer; // Prepare data // *memory barrier* SetEvent(dataIsPrepared); g_results.fun = FunCalculate(g_data); WaitForSingleObject(boringComplete); // Do something with g_results } Boring::Run() { WaitForSingleObject(dataIsPrepared); g_results.boring = BoringCalculate(g_data); // *memory barrier* SetEvent(boringComplete); } </code></pre> <p>Is there a "better" way to share data and results? Are there any red flags that stand out?</p> <p>Thanks for any feedback.</p>
[]
[ { "body": "<p>This is correct code. It could go into production.</p>\n\n<p>You don't need the memory barrier because SetEvent will do that for you (if it didn't a <em>lot</em> of code would be broken).</p>\n\n<p>You could change this to use futures (provided that you have some C++ lib that supports them. I don't really know C++ well):</p>\n\n<pre><code>var data = PrepareData();\nvar boringComputation = StartSomeFuture([&amp;data] { ... });\nvar funComputation = ComputeFun(data);\nvar boringResult = boringComputation.ResultAndWait();\n</code></pre>\n\n<p>Much better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T20:06:07.593", "Id": "9027", "ParentId": "9026", "Score": "1" } }, { "body": "<p>Your code is correct. </p>\n\n<p>Now that we got that out of the way, there is always a \"better way\" than using hand-coded synchronization, especially since what you are doing is in fact a producer-consumer pattern. </p>\n\n<p>You can use for example Intel TBB which has some nice concurrent queue data structures (for example <a href=\"http://threadingbuildingblocks.org/files/documentation/a00129.html\" rel=\"nofollow\">concurrent_bounded_queue</a>) in order to easily share data between a producer and a consumer in a thread-safe manner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T20:15:40.940", "Id": "9028", "ParentId": "9026", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T19:56:10.740", "Id": "9026", "Score": "4", "Tags": [ "c++", "multithreading" ], "Title": "Two threads working on shared data" }
9026
<p>I'd just like to get some pointers on my newbie-ish C here. The intention is to have an environment variable provide the "prefix" for any paths this app needs.</p> <p>For example, <code>APP_PREFIX</code> could be <code>/opt/app</code>, a path the app wanted to get could be <code>/etc/app.conf</code>, and so <code>app_path("/etc/app.conf")</code> should return <code>/opt/app/etc/app.conf</code>.</p> <p>I realise this is currently sensitive to leading/trailing slashes; I just wanted to make sure I'm on the right track with this basic stuff. Be as pedantic as you like – from outright bugs down to style and convention.</p> <p>It compiles with no warnings on Mac OS X with <code>gcc -Wall -pedantic ...</code>, and does what I expect it to. On Linux, I had to compile with libbsd, and <code>#include &lt;bsd/string.h&gt;</code> for <code>strlcpy()</code> and <code>strlcat()</code>.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define APP_PREFIX_ENV_VAR "APP_PREFIX" const char * app_path_prefix() { char * env_prefix = getenv(APP_PREFIX_ENV_VAR); if (env_prefix == NULL) { return ""; } else { return env_prefix; } } char * app_path(char * in_path) { const char * prefix = app_path_prefix(); size_t prefix_len = strlen(prefix); size_t out_size = prefix_len + strlen(in_path) + 1; char * out = malloc(out_size); strlcpy(out, prefix, prefix_len + 1); strlcat(out, in_path, out_size); return out; } int main(int argc, char ** argv) { char * path = app_path(argv[1]); printf("result: '%s'\n", path); free(path); return EXIT_SUCCESS; } </code></pre>
[]
[ { "body": "<p>All seems good.</p>\n\n<p>As you mentioned it is sensitive to trailing slash being missing. I would just force that issue and always append one between the prefix and the path. An extra slash will not hurt but a missing one will.</p>\n\n<p>Apart from not using C in the first place :-) all my other issues are simple stylistic ones that only 30% of people would agree (I always divide stylistic camps as 30% Side A, 30% side ~A, 40% don't care).</p>\n\n<p>A tiny bit more white space to make it easier to read. But let me just say your code is not bad in that regards (just slightly less than I would use).</p>\n\n<p>I don't want to recommend any particular style. But I can show you how I would have written it:</p>\n\n<pre><code>// Keep you includes sorted in alphabetical order\n// Here it is not such a big deal but with big projects the list can get big\n// and alphabetical order helps you find things in large lists.\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n#define APP_PREFIX_ENV_VAR \"APP_PREFIX\"\n\nconst char * app_path_prefix()\n{\n char * env_prefix = getenv(APP_PREFIX_ENV_VAR);\n return (env_prefix == NULL)\n ? \"\"\n : env_prefix;\n}\n\nchar * app_path(char * in_path)\n{\n /*\n * Some people really hate this.\n *\n * Others like myself really like lining up the '=' sign\n * Just do it locally with a set of calculations. I find it easier to see\n * both the lhs and the rhs of expression quickly.\n */\n char const* prefix = app_path_prefix();\n size_t prefix_len = strlen(prefix);\n size_t out_size = prefix_len + strlen(in_path) + 1;\n\n /* \n * Dynamically allocated. Released to outside world it is the\n * responsibility of the caller to free this memory\n */\n char * out = malloc(out_size);\n\n strlcpy(out, prefix, prefix_len + 1);\n strlcat(out, in_path, out_size);\n return out;\n}\n\nint main(int argc, char ** argv)\n{\n /* test */\n char * path = app_path(argv[1]);\n printf(\"result: '%s'\\n\", path);\n free(path);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T10:23:00.527", "Id": "14250", "Score": "0", "body": "Thanks! Do feel free to expand on the style points more if you like though, with reasons. Then I can form my own opinions :) Whitespace: blank lines between variable defs and the rest of the function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T15:24:44.157", "Id": "14294", "Score": "0", "body": "@DanB: Added more comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-14T17:53:27.260", "Id": "87555", "Score": "0", "body": "The conditional in `app_path_prefix` can be simplified to `env_prefix ? env_prefix : \"\"`. Don't hesitate to exploit C's generalized Boolean conditionals." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T17:55:24.937", "Id": "9049", "ParentId": "9037", "Score": "3" } } ]
{ "AcceptedAnswerId": "9049", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T10:58:56.113", "Id": "9037", "Score": "4", "Tags": [ "c", "beginner", "strings" ], "Title": "C-string manipulation" }
9037
<p>I recently answered a question on Stack Overflow where someone asked for advice about making a Hash thread-safe. They indicated that performance was important and that there would be a heavy read bias. I suggested a read-write lock, but couldn't find a Ruby implementation available anywhere. The only thing I found was a blog entry from 2007 where someone said they had built one, but the link was broken.</p> <p>I thought that a freely available read-write lock implementation for Ruby would be a good thing for the community, so I tried coming up with one. If you can find any bugs, or see any way to increase performance, please comment!</p> <p>The latest version of this file is <a href="https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb" rel="nofollow">here</a>. There is a forked version <a href="https://github.com/alexdowad/showcase/blob/fair-to-readers/ruby-threads/read_write_lock.rb" rel="nofollow">here</a>, which makes queued readers and writers interleave, rather than preferring to run the queued writers first. I haven't decided whether this is a good idea or not. If I determine that it is better, I will merge the change into 'master'.</p> <pre><code># Ruby read-write lock implementation # Allows any number of concurrent readers, but only one concurrent writer # (And if the "write" lock is taken, any readers who come along will have to wait) # If readers are already active when a writer comes along, the writer will wait for # all the readers to finish before going ahead # But any additional readers who come when the writer is already waiting, will also # wait (so writers are not starved) # Written by Alex Dowad # Thanks to Doug Lea for java.util.concurrent.ReentrantReadWriteLock (used for inspiration) # Usage: # lock = ReadWriteLock.new # lock.with_read_lock { data.retrieve } # lock.with_write_lock { data.modify! } # Implementation note: A goal for this implementation is to make the "main" (uncontended) # path for readers lock-free # Only if there is reader-writer or writer-writer contention, should locks be used require 'atomic' # must install 'atomic' gem require 'thread' class ReadWriteLock def initialize @counter = Atomic.new(0) # single integer which represents lock state # 0 = free # +1 each concurrently running reader # +(1 &lt;&lt; 16) for each waiting OR running writer # so @counter &gt;= (1 &lt;&lt; 16) means at least one writer is waiting/running # and (@counter &amp; ((1 &lt;&lt; 16)-1)) &gt; 0 means at least one reader is running @reader_q = ConditionVariable.new # queue for waiting readers @reader_mutex = Mutex.new # to protect reader queue @writer_q = ConditionVariable.new # queue for waiting writers @writer_mutex = Mutex.new # to protect writer queue end WRITER_INCREMENT = 1 &lt;&lt; 16 # must be a power of 2! MAX_READERS = WRITER_INCREMENT - 1 def with_read_lock while(true) c = @counter.value raise "Too many reader threads!" if (c &amp; MAX_READERS) == MAX_READERS if c &gt;= WRITER_INCREMENT @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if @counter.value &gt;= WRITER_INCREMENT end else break if @counter.compare_and_swap(c,c+1) end end yield while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if c &gt;= WRITER_INCREMENT &amp;&amp; (c &amp; MAX_READERS) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end end def with_write_lock(&amp;b) while(true) c = @counter.value if @counter.compare_and_swap(c,c+WRITER_INCREMENT) @writer_mutex.synchronize do @writer_q.wait(@writer_mutex) if @counter.value &gt; 0 end break end end yield while(true) c = @counter.value if @counter.compare_and_swap(c,c-WRITER_INCREMENT) if c-WRITER_INCREMENT &gt;= WRITER_INCREMENT @writer_mutex.synchronize { @writer_q.signal } else @reader_mutex.synchronize { @reader_q.broadcast } end break end end end end if __FILE__ == $0 # for performance comparison with ReadWriteLock class SimpleMutex def initialize; @mutex = Mutex.new; end def with_read_lock @mutex.synchronize { yield } end alias :with_write_lock :with_read_lock end # for seeing whether my correctness test is doing anything... # and for seeing how great the overhead of the test is # (apart from the cost of locking) class FreeAndEasy def with_read_lock yield # thread safety is for the birds... I prefer to live dangerously end alias :with_write_lock :with_read_lock end require 'benchmark' def test(lock, n_readers=20, n_writers=20, reader_iterations=50, writer_iterations=50, reader_sleep=0.001, writer_sleep=0.001) puts "Testing #{lock.class} with #{n_readers} readers and #{n_writers} writers. Readers iterate #{reader_iterations} times, sleeping #{reader_sleep}s each time, writers iterate #{writer_iterations} times, sleeping #{writer_sleep}s each time" mutex = Mutex.new bad = false data = 0 result = Benchmark.measure do readers = n_readers.times.collect do Thread.new do reader_iterations.times do lock.with_read_lock do mutex.synchronize { bad = true } if (data % 2) != 0 sleep(reader_sleep) mutex.synchronize { bad = true } if (data % 2) != 0 end end end end writers = n_writers.times.collect do Thread.new do writer_iterations.times do lock.with_write_lock do value = data data = value+1 sleep(writer_sleep) data = value+1 end end end end readers.each { |t| t.join } writers.each { |t| t.join } puts "BAD!!! Readers+writers overlapped!" if mutex.synchronize { bad } puts "BAD!!! Writers overlapped!" if data != (n_writers * writer_iterations * 2) end puts result end test(ReadWriteLock.new) test(SimpleMutex.new) test(FreeAndEasy.new) end </code></pre> <p>By the way, the performance results on my machine were:</p> <ul> <li>17.9s for <code>ReadWriteLock</code></li> <li>33.4s for <code>SimpleMutex</code></li> <li>0.8s for <code>FreeAndEasy</code></li> </ul> <p>What are yours?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T13:41:45.833", "Id": "14186", "Score": "0", "body": "Do you have this project at github, can you share the link? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T14:21:17.783", "Id": "14188", "Score": "0", "body": "@AlexKliuchnikau, all the Ruby code which I want to share with others is at http://www.github.com/alexdowad/showcase. I intend to upload this to GitHub after I get input from others who have a deeper knowledge of multithreading than I do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T14:51:37.437", "Id": "14258", "Score": "0", "body": "@AlexKliuchnikau, do you have a multi-core machine? If so, can you try running this file, perhaps with `n_readers`, `n_writers`, `reader_iterations` and `writer_iterations` increased? I only have a single-core machine and think that bugs may be exposed more easily with multiple cores." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T15:48:56.697", "Id": "14262", "Score": "0", "body": "I am reviewing the code, will let you know when don and will show benchmarks for dual code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T15:54:52.653", "Id": "14263", "Score": "0", "body": "Thank you!!! If you need better comments to understand the code, let me know; I can comment and post again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T16:11:02.343", "Id": "50794", "Score": "0", "body": "I don't see any `ensure` stanzas following `yield`. Is this code exception-safe?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T18:27:43.837", "Id": "50816", "Score": "0", "body": "@Avdi, good point! Make that an answer and I'll upvote!" } ]
[ { "body": "<p>I am not an expert in multithreading, but I reviewed the code and here are my thoughts:</p>\n\n<p>The following code leads to deadlock:</p>\n\n<pre><code>l = ReadWriteLock.new\nl.with_write_lock { puts 'passed' }\n</code></pre>\n\n<p>This happens because writer wait for himself to release lock (it increments <code>@counter</code> and then waits if <code>@counter &gt; 0</code>:</p>\n\n<pre><code>while(true)\n c = @counter.value\n if @counter.compare_and_swap(c,c+WRITER_INCREMENT)\n @writer_mutex.synchronize do\n @writer_q.wait(@writer_mutex) if @counter.value &gt; 0 # here\n end\n break\n end\nend\n</code></pre>\n\n<hr>\n\n<p>Looks like increment and decrement for <code>@counter</code> are atomic operations, but <code>change @counter + do operation</code> are not atomic - possible race condition, for example:</p>\n\n<pre><code># let say we have 1 writer working and 1 reader tries to do the job:\nwhile(true)\n c = @counter.value \n raise \"Too many reader threads!\" if (c &amp; MAX_READERS) == MAX_READERS\n if c &gt;= WRITER_INCREMENT # here @counter == WRITER_INCREMENT\n @reader_mutex.synchronize do\n if @counter.value &gt;= WRITER_INCREMENT # here @counter == WRITER_INCREMENT\n # &lt;- but here writer decrements WRITER_INCREMENT and does @reader_q.broadcast (there is no synchronization to protect from this)\n @reader_q.wait(@reader_mutex) # then we wait until writer will broadcast, but it will not happen -&gt; deadlock\n end\n end\n else\n break if @counter.compare_and_swap(c,c+1)\n end\nend\n</code></pre>\n\n<hr>\n\n<p>In your benchmark code I believe you wanted to write something like this</p>\n\n<pre><code>lock.with_write_lock do\n value = data + 1\n sleep(writer_sleep)\n data = value + 1\nend\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>lock.with_write_lock do\n value = data\n data = value + 1\n sleep(writer_sleep)\n data = value + 1 # 2 times assign `value + 1` to `data`\nend\n</code></pre>\n\n<hr>\n\n<p>I think it is too early to do performance tuning of the implementation, but here are results of the benchmark for <code>Intel(R) Core(TM)2 Duo CPU P7570 @ 2.26GHz</code> machine:</p>\n\n<pre><code># MRI 1.9.2 (with global interpreter lock)\n 0.090000 0.140000 0.230000 ( 1.419659)\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.050000 0.090000 0.140000 ( 2.356187)\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Writers overlapped!\n 0.010000 0.030000 0.040000 ( 0.063878)\n\n# MRI 1.9.3 (with global interpreter lock)\n 0.110000 0.100000 0.210000 ( 1.405219)\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.030000 0.070000 0.100000 ( 2.292269)\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Writers overlapped!\n 0.010000 0.010000 0.020000 ( 0.076124)\n\n# Jruby 1.6.5 (with native threads)\n 1.783000 0.000000 1.783000 ( 1.783000)\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 2.484000 0.000000 2.484000 ( 2.484000)\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Writers overlapped!\n 0.151000 0.000000 0.151000 ( 0.151000)\n</code></pre>\n\n<p><em>Note:</em> MRI benchmarks frequently fail with <code>deadlock detected</code> error (or hang in jruby).</p>\n\n<p><em>Sidenote</em>: I think it would be a good idead to put this project into github repo so other people can participate with pull requests/bug reports. I would participated :)</p>\n\n<hr>\n\n<p><strong>UPDATE after fix</strong></p>\n\n<p>I ran benchmarks after your fix and here are the results (I ran it several times and did not encountered a deadlock error):</p>\n\n<pre><code>READ INTENSIVE (80% read, 20% write):\nTesting ReadWriteLock with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.070000 0.080000 0.150000 ( 0.557659)\nWRITE INTENSIVE (80% write, 20% read):\nTesting ReadWriteLock with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.140000 0.080000 0.220000 ( 2.015721)\nBALANCED (50% read, 50% write):\nTesting ReadWriteLock with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.090000 0.080000 0.170000 ( 1.286458)\nREAD INTENSIVE (80% read, 20% write):\nTesting SimpleMutex with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.080000 0.070000 0.150000 ( 2.401325)\nWRITE INTENSIVE (80% write, 20% read):\nTesting SimpleMutex with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.050000 0.090000 0.140000 ( 2.361558)\nBALANCED (50% read, 50% write):\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.070000 0.080000 0.150000 ( 2.357656)\nREAD INTENSIVE (80% read, 20% write):\nTesting FreeAndEasy with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.030000 0.040000 0.070000 ( 0.072458)\nWRITE INTENSIVE (80% write, 20% read):\nTesting FreeAndEasy with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.010000 0.050000 0.060000 ( 0.079889)\nBALANCED (50% read, 50% write):\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.030000 0.030000 0.060000 ( 0.072672)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T14:59:24.907", "Id": "14289", "Score": "0", "body": "Awesome post, thanks!!! Yes, I already posted this project on GitHub, see http://www.github.com/alexdowad/showcase" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T15:03:48.803", "Id": "14290", "Score": "0", "body": "Great point about the deadlock, that was a mistake. It should have been (@counter.value & MAX_READERS) > 0. (In other words, is a reader currently running?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T15:05:16.110", "Id": "14291", "Score": "0", "body": "The second problem you suggested cannot occur, because `@reader_q.broadcast` happens *inside* a `@reader_mutex.synchronize` block. So if the writer finishes while the new reader is already inside that block, the writer will wait until *after* the reader sleeps to do `@reader_q.broadcast`, and the reader will be woken up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T15:06:06.193", "Id": "14292", "Score": "0", "body": "I pushed a fix (I hope?) for the deadlock problem to GitHub. Can you try running the new code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T15:14:39.803", "Id": "14293", "Score": "0", "body": "Sorry, that fix was bad. I am reasoning more carefully about the code and will pus a different fix soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T16:32:37.597", "Id": "14295", "Score": "0", "body": "@AlexD, Ah, yes, you are right, second condition cannot occur." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:21:41.050", "Id": "14298", "Score": "0", "body": "I have been reasoning very carefully about the conditions for a writer to wait, and I am starting to think that I need to use different bits to represent the number of *waiting* and *running* writers (of course, there can only be 1 running)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T21:53:38.940", "Id": "14310", "Score": "0", "body": "Just pushed new code to GitHub (https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb). I don't expect you to use more of your valuable time to keep reviewing code, but if you can, please try running the test (problems are far more likely to show up on your multi-core machine)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T19:54:14.123", "Id": "14407", "Score": "0", "body": "@AlexD, I ran the tests and updated my answer with the results (for MRI 1.9.2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T19:57:44.117", "Id": "14408", "Score": "0", "body": "Thanks!!! I posted a new question for review of the new code... since your edit applies to the new code, I suggest you post it as an answer for the new question, and I will upvote." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T10:14:12.860", "Id": "9103", "ParentId": "9038", "Score": "2" } }, { "body": "<p>Commenting on github version 3d9881516083a831e4bd0e03aa53696a47cb2a08 :</p>\n\n<p>This pattern seems unsafe (or at least the comment is wrong):</p>\n\n<pre><code>@writer_mutex.synchronize do\n # So we have to do another check inside the synchronized section\n # If a writer OR reader is running, then go to sleep\n c = @counter.value\n @writer_q.wait(@writer_mutex) if (c &gt;= RUNNING_WRITER) || ((c &amp; MAX_READERS) &gt; 0)\nend\n</code></pre>\n\n<p>You don't have a mutex protecting @counter, and You are changing it left-and-right. So @counter could change between Your checking of c and going to sleep. I have not analyzed it enough to tell if it is actually a problem.</p>\n\n<p>Also, this code has serious starvation problems. Try printing \"w\" and \"r\" for each iteration of the reader and writer threads. Readers can only do some work after the writers are done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T05:57:49.153", "Id": "14423", "Score": "0", "body": "thanks for reviewing the code! @counter is an `Atomic` (from the excellent `atomic` gem), and it is updated using atomic compare-and-swap operations. Atomic compare-and-swaps are the primary building block used to make code thread-safe *without* locks. You can learn about them here: http://en.wikipedia.org/wiki/Compare-and-swap" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T06:04:01.973", "Id": "14424", "Score": "0", "body": "In this case, we want to sleep if a reader or another writer is running. The danger is that if we checked, found another reader/writer was running, and went to sleep, but the other reader/writer had actually finished running by that time, we could keep sleeping forever. Since this code checks the atomic variable *inside* the synchronized section, the other reader/writer would have to finish *while* we are inside the synchronized section for this to happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T06:06:55.280", "Id": "14425", "Score": "0", "body": "But since both readers and writers call `@writer_mutex.synchronize` after finishing, we are guaranteed the call to `@writer_mutex.signal` will execute *after* this code. We are also guaranteed that the other writer/reader who finishes will see that a writer is waiting, since this code runs *after* a successful atomic swap which increments the counter by WAITING_WRITER." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T06:08:43.490", "Id": "14426", "Score": "0", "body": "About the starvation problem, the concept of a read-write lock is that all readers *must* wait if a writer is running. If readers could work when writers were not done, that would be a bug. You can learn about read-write locks here: http://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock. Please note also that read-write locks are designed to be used where *most* accesses are reads. (If you ran the benchmark, you probably saw that the performance of ReadWriteLock trounces Mutex in read-intensive situations.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T06:16:46.207", "Id": "14427", "Score": "0", "body": "+1 for the suggestion to print \"w\" and \"r\". The problem here is that queued writers are always run *before* queued readers. But if we did it the opposite way, writers could be starved. Maybe this will work: when a writer thread finishes, it will prefer to wake up readers if any are queued. When all reader threads finish, they will prefer to wake up writers if any are queued. What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T06:47:11.383", "Id": "14428", "Score": "0", "body": "I just pushed a new branch called 'fair-to-readers'. It makes waiting readers and writers interleave. At least on this simple benchmark, performance seems unaffected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T09:14:11.253", "Id": "14433", "Score": "0", "body": "With this change, readers can't starve writers, because if at least one writer is waiting, newly-arrived readers will also wait. Once a writer has the chance to run, all waiting readers will be allowed to run. But if a writer is still waiting, any more readers who arrive after that will have to wait, etc. Try running the benchmark code, printing 'w' and 'r' and you will see." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T09:59:09.037", "Id": "14436", "Score": "0", "body": "OK, I read the code, I think it is OK now. The interlock is quite subtle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:23:26.323", "Id": "14437", "Score": "0", "body": "Thanks!!! I added your name to the file... would you prefer your real name, rather than a nick? Also, did you run the test script? If it runs quickly, please try increasing TOTAL_THREADS to a number as large as is practicable... I want to put this to an \"acid test\"!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T00:54:12.820", "Id": "9208", "ParentId": "9038", "Score": "1" } }, { "body": "<p>Here's a simple implementation similar to yours that doesn't require any extra gems added (such as Atomic) - it uses a Queue to easily handle writer/readers signaling, though I suppose this could probably be done faster with a ConditionVariable. Not using extra gems is important in my situation because I need to easily be able to distribute to people who are not ruby-saavy.</p>\n\n<p>It's based off the pseudo-code at:\n<a href=\"http://en.wikipedia.org/wiki/Readers-writers_problem\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Readers-writers_problem</a></p>\n\n<p>It's slightly slower, but doesn't seem to be punished as much by multiple writers. I'd be curious as to how it performs on other systems against your implementation. I believe it to be correct, and it doesn't show any errors according to your test framework.</p>\n\n<pre><code>class LimitWriters\n def initialize\n @noWaiting = Mutex.new\n # Users are either a writer or any number of readers\n @users = Queue.new\n @users.push(true)\n @readers = 0\n @readersSem = Mutex.new\n end\n def with_write_lock\n @noWaiting.lock\n @users.pop\n @noWaiting.unlock\n yield\n @users.push(true)\n end\n def with_read_lock\n prev,curr = nil,nil\n @noWaiting.lock\n @readersSem.synchronize {\n prev = @readers\n @readers += 1\n }\n @users.pop if prev==0\n @noWaiting.unlock\n yield\n @readersSem.synchronize {\n @readers -= 1\n curr = @readers\n }\n @users.push(true) if curr==0\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-12T15:06:48.607", "Id": "21627", "ParentId": "9038", "Score": "2" } } ]
{ "AcceptedAnswerId": "9103", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T11:10:40.767", "Id": "9038", "Score": "5", "Tags": [ "performance", "ruby", "multithreading" ], "Title": "Read-write lock implementation for Ruby" }
9038
<p>I wrote this code using jQuery, but I think it can be improved. Can you provide some feedback?</p> <pre><code> var $i = 1, totalImg = $('.home-featured-bg .absolute div').length, $theWidth = $(window).width(), $theHeight = $(window).height(); $('.home-featured-bg .absolute').css('width',$theWidth * totalImg+'px'); $('.home-featured-bg .absolute .slide,.home-featured-bg .absolute .slide img').css({'width':$theWidth+'px','height' : $theHeight+'px'}); window.setInterval(function(){ $('.events-links a').hide(); if($i == 1) { var $el = $theWidth; }else{ var $el = $theWidth * $i; } if($i &lt; totalImg) { $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000); $i++; $('.events-links a').eq($i - 1).css('display','block'); }else{ $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000); $i = 1; $('.events-links a').eq($i - 1).css('display','block'); } },3000); $(window).resize(function(){ totalImg = $('.home-featured-bg .absolute div').length, $theWidth = $(window).width(), $theHeight = $(window).height(); $('.home-featured-bg .absolute').css('width',$theWidth * totalImg+'px'); $('.home-featured-bg .absolute .slide,.home-featured-bg .absolute .slide img').css({'width':$theWidth+'px','height' : $theHeight}); }); </code></pre>
[]
[ { "body": "<p>Here few suggestion:</p>\n\n<p>in the function you have :</p>\n\n<pre><code>if($i == 1)\n{\n\n var $el = $theWidth;\n}else{\n var $el = $theWidth * $i;\n}\n</code></pre>\n\n<p>could be replaced by a single line:</p>\n\n<pre><code>var $el = $theWidth * $i;\n</code></pre>\n\n<p>and you could modify the following if :</p>\n\n<pre><code>if($i &lt; totalImg)\n{\n $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000);\n $i++;\n $('.events-links a').eq($i - 1).css('display','block');\n}else{\n $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000);\n $i = 1;\n $('.events-links a').eq($i - 1).css('display','block');\n}\n</code></pre>\n\n<p>by extract the $('.events-links a').eq($i - 1).css('display','block'); like this:</p>\n\n<pre><code>if($i &lt; totalImg)\n{\n $('.home-featured-bg .absolute').animate({'margin-left':'-'+$el+'px'},2000);\n $i++;\n}else{\n $('.home-featured-bg .absolute').animate({'margin-left':'0px'},2000);\n $i = 1;\n}\n$('.events-links a').eq($i - 1).css('display','block');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T19:40:46.543", "Id": "9055", "ParentId": "9050", "Score": "2" } }, { "body": "<p>I agree with Nettogrof on the following:</p>\n\n<pre><code>var $el = $theWidth * $i;\n</code></pre>\n\n<p><strong>But you can shorten your code even more by doing the following</strong> (*not tested):</p>\n\n<pre><code>var posNeg = '-';\nif($i &lt; totalImg) {$i = 0; posNeg='';}\n$('.home-featured-bg .absolute').animate({marginLeft:posNeg +$el+'px'},2000);\n$('.events-links a').eq($i).show();\n$i++;\n</code></pre>\n\n<p><strong>More things you can do to improve code:</strong></p>\n\n<p>Set variables for selector objects, makes changes easier, and easier to manage etc., e.g:</p>\n\n<p>Instead of : </p>\n\n<pre><code>$('.myClass').fadeIn();\n$('.myClass').css('color','#ff0000');\n</code></pre>\n\n<p>Use :</p>\n\n<pre><code>var mySel = $('.myClass');\nmySel.fadeIn().css('color','#ff0000');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:55:14.627", "Id": "9084", "ParentId": "9050", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T18:58:00.687", "Id": "9050", "Score": "2", "Tags": [ "javascript", "jquery", "css", "animation" ], "Title": "Periodically sliding images" }
9050
<p>I have created a page that displays markers for local attractions on a Google map. There are a few functions that do similar tasks and I have tried to reduce these by incorporating them into one function, but to no avail. Any suggestions on how to go about doing this?</p> <pre><code>&lt;script type="text/javascript" src="//maps.googleapis.com/maps/api/js? sensor=true&amp;libraries=places"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var map, map1, map2; var infowindow; function initialize() { var feed1 = new google.maps.LatLng(51.5069999695, -0.142489999533); var feed2 = new google.maps.LatLng(40.79445,-74.01558); var feed3 = new google.maps.LatLng(48.858001709, 2.29460000992); map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center:feed1, zoom: 11 }); map1 = new google.maps.Map(document.getElementById('map1'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center:feed2, zoom: 11 }); map2 = new google.maps.Map(document.getElementById('map2'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center:feed3, zoom: 11 }); var request = { location: feed1, radius: 5000 }; var request1 = { location: feed2, radius: 5000 }; var request2 = { location: feed3, radius: 5000 }; infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.search(request, callback); infowindow1 = new google.maps.InfoWindow(); var service1 = new google.maps.places.PlacesService(map1); service1.search(request1, callback); infowindow2 = new google.maps.InfoWindow(); var service2 = new google.maps.places.PlacesService(map2); service2.search(request2, callback); } function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i &lt; results.length; i++) { createMarker(results[i]); createMarker1(results[i]); createMarker2(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ animation: google.maps.Animation.DROP, map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(place.name); infowindow.open(map, this); }); } function createMarker1(place1) { var placeLoc1 = place1.geometry.location; var marker1 = new google.maps.Marker({ animation: google.maps.Animation.DROP, map: map1, position: place1.geometry.location }); google.maps.event.addListener(marker1, 'click', function() { infowindow1.setContent(place1.name); infowindow1.open(map1, this); }); } function createMarker2(place2) { var placeLoc2 = place2.geometry.location; var marker2 = new google.maps.Marker({ animation: google.maps.Animation.DROP, map: map2, position: place2.geometry.location }); google.maps.event.addListener(marker2, 'click', function() { infowindow2.setContent(place2.name); infowindow2.open(map2, this); }); } google.maps.event.addDomListener(window, 'load', initialize); </code></pre> <p></p> <pre><code>&lt;div id="map" style="position:absolute; width: 290px; height: 300px;"&gt;&lt;/div&gt; &lt;div id="map1" style="position:absolute; left:300px; width: 290px; height: 300px;"&gt;&lt;/div&gt; &lt;div id="map2" style="position:absolute; left:600px; width: 290px; height: 300px;"&gt;&lt;/div&gt; </code></pre>
[]
[ { "body": "<p>First off, I find it helpful to use arrays instead of multiple variables. So, how about this:</p>\n\n<pre><code>var map = [], infoWindow = [];\n</code></pre>\n\n<p>Then, lets rename id <code>map</code> to <code>map0</code>. This will allow us to be clever with how we reference it :)</p>\n\n<p>Now we refactor initialize to use the array and reduce repetition:</p>\n\n<pre><code>function initialize(){\n initMap(0, 51.5069999695, -0.142489999533);\n initMap(1, 40.79445,-74.01558);\n initMap(2 , 48.858001709, 2.29460000992);\n}\n\nfunction initMap(ndx, lat, lng){\n var feed = new google.maps.LatLng(lat, lng);\n\n map[ndx] = new google.maps.Map(document.getElementById('map'+ndx), {\n mapTypeId: google.maps.MapTypeId.ROADMAP,\n center: feed,\n zoom: 11\n });\n\n var request = {\n location: feed,\n radius: 5000\n };\n\n infoWindow[ndx] = new google.maps.InfoWindow();\n var service = new google.maps.places.PlacesService(map);\n service.search(request, callback);\n}\n</code></pre>\n\n<p>Finally, lets refactor <code>createMarker</code> to use the arrays as well.</p>\n\n<pre><code>function callback(results, status) {\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n for (var i = 0; i &lt; results.length; i++) {\n createMarker(0, results[i]);\n createMarker(1, results[i]);\n createMarker(2, results[i]);\n }\n }\n}\n\nfunction createMarker(ndx, place) {\n var marker = new google.maps.Marker({\n animation: google.maps.Animation.DROP,\n map: map[ndx],\n position: place.geometry.location\n });\n\n google.maps.event.addListener(marker, 'click', function() {\n infowindow[ndx].setContent(place.name);\n infowindow[ndx].open(map[ndx], this);\n }); \n}\n\ngoogle.maps.event.addDomListener(window, 'load', initialize);\n</code></pre>\n\n<p>Finally, don't forget to rename <code>map</code> to <code>map0</code></p>\n\n<pre><code>&lt;div id=\"map0\" style=\"position:absolute; width: 290px; height: 300px;\"&gt;&lt;/div&gt;\n&lt;div id=\"map1\" style=\"position:absolute; left:300px; width: 290px; height: 300px;\"&gt;&lt;/div&gt;\n&lt;div id=\"map2\" style=\"position:absolute; left:600px; width: 290px; height: 300px;\"&gt;&lt;/div&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T23:39:17.263", "Id": "9070", "ParentId": "9051", "Score": "1" } } ]
{ "AcceptedAnswerId": "9070", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T18:58:34.553", "Id": "9051", "Score": "2", "Tags": [ "javascript", "google-maps" ], "Title": "Displaying markers for local attractions on a Google map" }
9051
<p>I am using Trail Division Method with a pre-calculated list of primes to calculate the prime factorization of <strong>all</strong> numbers less than M (M &lt;= 10^7).</p> <p>I am using an array of vectors of pairs. The format for 10 is as follows:</p> <pre><code>PF[10][0].first = 2 // Base PF[10][0].second = 1 // Exp PF[10][1].first = 5 PF[10][1].second = 1 </code></pre> <p>My approach is <strong>working fine</strong> but it is <strong>too slow</strong>. For M=10^7 it took <strong>36.841 sec</strong> to compute PF of all numbers &lt;=M on my system.</p> <h2>Questions</h2> <ol> <li>Which is the best approach for this question?</li> <li>For my approach what other optimizations can i do?</li> </ol> <h2>My code</h2> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include "math.h" #include "stdio.h" using namespace std; const int lim=45000; const int Max=10000000; char prime[lim]; vector&lt;pair &lt;int,unsigned char&gt; &gt; PF[Max]; void prep() { //Calculation of Prime Numbers for(int i=1;i&lt;lim;prime[i++]=1); for(int i=2;i*i&lt;lim;i++) if(prime[i]) for(int j=i+i;j&lt;lim;prime[j]=0,j+=i); for(int i=2;i&lt;Max;i++) { int num=i; unsigned char pq=0; //Check for powers of 2 while(num%2==0) { pq++; num=num/2; } if(pq&gt;0) PF[i].push_back( make_pair(2,pq) ); int pan=num; //Loop for all primes j such that j*j&lt;num for(int j=3;j*j&lt;=num;j+=2) { if(prime[j]) { pq=0; while(num%j==0) { pq++; num=num/j; } if(pq&gt;0) PF[i].push_back( make_pair(j,pq) ); } } if(num&gt;1) PF[i].push_back( make_pair(num,1) ); } } main() { prep(); } </code></pre> <h2>Timing</h2> <h3>My Code</h3> <pre><code>real 0m36.841s user 0m36.624s sys 0m0.265s </code></pre> <h3>Igor ostrovsky Code</h3> <pre><code>real 0m41.628s user 0m41.390s sys 0m0.265s </code></pre>
[]
[ { "body": "<p>Off the top of my head, once you find a factor, you can look that up in your existing table. That will keep you from having to continue searching for more primes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T18:37:04.763", "Id": "9053", "ParentId": "9052", "Score": "2" } }, { "body": "<p>Instead of storing the full factorization of each integer, just store one of the factors:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nconst int MAX = 10000000;\nint factor[MAX];\n\nvoid precompute()\n{\n for(int i = 1; i &lt; MAX; i++) {\n factor[i] = i;\n }\n\n for(int i = 2; i * i &lt; MAX; i++) if (factor[i] == i) {\n for(int j = i + i; j &lt; MAX; j += i) {\n factor[j] = i;\n }\n }\n}\n\nvector&lt;int&gt; get_factors(int x)\n{\n vector&lt;int&gt; factors;\n while (x &gt; 1) {\n int f = factor[x];\n factors.push_back(f);\n x /= f;\n }\n return factors;\n}\n\nvoid main() {\n precompute();\n vector&lt;int&gt; factors = get_factors(2012);\n\n for(int i=0; i&lt;factors.size(); i++) { \n std::cout &lt;&lt; factors[i] &lt;&lt; \" \";\n }\n std::cout &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Edit: I tested the code and fixed a couple of minor bugs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T16:37:02.517", "Id": "17989", "Score": "0", "body": "it seems you store the biggest factor for an entry in the table. Thus the factors will be found in descending order. If you store the smallest factor, they will be found in ascending order. Valid as well. Advantage? Start your inner loop in `precompute()` from `i*i` - a speedup! Put 2 in all even entries and then skip them, using `j += 2*i` step in the inner loop - a speedup! Separate out the testing of even/odd (test by `n&1`, not `n%2`), have your table twice as small - a speedup!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T18:37:06.417", "Id": "9054", "ParentId": "9052", "Score": "1" } }, { "body": "<p>I tried to use cache ang finished with foolwing code (based on Igor's one):</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n\nusing namespace std;\n\nconst int MAX = 10000000;\nconst int SQRT_MAX = sqrt(MAX);\nint factor[MAX];\n\nstruct Node\n{\n int number;\n Node* prior;\n};\n\nvector&lt;Node&gt; cache(MAX);\n\nvoid precompute()\n{\n for(int i = 1; i &lt; MAX; i++) {\n factor[i] = i;\n }\n\n cache[1].prior = 0;\n cache[1].number = 1;\n\n for(int i = 2; i &lt; SQRT_MAX; i++) {\n if (factor[i] == i) {\n for(int j = i &lt;&lt; 1; j &lt; MAX; j += i) {\n factor[j] = i;\n }\n }\n }\n\n for(int i = 2; i &lt; MAX; i++) {\n int&amp; f = factor[i];\n cache[i].prior = &amp; cache[i/f];\n cache[i].number = f;\n }\n}\n\nNode* get_factors(int x)\n{\n return &amp;cache[x];\n}\n\nint main() {\n precompute();\n\n for (int k = 2; k &lt; MAX; k++) {\n Node* it = get_factors(k);\n while (it != 0) { \n //std::cout &lt;&lt; it-&gt;number &lt;&lt; \" \";\n it = it-&gt;prior;\n }\n //std::cout &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<p>My result is:</p>\n\n<pre><code>sh-3.1$ g++ 1.cpp -O3\nsh-3.1$ time ./a\n\nreal 0m0.900s\nuser 0m0.000s\nsys 0m0.015s\nsh-3.1$\n</code></pre>\n\n<p>Opposed Igor's:</p>\n\n<pre><code>sh-3.1$ time ./a\n\nreal 0m10.313s\nuser 0m0.015s\nsys 0m0.015s\nsh-3.1$\n</code></pre>\n\n<p>With the following main cycle:</p>\n\n<pre><code>int main() {\n precompute();\n\n for (int k = 2; k &lt; MAX; k++) {\n vector&lt;int&gt; factors = get_factors(k);\n\n for(int i=0; i&lt;factors.size(); i++) { \n //std::cout &lt;&lt; factors[i] &lt;&lt; \" \";\n }\n //std::cout &lt;&lt; std::endl;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T06:58:00.323", "Id": "14281", "Score": "0", "body": "(1) Really slick implementation. (2) Why do you print 0 (zero) at the end of each line of output?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T07:22:43.963", "Id": "14282", "Score": "0", "body": "BTW, you can speed this up by about 32% with a very simple modification: Inside `precompute()`, also initialize the entire `cache` array in a single straightforward loop from 1 to MAX. Then `get_factors` simply returns `&cache[x]` without doing any other work. On my system, this improved the runtime from 0.65 seconds to 0.49 seconds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T07:25:01.853", "Id": "14283", "Score": "0", "body": "I forgot to say: Your implementation is the most beautiful prime factorization algorithm I've ever seen. Storing the lists of factors of all the numbers as interwoven linked lists is so cool it blows my mind. I've never seen this before. Did you discover this algorithm yourself or see it elsewhere?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T10:09:22.677", "Id": "14284", "Score": "1", "body": "@ToddLehman, There is an error in code. I missed ` cache[1].number= 1;`. It will print 1 (1 is actually a factor of every number). Hm, if I make the improvement, that you recommend, I become faster than @Ben Voigt, yeaaah! Also, you can see that @Ben Voigt uses same structured cache, storing _index_ of _prior_ number, instead of _pointer_ to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T18:03:18.110", "Id": "14303", "Score": "0", "body": "@Lol4t0: That, and `first` is both the *index* and the actual paired factor itself, and I don't have anything equivalent to your separate `factor` array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T18:07:04.753", "Id": "14304", "Score": "0", "body": "I'm not sure, but I think the factor-walking code in your `main` function may be optimized away. What if you compute the sum of `it->number`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T18:22:36.193", "Id": "14305", "Score": "0", "body": "@BenVoigt, Ahaha, I made an error. Now all became the same :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T21:22:28.020", "Id": "14308", "Score": "0", "body": "@Lol4t0: While it is a factor, 1 is not a prime factor of any number." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T20:14:16.007", "Id": "9060", "ParentId": "9052", "Score": "2" } }, { "body": "<p>On the topic of optimisations:</p>\n\n<ul>\n<li>You're using <code>push_back</code> while not reserving any memory. Are you sure you don't want to reserve some amount you consider safe first?</li>\n<li>You're checking whether something is a multiple of two by using modulo and then division. Your compiler probably optimises this out already, but you could use bitwise-and and a right-shift instead, as long as you know the numbers aren't negative.</li>\n<li>You're multiplying <code>j</code> with itself on every iteration of one of the inner loops. Storing <code>ceil(sqrt(num))</code> is likely to be more efficient.</li>\n<li>Rereading, I see that you're doing the same thing with <code>i</code> in the second loop.</li>\n</ul>\n\n<p>Apart from that, you should probably take a look at the following issues:</p>\n\n<ul>\n<li>Declaring <code>main</code> with no return type is not allowed.</li>\n<li>C headers of the style <code>header.h</code> are deprecated, use <code>cheader</code> now. (For example, <code>cmath</code> instead of <code>math.h</code>.) As Ben Voigt remarks, you're not using anything from many of your includes so you should drop them altogether.</li>\n<li>You've got <code>using namespace std;</code>. While this may be okay for a short program, it does not combine well with global variables, and explicitly qualifying names would make more sense in this case (you only have five names to qualify, anyway).</li>\n<li>The lines that calculate prime numbers are not readable to me as they are. As you can be sure that the body of the loop will always be executed before the increment, you could change it to be <code>for (int j = i+i; j &lt; lim; j += i) prime[j] = 0;</code>, which would do the same thing while making it more readable. A similar thing can be done with the very first loop.</li>\n<li>Splitting this code into functions would help a lot. Seeing as most of your variables are global, the only thing you need to worry about is the function call overhead (which may be non-existent if the function is inlined). In particular, I would move out <code>calculate_primes</code>.</li>\n<li>You're not using <code>pan</code> anywhere, so you shouldn't declare it in the first place.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T20:45:19.827", "Id": "9061", "ParentId": "9052", "Score": "2" } }, { "body": "<p>I did this a while ago, in the interest of reducing ratios of factorials</p>\n\n<pre><code>#include &lt;utility&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt; std::pair&lt;int, int&gt; &gt; factor_table;\nvoid fill_sieve( int n )\n{\n factor_table.resize(n+1);\n for( int i = 1; i &lt;= n; ++i ) {\n if (i &amp; 1)\n factor_table[i] = std::pair&lt;int, int&gt;(i, 1);\n else\n factor_table[i] = std::pair&lt;int, int&gt;(2, i&gt;&gt;1);\n }\n for( int j = 3, j2 = 9; j2 &lt;= n; ) {\n if (factor_table[j].second == 1) {\n int i = j;\n int ij = j2;\n while (ij &lt;= n) {\n factor_table[ij] = std::pair&lt;int, int&gt;(j, i);\n ++i;\n ij += j;\n }\n }\n j2 += (j + 1) &lt;&lt; 2;\n j += 2;\n }\n}\n\nstd::vector&lt;int&gt; factor( int num )\n{\n std::vector&lt;int&gt; factors;\n factors.reserve(30);\n do {\n factors.push_back(factor_table[num].first);\n num = factor_table[num].second;\n } while (num != 1);\n return factors;\n}\n</code></pre>\n\n<p>I believe it will be much faster than yours, because I was able to avoid ever using division (<code>/</code> and <code>%</code>). As a matter of fact, I don't use any multiplies either.</p>\n\n<p>(It's about 6x faster with g++ than the code in the question, and the actual factor generation part is marginally faster, about 10%, than lol4t0's. Returning factors in a <code>std::vector&lt;int&gt;</code> takes 5x as long as the factor generation.)</p>\n\n<p>Test program: <a href=\"http://ideone.com/pt9nu\" rel=\"nofollow\">http://ideone.com/pt9nu</a></p>\n\n<p>Original application:</p>\n\n<ul>\n<li><a href=\"http://ideone.com/Weeg6\" rel=\"nofollow\">http://ideone.com/Weeg6</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:09:45.260", "Id": "14231", "Score": "0", "body": "Hey, I comprehend your idea! It looks very interesting to me. Still the idea is not obviuos from your code -- so one may want your data structure to be explained in more detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:48:05.180", "Id": "14233", "Score": "0", "body": "It seems that your `for( int j` cycle may be further improved by `inc=2`...`j+=inc; inc=6-inc;` trick, so `j2` have to be calculated slightly differently. Also one have to start `j` from 5, and add `j=3` special processing case just like `j=2` special processing case in `factor_table[i] = std::pair<int, int>(2, i>>1);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T10:05:37.007", "Id": "14247", "Score": "0", "body": "@ben .. Thanks for your reply :) .. [link](http://ideone.com/pt9nu) -- In this particular problem 'factor(k).swap(factors);'. will make factors to always store the return value and hence it will have the MAX-1 value after execution .. How can i display factors of some other number ?? . . When i declared factors as 2D vectors i need to use 'factors.push_back(factor(k));'. which is very time consuming .. It is taking 23 sec on my system to run while with 'factor(k).swap(factors);'. it took 8 sec ..\n\n**Edit:**\nwhile with reserving required memory beforehand it took 14 sec" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T15:19:21.613", "Id": "14260", "Score": "2", "body": "@anudeep2011: Looking up the factors from the table I built is extremely fast, there's no need to build a table of vectors of factors. Just call the `factor(int num)` function when you need the factors of `num`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T06:16:06.850", "Id": "14280", "Score": "2", "body": "This method is bloody brilliant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T10:17:12.913", "Id": "14285", "Score": "0", "body": "I think, you shouldn't make `vector<int>` itself. In production code, you can make `forward iterator` that will work without any overhead on array creation" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T21:03:43.550", "Id": "9063", "ParentId": "9052", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T18:13:53.240", "Id": "9052", "Score": "6", "Tags": [ "c++", "optimization", "primes" ], "Title": "Optimization - Prime Factorizations of Numbers <= 10^7" }
9052
<p>I'm creating Sudoku in JS but can't find the way to extract the numbers from the squares. The numbers from the rows and columns are easy to extract but I can't find the way around the squares. According to users input, I'll validate the column, then the row and finally the squares to see if the numbers are being repeated. Is this best practice?</p> <p>Globals: </p> <pre><code> var numIni = 9; //Number of squares per side; var squared = Math.sqrt(numIni); // I'll need this. </code></pre> <p>Column check:</p> <pre><code>function getColumn(){ var num = 30; //USER's INPUT var colNums = []; //numbers IN the column var countCol = num; // column anchor while(countCol &gt; numIni ){ countCol -= numIni } colNums[0] = countCol; for(i=1;i&lt; numIni;i++){ colNums[i]= colNums[i-1]+9; } } </code></pre> <p>Row check:</p> <pre><code>function getRow(){ var num = 50; //USER's INPUT var rowAnchor = (Math.ceil(num/numIni))*numIni-(numIni-1); var rowNums=[rowAnchor]//numbers IN the row for(i=1;i&lt; numIni;i++){ rowNums[i]= rowAnchor+i; } } </code></pre> <p>These last two work, but the squares are killing me. I'm first extracting the anchors, then building the squares and validating the number against that. It's getting quite long. Is there a better way to write this? Is the logic inefficient? If it's right, I'm stuck anyway.</p> <p>Squares check (so far):</p> <pre><code>function getSquare(){ var boxes = []; var boxesAnchor = []; boxes[0]=1; boxesAnchor[0]=1; for(i=0; i&lt; numIni*numIni ; i++){ boxes[i]= squared + ((i-1)* squared )+1; } for(i=0; i&lt; numIni*squared ; i++){ for(j=0; j&lt; squared ; j++){ boxesAnchor[i] = boxes[i]; boxesAnchor[i+j] = boxes[i+j]; boxesAnchor[i+j] = boxes[i+j]; } i +=(numIni-1); } boxesAnchor.clean(undefined);// method added to the Array object } </code></pre>
[]
[ { "body": "<p>As we know, the numbers that could be placed in sudoku cells are limited (1..9). So we can easily make an index to existence of 1 through 9 in each row, column and square.\nConsider we use <code>rowIndex[9][10]</code>, <code>colIndex[9][10]</code> and <code>sqrIndex[9][10]</code> for this purpose. Now checking that putting value <code>v</code> in row <code>x</code> and column <code>y</code> would be like below:</p>\n\n<pre><code>if ( rowIndex[x][v] ) return FAILURE;\nif ( colIndex[y][v] ) return FAILURE;\nvar sqrID = (x/3)*3 + (y/3);\nif ( sqrIndex[sqrID][v] ) return FAILURE;\nreturn SUCCESS;\n</code></pre>\n\n<p>and if <code>SUCCESS</code> is returned we can put that value in the specified cell and update our maps:</p>\n\n<pre><code>rowIndex[x][v] = colIndex[y][v] = sqrIndex[(x/3)*3+(y/3)][v] = 1;\n</code></pre>\n\n<p>P.S: <code>sqrIndex</code> address all squares in row major.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T13:17:36.017", "Id": "14287", "Score": "0", "body": "Can you explain further??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T15:06:50.283", "Id": "14333", "Score": "0", "body": "`rowIndex[i][v]` is 1 if there is a value `v` in `ith` row and 0 otherwise. The same definition stands for `colIndex` and `sqrIndex`. Since there are 9 rows, columns and squares, first index is enough to be 9, but values could be at most 9, so second index should be 10 to cover all values (array indices are 0-based). Square ID is easily obtained by dividing row and column IDs by 3. But I assumed squares as a 1D array, so index of your square in this 1D array is X*3+Y." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:47:24.733", "Id": "9083", "ParentId": "9066", "Score": "3" } }, { "body": "<p>+1 to @saeedn for showing a nice approach to tracking the state of the board in a way that makes checking easy -- I suspect it would involve some <em>major</em> code restructuring from the OP, though the improvement would likely be worth the effort.</p>\n\n<p>That said, here's how getSquares might work within the original approach:</p>\n\n<p>BTW, The (apparent) use of 1-based numbers for the game cells 1-81 vs. 0-80 adds awkwardness as these functions have to keep adjusting for it.</p>\n\n<p>For example, a formula like:</p>\n\n<pre><code>var rowAnchor = (Math.ceil(num/numIni))*numIni-(numIni-1);\n</code></pre>\n\n<p>more cleanly expressed as</p>\n\n<pre><code>var rowAnchor = Math.floor((num-1)/numIni)*numIni +1;\n</code></pre>\n\n<p>would be even cleaner if you didn't have to subtract 1 at the start and add 1 at the end, all just to accommodate a 1-based value range. </p>\n\n<pre><code>function getSquare(){\n var squares = []; \n var rowOfSquares = numIni*squared; // squared?\n // num-1 to account for 1-based range\n var rowAnchor = Math.floor((num-1)/rowOfSquares)*rowOfSquares;\n var colAnchor = Math.floor(((num-1) % numIni) / squared ) * squared;\n\n squareAnchor = rowAnchor + colAnchor + 1; // + 1 to account for 1-based range\n\n\n for (i = 0; i &lt; rowOfSquares ; i += numIni)\n for (j = 0; j &lt; squared; j++)\n square[k] = squareAnchor+i+j;\n}\n</code></pre>\n\n<p>Some final comments: the name <code>squared</code> for the square root made my head hurt. Suggest: <code>root</code> or <code>squareSide</code>. And NOT passing num as an input to these functions or returning the resulting vectors (locals?) added much confusion. I am hoping that these are just artifacts of an attempt to \"clean up\" for code review.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T01:23:49.603", "Id": "9101", "ParentId": "9066", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T23:21:43.783", "Id": "9066", "Score": "2", "Tags": [ "javascript", "gui", "sudoku" ], "Title": "Sudoku boxes count JavaScript" }
9066
<p>I have the following SQL statement that I think could be improved in areas (I believe there may be a way to use where over having, but I'm not sure how and I'm sure there's a way to reference the last updated column in the having clause but I'm unsure how to do it). Any suggestions would be greatly appreciated:</p> <pre><code>/* Show indexes that haven't had statistics updated in two days or more */ select t.name as [Table Name], min(convert(CHAR(11),stats_date(t.object_id,s.[stats_id]),106)) as [Last Updated] from sys.[stats] as s inner join sys.[tables] as t on [s].[object_id] = [t].[object_id] group by t.name having min(convert(CHAR(11),stats_date(t.object_id,s.[stats_id]),106)) &lt; dateadd(day, -1, getdate()) order by 2 desc </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:09:57.213", "Id": "14244", "Score": "1", "body": "Don't you want `max` rather than `min`? Your comment at the top of the code suggest that you want tables whose latest statistics entry is more than two days ago, not whose earliest statistics entry is in that range." } ]
[ { "body": "<p>You can just use the condition in a <code>where</code>, that will filter the single records instead of filtering groups, then you can group the result to avoid duplicates in the result.</p>\n\n<p>You shouldn't convert the date to a string when you are comparing it. When you convert it to a string, you should do that after getting the lowest value, otherwise <code>min</code> will compare the dates as strings and give you the wrong result.</p>\n\n<pre><code>select\n t.name as [Table Name], \n convert(CHAR(11),min(stats_date(t.object_id,s.[stats_id])),106) as [Last Updated]\nfrom\n sys.[stats] as s\n inner join sys.[tables] as t on s.[object_id] = t.[object_id]\nwhere\n stats_date(t.object_id,s.[stats_id]) &lt; dateadd(day, -1, getdate())\ngroup by\n t.name\norder by\n 2 desc\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:00:01.760", "Id": "9081", "ParentId": "9067", "Score": "2" } } ]
{ "AcceptedAnswerId": "9081", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T23:24:50.130", "Id": "9067", "Score": "2", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Statistics updating SQL Query" }
9067
<p>I need multiple read access to some data which can be updated from time to time. I created a class for managing lock-less access to the data. The class uses 2 counters, one for count of the acquired references and another one for the count of released references. The update function replaces the data pointer and then waits for the completion of the previous reads.</p> <p>Can someone with more experience in lock-less programming comment on the correction and performance of the code?</p> <pre><code>template&lt;typename T&gt; inline void IgnorePolicy(T* item) {} template&lt;typename T&gt; inline void DeletePolicy(T* item) { delete item; } template&lt;typename T&gt; inline void ReleasePolicy(T* item) { if(item != NULL) item-&gt;Release(); } template&lt;typename T, void (* DestroyPolicy)(T* item) = IgnorePolicy&gt; class ReadUpdateData { private: volatile int m_acquireCount, m_releaseCount; T* m_data; bool CheckReleaseCount(int limit) //wrap-safe check to see if release count has reached the required limit { int releaseCount = m_releaseCount; return (limit &lt; 0 || releaseCount &gt;= 0) ? limit &lt;= releaseCount : limit &gt;= 0 &amp;&amp; releaseCount &lt; 0; } public: ReadUpdateData() : m_acquireCount(0), m_releaseCount(0), m_data(NULL) {} ~ReadUpdateData() { assert(m_acquireCount == m_releaseCount); DestroyPolicy(m_data); } T* Acquire() { AtomicIncrement(&amp;m_acquireCount); return m_data; } void Release() { AtomicIncrement(&amp;m_releaseCount); } void Update(T* newData) { T* oldData = m_data; while(AtomicCompareExchangePtr(&amp;m_data, newData, oldData) == oldData) oldData = m_data; int acquireCount = m_acquireCount; while(!CheckReleaseCount(acquireCount)) Yield(); DestroyPolicy(oldData); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:10:45.450", "Id": "14223", "Score": "3", "body": "`(limit >= 0) <= (releaseCount >= 0)` ouch. What's wrong with `limit < 0 || releaseCount >= 0` ?" } ]
[ { "body": "<pre><code> bool CheckReleaseCount(int limit) //wrap-safe check to see if release count has reached the required limit \n {\n int releaseCount = m_releaseCount;\n return (limit &gt;= 0) &lt;= (releaseCount &gt;= 0) ? limit &lt;= releaseCount : limit &gt;= 0 &amp;&amp; releaseCount &lt; 0;\n }\n</code></pre>\n\n<p>This has no protection on <code>m_releaseCount</code>. Most threading platforms claim UB if a variable is accessed in one thread while another thread is, or might be, modifying it. So this code is only usable on platforms that have defined semantics for concurrent accesses to aligned volatile integers. Don't you have some kind of <code>AtomicFetch</code> function for just this purpose?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:23:00.483", "Id": "14224", "Score": "0", "body": "I'm sorry, but can you explain what UB stands for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:29:12.657", "Id": "14225", "Score": "0", "body": "But aren't int assignments atomic on 32/64 bit platforms anyway? And m_releaseCount is `volatile`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:29:26.743", "Id": "14226", "Score": "0", "body": "Undefined Behavior. That is, nothing specifically tells you what will happen, so in principle anything can happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:31:51.330", "Id": "14227", "Score": "0", "body": "@Tudor If you know your platform has defined semantics for concurrent accesses to aligned volatile integers, then this isn't an issue. Windows (with either GCC, ICC, or VC) has defined semantics for these accesses on 32-bit and 64-bit x86 platforms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:34:14.760", "Id": "14228", "Score": "0", "body": "I'm only familiar with x86/x64 processors which have atomic reads/writes to aligned memory. I guess that may not be the case on other platforms. I'll add and AtomicFetch function also. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:39:09.357", "Id": "14229", "Score": "0", "body": "@Chris It really doesn't have much to do with the processor. That's just one place it can break. It can break in the compiler (What if the compiler decides to implement your fetch with four byte fetches? Is there some rule that prohibits that?), the memory controller, or god knows where else. Unless you're coding on a platform that guarantees this behavior as a whole, it's not guaranteed behavior. -- You should code an `AtomicFetch` and make sure that does whatever is needed to get an atomic fetch (which may be nothing on your platform)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T15:06:13.893", "Id": "9069", "ParentId": "9068", "Score": "2" } }, { "body": "<p>I'm not an expert, but I this line caught my eye:</p>\n\n<pre><code>volatile int m_acquireCount, m_releaseCount;\n</code></pre>\n\n<p><code>m_acquireCount</code> and <code>m_releaseCount</code> will be part of the <strong>same cache line</strong>!</p>\n\n<p>Therefor I expect <strong>no performance advantages</strong> compared to the simpler AtomicIncrement/AtomicDecrement on one variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T02:42:36.180", "Id": "9076", "ParentId": "9068", "Score": "3" } }, { "body": "<p>There is a flaw in the code.</p>\n\n<pre><code>int acquireCount = m_acquireCount;\nwhile(!CheckReleaseCount(acquireCount))\n Yield();\nDestroyPolicy(oldData);\n</code></pre>\n\n<p>You read the acquire counter, then wait for the release counter to be equal to what you read, and think that this indicates the old data are not used anymore. This is incorrect, because after reading you might get both counters incremented by threads that use <strong>new</strong> data. Thus, despite the release counter being equal to or greater than the value you read, some threads still may use the old data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:31:41.947", "Id": "9217", "ParentId": "9068", "Score": "1" } }, { "body": "<p>if you have C++11, use std::atomic instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T12:08:36.880", "Id": "9669", "ParentId": "9068", "Score": "1" } } ]
{ "AcceptedAnswerId": "9217", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T14:59:07.440", "Id": "9068", "Score": "4", "Tags": [ "c++", "multithreading" ], "Title": "Is my lockless data structure correct?" }
9068
<p>I am trying to make some code shorter and usable. Can someone look over the code I wrote and let me know if it's done correctly? I think it is but it seems a little too simple. The code allows a user to select a location form a drop down, then goes to that page.</p> <p>Old Code</p> <pre><code> if (typeof $.uniform === "undefined") { } else { $.uniform.update("select.jump"); $("select#mexico").change(function() { window.location = $("select#mexico option:selected").val(); }); $("select#paris").change(function() { window.location = $("select#paris option:selected").val(); }); $("select#london").change(function() { window.location = $("select#london option:selected").val(); }); $("select#jumpMenu").change(function() { window.location = $("select#jumpMenu option:selected").val(); }); } </code></pre> <p>New Code</p> <pre><code> if (typeof $.uniform === "undefined") { } else { $.uniform.update("select.jump"); $(this).change(function() { window.location = $(this).val(); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T22:58:42.533", "Id": "14230", "Score": "3", "body": "\"let me know if its done correctly\" --- does it work as expected? If yes - then yes, it's been done correctly. PS: there are `!=` and `!==` in js" } ]
[ { "body": "<p>Try this <a href=\"http://jsfiddle.net/deerua/yw52u/\" rel=\"nofollow\">sample</a></p>\n\n<p>html:</p>\n\n<pre><code>&lt;select&gt;\n &lt;option val=\"#\"&gt;---&lt;/option&gt;\n &lt;option val=\"#paris\"&gt;paris&lt;/option&gt;\n&lt;/select&gt;\n&lt;br/&gt;\n&lt;select&gt;\n &lt;option val=\"#\"&gt;---&lt;/option&gt;\n &lt;option val=\"#mexico\"&gt;mexico&lt;/option&gt;\n&lt;/select&gt;\n&lt;br/&gt;\n&lt;select&gt;\n &lt;option val=\"#\"&gt;---&lt;/option&gt;\n &lt;option val=\"#london\"&gt;london&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>​js:</p>\n\n<pre><code>//if (typeof $.uniform !== \"undefined\") {\n //$.uniform.update(\"select.jump\");\n $(\"select\").each(function(){\n $(this).change(function() {\n alert($(this).find(\"option:selected\").val());\n window.location = $(this).find(\"option:selected\").val();\n });\n });\n//}​​\n</code></pre>\n\n<p>uncomment your function parts</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:22:03.747", "Id": "9073", "ParentId": "9071", "Score": "1" } }, { "body": "<p>I'm not too familiar with jQuery, but instead of the empty block I'd invert the condition:</p>\n\n<pre><code>if (typeof $.uniform !== \"undefined\") {\n $.uniform.update(\"select.jump\");\n $(this).change(function() {\n window.location = $(this).val();\n });\n}\n</code></pre>\n\n<p>It's definitely more readable. Or you can use a guard clause if it is in a function:</p>\n\n<pre><code>if (typeof $.uniform === \"undefined\") {\n return;\n}\n$.uniform.update(\"select.jump\");\n$(this).change(function() {\n window.location = $(this).val();\n});\n</code></pre>\n\n<p>(References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T16:30:52.343", "Id": "16058", "Score": "1", "body": "I did invert the condition. That makes sense. Also thanks for the link about flattening code. I didn't know I had a problem until I read the article. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T09:05:37.393", "Id": "9085", "ParentId": "9071", "Score": "1" } } ]
{ "AcceptedAnswerId": "9073", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-16T22:55:17.823", "Id": "9071", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jQuery jump menu" }
9071
<p>The problem I want to solve is to replace a given string inside tags.</p> <p>For example, if I'm given:</p> <blockquote> <p>Some text abc [tag]some text abc, more text abc[/tag] still some more text</p> </blockquote> <p>I want to replace <code>abc</code> for <code>def</code> but only inside the tags, so the output would be:</p> <blockquote> <p>Some text abc [tag]some text def, more text def[/tag] still some more text</p> </blockquote> <p>We may assume that the tag nesting is well formed. My solution is the following:</p> <pre><code>def replace_inside(text): i = text.find('[tag]') while i &gt;= 0: j = text.find('[/tag]', i+1) snippet = text[i:j].replace('abc', 'def') text = text[:i] + snippet + text[j:] i = text.find('[tag]', j) return text </code></pre> <p>I was wondering if it can be solved in a more elegant way, for example, using regex.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:59:54.327", "Id": "14235", "Score": "0", "body": "This reminds me of bbcode ... could this help: http://www.codigomanso.com/en/2010/09/bbcodeutils-bbcode-parser-and-bbcode-to-html-for-python/" } ]
[ { "body": "<p>Your code is incorrect. See the following case:</p>\n\n<pre><code>print replace_inside(\"[tag]abc[/tag]abc[tag]abc[/tag]\")\n</code></pre>\n\n<p>You can indeed use regular expressions</p>\n\n<pre><code>pattern = re.compile(r\"\\[tag\\].*?\\[/tag\\]\")\nreturn pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:54:28.453", "Id": "14234", "Score": "1", "body": "doesn't it need to be `r\"\\[tag\\].*?\\[/tag\\]\"` for a non-greedy `*`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T21:37:31.493", "Id": "14268", "Score": "0", "body": "@Winston Ewert♦: you're right, I fixed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T21:38:55.547", "Id": "14269", "Score": "0", "body": "I agree with @James Khoury, it's necessary to use the non-greed version, otherwise it will fail in your test case too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T06:12:27.237", "Id": "14279", "Score": "1", "body": "@JamesKhoury, thanks. It seems I don't do regular expressions enough." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:10:15.363", "Id": "9074", "ParentId": "9072", "Score": "1" } }, { "body": "<p>Unless you have further restrictions on your input, your code cannot be correct. You're assuming there can be tag nesting, so you should be making a parser.</p>\n\n<p>As far as I can tell, your grammar is:</p>\n\n<pre><code>text -&gt; text tag_open text tag_close text\ntext -&gt; char_sequence\ntag_open -&gt; '[' identifier ']'\ntag_close -&gt; '[/' identifier ']'\n</code></pre>\n\n<p>Where <code>char_sequence</code> is some (possibly empty) sequence of characters that don't contain <code>[</code> and <code>identifier</code> is some sequence of (probably alphanumeric + underscore) characters.</p>\n\n<p>Now you could use something like PLY to build a syntax tree. You'll have to define your terminals:</p>\n\n<pre><code>char_sequence = r\"[^\\[]*\"\ntag_open = r\"\\[[a-zA-Z0-9_]+\\]\"\ntag_close = r\"\\[/[a-zA-Z0-9_]+\\]\"\n</code></pre>\n\n<p>Now you've got to build your abstract syntax tree. I would advise a class <code>Node</code> that contains a list of children, the associated tag, and the text in it. Thus, something like</p>\n\n<pre><code>def Node(object):\n def __init__(self, tag_name, text):\n self.tag_name = tag_name\n self.text = text\n self.children = []\n\n def add_child(self, child):\n self.children.append(child)\n</code></pre>\n\n<p>You'd want <code>[tag]Hello![tag]Hi![/tag][/tag]</code> to parse to a <code>Node</code> that has the <code>tag_name</code> <code>tag</code>, the <code>text</code> <code>Hello!</code>, and a single child.</p>\n\n<p>Once you have that, you can go ahead and define the grammar rules. PLY lets you do that with</p>\n\n<p>def p_tag_in_text(p):\n \"\"\"text : text open_tag text close_tag text\"\"\"\n # You now have an object for each of text, text, open_tag, text, close_tag, text\n # and can put them together here.</p>\n\n<p>Once you've defined all parser rules, you get an abstract syntax tree, which you can then traverse finding all relevant nodes and calling replace on the text you want.</p>\n\n<p>As you can see, this method is a lot longer and a good deal more complicated. The token examples I showed don't match the grammar -- you'd probably want to split the <code>[</code>, <code>[/</code> and <code>]</code> out of the tokens, and make sure that <code>close_tag</code> and <code>open_tag</code> just contain the identifiers. I've also not entirely specified how the grammar rules should be implemented: the current setup leads to it being unclear where the text is in relation to the tags. You'd have to refine the system somewhat to make that work (probably making the text a kind of child, and appending it at a suitable time.</p>\n\n<p>Because of this, you should first try to restrict your input. If you can ensure a number of things about tag nesting (especially tags containing themselves) it would allow you to do all of this with a regex, and in that case Winston Ewert's solution is what you should go with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T09:41:48.673", "Id": "9102", "ParentId": "9072", "Score": "0" } } ]
{ "AcceptedAnswerId": "9074", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:17:09.643", "Id": "9072", "Score": "2", "Tags": [ "python", "regex" ], "Title": "Replace match inside tags" }
9072
<p>I did this code for somebody but need it to be double checked before I pass it onto them. Code seems fine but I need someone to confirm I have coded the crossover methods correctly.</p> <p>Would be great if somebody that is familiar with genetic algorithms and crossover methods, could confirm that I have the correct logic and code behind each crossover method.</p> <pre><code> //one crossover point is selected, string from beginning of chromosome to the //crossover point is copied from one parent, the rest is copied from the second parent // One-point crossover public void onePointCrossover(Individual indi) { if (SGA.rand.nextDouble() &lt; pc) { // choose the crossover point int xoverpoint = SGA.rand.nextInt(length); int tmp; for (int i=xoverpoint; i&lt;length; i++){ tmp = chromosome[i]; chromosome[i] = indi.chromosome[i]; indi.chromosome[i] = tmp; } } } //two crossover point are selected, binary string from beginning of chromosome to //the first crossover point is copied from one parent, the part from // the first to the second crossover point is copied from the second parent // and the rest is copied from the first parent // Two-point crossover public void twoPointCrossover(Individual indi) { if (SGA.rand.nextDouble() &lt; pc) { // choose the crossover point int xoverpoint = SGA.rand.nextInt(length); int xoverpoint2 = SGA.rand.nextInt(length); int tmp; //swap if (xoverpoint &gt; xoverpoint2){ tmp = xoverpoint; xoverpoint = xoverpoint2; xoverpoint2 = tmp; } for (int i=xoverpoint; i&lt;xoverpoint2; i++){ tmp = chromosome[i]; chromosome[i] = indi.chromosome[i]; indi.chromosome[i] = tmp; } } } // For each gene, create a random number in [0,1]. If // the number is less than 0.5, swap the gene values in // the parents for this gene; otherwise, no swapping // Uniform Crossover public void UniformCrossover(Individual indi) { if (SGA.rand.nextDouble() &lt; pc) { for (int i= 1; i&lt;length; i++){ boolean tmp = SGA.rand.nextFloat() &lt; 0.5; if(tmp){ chromosome[i] = indi.chromosome[i]; } } } </code></pre> <p>Parent 1 = chromosome Parent 2= indi.chromosome</p> <p>I am turning the parents into children inplace.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:35:43.227", "Id": "14238", "Score": "1", "body": "I suggest you write unit tests. See JUnit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:46:30.627", "Id": "14239", "Score": "0", "body": "Does it work when you test it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:48:06.453", "Id": "14240", "Score": "0", "body": "Yes that would be appropriate but because I am not to good with genetic algorithms I will not know what to expect from the test results. I had an algorithm for each crossover method and implemented them into java code, I just wanted to check the code is swapping and keeping the correct parts from the parents." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:48:17.287", "Id": "14241", "Score": "0", "body": "What is pc equal to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:57:23.637", "Id": "14242", "Score": "0", "body": "Yes it does work when I run it and I get slightly different values each time I change the crossover methods (only when pm>0.2), which is a good sign? pc = 0.8" } ]
[ { "body": "<p>It's difficult to just look at, but a few things jump out. More improvements than bugs:</p>\n\n<ul>\n<li><p>For single point crossover using <code>System.arraycopy()</code> would be much more reliable. For example:</p>\n\n<pre><code>System.arraycopy(parent1Genes, 0, childGenes, 0, xoverPoint);\nSystem.arraycopy(parent2Genes, xoverPoint, childGenes, xoverPoint, geneSize-xoverPoint);\n</code></pre></li>\n<li><p>You could use the same method for two point, but it would be slightly more complex.</p></li>\n<li><p>In Uniform crossover you can use <code>rand.nextBoolean()</code>, which returns true or false, instead of comparing the float.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T02:01:46.157", "Id": "14243", "Score": "0", "body": "Thank you for the suggestions, I didn't quite understand how I could use rand.nextBoolean instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:38:00.463", "Id": "14245", "Score": "0", "body": "Well checking to see if a random double is < 0.5 is just a coin flip. So you can replace `rand.nextDouble() < 0.5` with `rand.nextBoolean()`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:55:40.687", "Id": "9078", "ParentId": "9077", "Score": "4" } }, { "body": "<p>A bit out of scope of the question, but one thing is if you are doing crossover directly on the parents, then the parents will not be viable for further selection. Otherwise the algorithm could do several crossovers on an already manipulated parent/child (assuming you allow the same individual to be selected for breeding more than once).</p>\n\n<p>The times I have implemented this myself I always pass in the individuals for crossover and return the children. That way it is easier to keep the generations separate. An alternative would be to clone the individuals in the parent generation do the crossover and mutations on the cloned copy and use the original individuals for selection. </p>\n\n<p>Your implementation looks alright to me. However as has been stated in the comments you really <strong>need</strong> to write tests for these functions. By mocking the random generation function you can control what the results should be. I.e. instead of generating random numbers like this:</p>\n\n<pre><code>SGA.rand.nextDouble()\n</code></pre>\n\n<p>you could have a field in your class:</p>\n\n<pre><code>pubilc class Crossover {\n private Randomizer randomizer\n public Crossover(Randomizer randomizer) {\n this.randomizer = randomizer;\n }\n\n public void onePointCrossover(Individual indi) {\n if (randomizer.nextDouble() &lt; pc) {\n // do stuff \n }\n }\n}\n</code></pre>\n\n<p>Where Randomizer is an interface with the <code>nextXXXX()</code> methods you need. That way you can create mocks for the Randomizer in your test, and have a concrete implementation which delegates to <code>SGA.rand.nextXXXX()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T08:26:43.497", "Id": "9082", "ParentId": "9077", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:34:08.313", "Id": "9077", "Score": "5", "Tags": [ "java", "algorithm" ], "Title": "Confirm code is correct - crossover methods in Java" }
9077
<p>This Socket Server should handle about 5000 lines of log file entries per second from at least 15 machines from same network. Any tips to further optimize this script or are there any big mistakes? </p> <pre><code>class Server { private $callback; private $clients; private $socket; public function __construct($ip, $port) { $this-&gt;hooks = array(); $this-&gt;clients = array(); $this-&gt;socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this-&gt;socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($this-&gt;socket, $ip, $port); socket_listen($this-&gt;socket); } public function setCallback($function) { $this-&gt;callback = $function; } public function loop_once() { $read = array( $this-&gt;socket ); $write = NULL; $except = NULL; foreach ($this-&gt;clients as $index =&gt; &amp;$client) { $read[] = &amp;$client-&gt;socket; } if (socket_select($read, $write, $except, 1) &lt; 1) { return true; } if (in_array($this-&gt;socket, $read)) { $this-&gt;clients[] = new Client($this-&gt;socket, 0); } foreach ($this-&gt;clients as $index =&gt; &amp;$client) { if (in_array($client-&gt;socket, $read)) { $input = socket_read($client-&gt;socket, 1024, PHP_NORMAL_READ); if ($input === false) { $client-&gt;destroy(); unset($this-&gt;clients[$index]); } else { if (isset($this-&gt;callback)) { call_user_func($this-&gt;callback, $input); } } } } $this-&gt;clients = array_values($this-&gt;clients); return true; } } class Client { public $socket; public function __construct(&amp;$socket, $i) { $this-&gt;socket = socket_accept($socket); } public function destroy() { socket_close($this-&gt;socket); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T11:19:20.830", "Id": "14637", "Score": "0", "body": "* removed @-operator from socket_select and socket_read" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T11:20:27.600", "Id": "14638", "Score": "0", "body": "* added socket_set_option for reuse of address" } ]
[ { "body": "<p>Why are you suppressing <code>socket_select</code> errors - I'd suggest at least catching any errors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T11:13:37.000", "Id": "14636", "Score": "0", "body": "Had problems with `PHP Warning: socket_select(): unable to select [4]: Interrupted system call in` because of the older use of `declare(ticks = 1);` changed that now to a call to `pcntl_signal_dispatch();` in each loop to get all signaling handled properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T11:21:33.657", "Id": "14639", "Score": "0", "body": "Ah I see, makes sense" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T00:22:18.220", "Id": "9301", "ParentId": "9086", "Score": "1" } }, { "body": "<p>Try dropping the reference usage. Objects are copied by reference already:</p>\n\n<pre><code>&lt;?php\n$a = (object)array('one' =&gt; 1, 'two' =&gt; 2);\n$b = $a;\n$b-&gt;three = 3;\n\nprint_r($a);\nprint_r($b);\n?&gt;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>stdClass Object\n(\n [one] =&gt; 1\n [two] =&gt; 2\n [three] =&gt; 3\n)\nstdClass Object\n(\n [one] =&gt; 1\n [two] =&gt; 2\n [three] =&gt; 3\n)\n</code></pre>\n\n<p>However, arrays are copied by value (using copy-on-write):</p>\n\n<pre><code>&lt;?php\n$a = array('one' =&gt; 1, 'two' =&gt; 2);\n$b = $a;\n$b['three'] = 3;\n\nprint_r($a);\nprint_r($b);\n?&gt;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Array\n(\n [one] =&gt; 1\n [two] =&gt; 2\n)\nArray\n(\n [one] =&gt; 1\n [two] =&gt; 2\n [three] =&gt; 3\n)\n</code></pre>\n\n<p>Since <code>Client</code> is an object type, you should be able to replace:</p>\n\n<pre><code>foreach ($this-&gt;clients as $index =&gt; &amp;$client)\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>foreach ($this-&gt;clients as $index =&gt; $client)\n</code></pre>\n\n<p>Actually, \"objects are copied by reference\" isn't entirely true. An \"object\" in PHP is just a handle referring to a shared entity, making it more like a reference in Java or a pointer in C. This is not true for arrays, where modification is confined to the variable upon which it happens.</p>\n\n<p>References in PHP are one level above the notion of object handle. When you modify a reference, you are changing what the referent variable <em>names</em>. For example:</p>\n\n<pre><code>$obj = (object)array('one' =&gt; 1, 'two' =&gt; 2);\n$a = $obj;\n$a-&gt;three = 'three';\n</code></pre>\n\n<p>Now <code>$obj</code> and <code>$a</code> point to the same object, but they are distinct variables. Now let's do something funky with references:</p>\n\n<pre><code>$b =&amp; $a;\n$b = null;\n</code></pre>\n\n<p>This actually sets both <code>$a</code> and <code>$b</code> to <code>null</code>, but leaves <code>$obj</code> intact.</p>\n\n<p>Confused? Good.</p>\n\n<p>For more information about references in PHP, see:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/language.references.php\" rel=\"nofollow\">http://php.net/manual/en/language.references.php</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T12:02:10.597", "Id": "18284", "Score": "0", "body": "$this->clients is an array and only the content are objects, but I see your point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T22:22:53.930", "Id": "10310", "ParentId": "9086", "Score": "3" } }, { "body": "<p>The code looks good (a few comments would have helped me understand it quicker though).</p>\n\n<p>I have only very minor things to comment on:</p>\n\n<ul>\n<li><code>$index</code> is not used in the first <code>foreach</code>. I believe this has a small impact on performance.</li>\n<li><code>else { if () {} }</code> is equivalent to <code>elseif { }</code></li>\n<li>Client constructor does not use <code>$i</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T05:10:09.737", "Id": "10313", "ParentId": "9086", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T09:49:47.153", "Id": "9086", "Score": "2", "Tags": [ "php", "php5" ], "Title": "PHP Socket Server" }
9086
<p>I built an extension method to cycle through all items of an <code>IEnumerable</code> starting at some index: </p> <pre><code>public static IEnumerable&lt;T&gt; Circle&lt;T&gt;(this IEnumerable&lt;T&gt; list, int startIndex) { if (list != null) { List&lt;T&gt; firstList = new List&lt;T&gt;(); using (var enumerator = list.GetEnumerator()) { int i = 0; while (enumerator.MoveNext()) { if (i &lt; startIndex) { firstList.Add(enumerator.Current); i++; } else { yield return enumerator.Current; } } } foreach (var first in firstList) { yield return first; } } yield break; } </code></pre> <p>So when you do</p> <pre><code>Enumerable.Range(1,10).Circle(5); </code></pre> <p>The result is 6,7,8,9,10,1,2,3,4,5.</p> <p>What I don't like is the use of the <code>firstList</code> variable. <strong>Is there a way to do this with the enumerator only, without storing an intermediate result?</strong></p> <p><strong>EDIT:</strong><br> I use an enumerator to iterate the enumerable not more than once.</p>
[]
[ { "body": "<p>A shorter form of Trevor's answer (but essentially doing the same thing):</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Circle&lt;T&gt;(this IEnumerable&lt;T&gt; list, int startIndex)\n{\n return list.Skip(startIndex).Concat(list.Take(startIndex));\n}\n</code></pre>\n\n<p>This will still lazy evaluate just like Trevor's answer, because <code>Concat</code> lazily evaluates.</p>\n\n<p>Further more, if you have written a method to <em>cycle</em> through an <code>IEnumerable</code>, why not call it <code>Cycle</code>?</p>\n\n<p>Lastly, I'd actually recommend taking advantage of lazy evaluation to give you a more useful method. The one below will continue to cycle indefinitely, starting with an optional index:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Cycle&lt;T&gt;(this IEnumerable&lt;T&gt; list, int index = 0)\n{\n\n var count = list.Count();\n index = index % count;\n\n while(true)\n {\n yield return list.ElementAt(index);\n index = (index + 1) % count;\n }\n}\n</code></pre>\n\n<p>Then you can do something like:</p>\n\n<pre><code>foreach(var num in Enumerable.Range(1, 10).Cycle(4).Take(30))\n{\n Console.WriteLine(num.ToString());\n}\n</code></pre>\n\n<p>And this lets you specify just how many repeated items you want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-28T15:12:38.783", "Id": "167118", "Score": "1", "body": "`list.ElementAt` will have terrible performance if the underlying collection doesn't support random access. Your algorithm will be `O(n^2)` in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-28T15:14:12.493", "Id": "167119", "Score": "0", "body": "Very true, but my review was intended to suggest alternative methods of structuring the entire method. The exact way of getting the element isn't important in my answer at all and could trivially be replaced." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-29T11:59:28.913", "Id": "167288", "Score": "2", "body": "Thanks, yes it's a bit shorter and it basically does the same thing. Your second method isn't useful in my use case (I really need one complete cycle without knowing the number of elements in advance), but I can imagine suitable use cases. I don't like that it requires a `Take` to come to an end though. (And I swapped two lines to make it work)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-29T16:08:06.970", "Id": "167326", "Score": "0", "body": "Haha, oops, looks like I copy-pasted those lines in the wrong order!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-28T15:02:02.000", "Id": "92070", "ParentId": "9088", "Score": "10" } }, { "body": "<p>The background, not mentioned in the question, was that I wanted this to work on <code>IQueryable</code>s from a database backend. Therefore, repeated execution of the input variable should be prevented and the best solution for this more limited case is:</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Circle&lt;T&gt;(this IQueryable&lt;T&gt; query, int startIndex)\n{\n var localList = query.ToList();\n return localList.GetRange(startIndex, localList.Count - startIndex)\n .Concat(localList.GetRange(0,startIndex));\n}\n</code></pre>\n\n<p>When testing this with 10<sup>7</sup> integers, the statement <code>var localList = query.ToList();</code> took approx. 70% of the time. But <code>List.GetRange</code> is a highly efficient method, so all in all this is the winner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-06T16:28:39.780", "Id": "411936", "Score": "0", "body": "A `.ToList()` in an extension method that takes `IEnumerable<T>` and returns `IEnumerable<T>` needs a _darn_ good comment on it to explain exactly why the `.ToList()` is required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-06T22:37:43.057", "Id": "411997", "Score": "0", "body": "@PaulSuart Well, obviously it is to prevent multiple execution of `list` which is a pretty standard pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T08:28:08.617", "Id": "412036", "Score": "1", "body": "But if the `IEnumerable<T>` you pass in is very large, and/or expensive to obtain... this method simply does not scale. For example, you can represent infinite collections with `IEnumerable` - this method would not work at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T15:44:22.667", "Id": "412262", "Score": "0", "body": "@PaulSuart My prime focus was on `IQueryable`s from a database which shouldn't be enumerated multiple times. Since that wasn't mentioned in the question my answer has a smaller usability scope than Nick's. Your comment made me aware of this. For that reason I'm marking the other answer as accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T16:17:52.223", "Id": "412267", "Score": "0", "body": "That's all good. I'd suggest a small improvement would be to make your method an extension for `IQueryable<T>` not `IEnumerable<T>` in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T16:38:28.263", "Id": "412268", "Score": "1", "body": "@PaulSuart OK, good suggestion. Well, after all I think this Q&A looks better now than before your comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T16:55:08.150", "Id": "412270", "Score": "0", "body": "I think the method should take an `IQueryable<T>` but return an `IEnumerable<T>` as you've materialised the query's results inside the extension method." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2016-02-22T21:52:40.323", "Id": "120821", "ParentId": "9088", "Score": "1" } } ]
{ "AcceptedAnswerId": "92070", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T11:37:52.040", "Id": "9088", "Score": "10", "Tags": [ "c#", "optimization", "extension-methods" ], "Title": "Cycle through an IEnumerable" }
9088
<p>I am building a web app with using UOW and Repository pattern. I have seen many different samples and found each one to be different, so not sure which is the correct way to go. I have a basic understanding of both these patterns and I wanted to know if I should keep one UOW implementation for all the tables in my project or keep a separate one as per functionality like for:</p> <pre><code>public interface IHomeUOW { IGenericRepository&lt;User&gt; Users { get; } IGenericRepository&lt;TableA&gt; Table_A { get; } IGenericRepository&lt;TableB&gt; Table_B{ get; } } public interface IBusinessCaseUOW { IGenericRepository&lt;TableA&gt; Table_A { get; } IGenericRepository&lt;TableXYZ&gt; Table_XYZ{ get; } } </code></pre> <p>As you can see, <code>TableA</code> is available in both Home UOW as well as a particular business case UOW. One UOW partially implemented as below:</p> <pre><code>public class UnitOfWork : IUnitOfWork { private readonly ObjectContext _context; private UserRepository _userRepository; public UnitOfWork(ObjectContext Context) { if (Context == null) { throw new ArgumentNullException("Context wasn't supplied"); } _context = Context; } public IGenericRepository&lt;User&gt; Users { get { if (_userRepository == null) { _userRepository = new UserRepository(_context); } return _userRepository; } } } </code></pre> <p>My repositories will be like so</p> <pre><code>public interface IGenericRepository&lt;T&gt; where T : class { //Fetch records T GetSingleByRowIdentifier(int id); T GetSingleByRowIdentifier(string id); IQueryable&lt;T&gt; FindByFilter(Expression&lt;Func&lt;T, bool&gt;&gt; filter); // CRUD Ops void AddRow(T entity); void UpdateRow(T entity); void DeleteRow(T entity); } public abstract class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt; where T : class { protected IObjectSet&lt;T&gt; _objectSet; protected ObjectContext _context; public GenericRepository(ObjectContext Context) { _objectSet = Context.CreateObjectSet&lt;T&gt;(); _context = Context; } //Fetch Data public abstract T GetSingleByRowIdentifier(int id); public abstract T GetSingleByRowIdentifier(string id); public IQueryable&lt;T&gt; FindByFilter(Expression&lt;Func&lt;T, bool&gt;&gt; filter) { // } //CRUD Operations implemented } public class UserRepository : GenericRepository&lt;User&gt; { public UserRepository(ObjectContext Context) : base(Context) { } public override User GetSingleByRowIdentifier(int id) { //implementation } public override User GetSingleByRowIdentifier(string username) { //implementation } } </code></pre> <p>What do you think? If this is not the correct implementation of UOW and Repository pattern for DDD, will it fail as just a bunch of code written to abstract the call to the EF tables?</p>
[]
[ { "body": "<p>The UoW pattern has a couple of properties. The UoW will:</p>\n\n<ul>\n<li>track changes to entities, wether that be adding, removing or updating.</li>\n<li>coordinate the persisting of these changes in one atomic action. Which also means rolling back if an error occurs.</li>\n</ul>\n\n<p>Since you're using EF, you don't have to implement this stuff, it's done for you. The ObjectContext is actually the UoW object. So unless you plan to switch out Persistence frameworks later on, any additional abstraction will be wasted effort.</p>\n\n<p>I'm guessing you want to make sure your domain isn't aware of how it's persisted. Your domain should only know of the repository <em>interfaces</em>. The repository interfaces are actually part of your domain. The repository implementation though, is part of the persistance layer.</p>\n\n<p>The repository implementation looks OK. I'm only curious about <code>FindByFilter</code>; if you're returning an <code>IQueryable&lt;T&gt;</code> object, you're saying you can query it. OTOH the <code>FindByFilter</code> function already takes an <code>Expression&lt;Func&lt;T, bool&gt;&gt; filter</code> parameter. I'd pick one of the two like the following:</p>\n\n<pre><code>public IEnumerable&lt;T&gt; FindByFilter(Expression&lt;Func&lt;T, bool&gt;&gt; filter)\n{\n //\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>public IQueryable&lt;T&gt; FindAll()\n{\n //\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T16:54:56.740", "Id": "14457", "Score": "0", "body": "Thanks for pointing out FindByFilter. I dont think it should return a queryable object. Will change that to a list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T17:00:47.170", "Id": "14459", "Score": "0", "body": "With respect to the UOW pattern, I guess I was trying to stretch the UOW concept a bit too much without fully understanding what it was for. My intent was to group a bunch of repositories by business case.. I dont want junior developers querying the wrong repositories for a particular application area. For eg. TableA can have child records in TableB for a particular area of the application and maybe TableC for another area of the application. I can now move the IUnitOfWork and its implementation to the Business layer. What do you think of that idea?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T17:07:53.463", "Id": "14461", "Score": "0", "body": "Is the UOW pattern redundant with EF? There are lots of articles like this one on MSDN that use EF and UOW together. http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T18:54:29.890", "Id": "14469", "Score": "0", "body": "The UoW pattern itself isn't redundant. It is already implemented by EF by the ObjectContext. In the article you mentioned the author created a custom IUnitOfWork interface to \"make things more explicit\", the comments on that article discuss the need for such an interface, since it doesn't really add any value on top of the ObjectContext. It's actually an implementation detail of how the repositories work. You might want to take a look at the onion architecture http://jeffreypalermo.com/blog/the-onion-architecture-part-3/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T19:02:03.080", "Id": "14471", "Score": "0", "body": "Instead of grouping a bunch of repositories by business case, try modeling the business cases with your Domain Model. That is what DDD is all about. I don't know how flexible EF is that regard but it should be able to do most things. Like having EntityA contain a list of EntityBs and a list of EntityCs. The code for manipulating these lists (not accessing the repositories!) would be contained withing EntityA." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T10:33:22.120", "Id": "14521", "Score": "0", "body": "but that would mean EntityA would need to pull all EntityB and EntityC data whether it needs it or not. correct? . That is probably going to be a performance hit then.. right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T14:57:53.557", "Id": "14537", "Score": "1", "body": "That is a valid (infrastructure) concern, not a domain concern though. Luckily Entity Framework 4 has a solution for this, called Lazy Loading. In short this means that instead of querying the EntityB and EntityC data when EntityA is pulled out of the ObjectContext, the framework will make sure this data is only queried the moment your code actually accesses the EntityB and EntityC lists. It does have its own caveats, but there's a whole lot more information available. I'd suggest you start at http://msdn.microsoft.com/en-us/library/bb896272.aspx and work your way from there." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T21:46:57.317", "Id": "9203", "ParentId": "9091", "Score": "1" } } ]
{ "AcceptedAnswerId": "9203", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T14:08:41.493", "Id": "9091", "Score": "3", "Tags": [ "c#", "design-patterns", "asp.net-mvc-3" ], "Title": "Is this a workable UnitOfWork with Repository pattern design?" }
9091
<p>I have this query built using the above, but it feels like it could be improved to make it more concise:</p> <pre><code> private IQueryable&lt;Lead&gt; _queryLeadsByHeat(int? ownerUserId, bool warmLeads) { var predicate = PredicateBuilder.False&lt;Lead&gt;(); predicate = predicate.Or(x =&gt; x.LeadPool.DecreaseByUnit == (int) DecreaseUnitTime.Day &amp;&amp; ( (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &gt; 0 &amp;&amp; warmLeads || (x.LastHeatValue - SqlFunctions.DateDiff("day", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today)* x.LeadPool.DecreaseLeadBy) &lt;= 0 &amp;&amp; !warmLeads ) ); predicate = predicate.Or(x =&gt; x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Week &amp;&amp; ( (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &gt; 0 &amp;&amp; warmLeads || (x.LastHeatValue - SqlFunctions.DateDiff("week", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &lt;= 0 &amp;&amp; !warmLeads ) ); predicate = predicate.Or(x =&gt; x.LeadPool.DecreaseByUnit == (int)DecreaseUnitTime.Month &amp;&amp; ( (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &gt; 0 &amp;&amp; warmLeads || (x.LastHeatValue - SqlFunctions.DateDiff("month", !x.LastContactDate.HasValue ? x.InitialContactDate : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &lt;= 0 &amp;&amp; !warmLeads ) ); var query = _activeLeads(ownerUserId) .AsExpandable().Where(predicate); return query; } </code></pre> <p>Any ideas on how to improve this?</p>
[]
[ { "body": "<p>First of all. Is _queryLeadsByHeat supposed to represent a method? If so I would steer away from using underscore in it's method name unless that's your naming convention in which case I guess your stuck with it. Underscore is traditionally mainly reserved for fields (if at all as there are large debates for this practice).</p>\n\n<p>I don't have Visual studio in front of me so not sure if this will even compile (or is even possible) but my initial thought would be to try and consolidate the Predicates into one method.</p>\n\n<pre><code>Expression&lt;Func&lt;T, bool&gt;&gt; GetHeatCondition(DecreaseUnitTime period)\n{\n string periodAsString = period.ToString();\n\n return predicate.Or(x =&gt; x.LeadPool.DecreaseByUnit == (int)period\n &amp;&amp;\n (\n (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue\n ? x.InitialContactDate\n : x.LastContactDate.Value, DateTime.Today) * x.LeadPool.DecreaseLeadBy) &gt; 0 &amp;&amp; warmLeads ||\n\n (x.LastHeatValue - SqlFunctions.DateDiff(periodAsString, !x.LastContactDate.HasValue\n ? x.InitialContactDate\n : x.LastContactDate.Value, DateTime.Today) *\n x.LeadPool.DecreaseLeadBy) &lt;= 0 &amp;&amp; !warmLeads\n )\n );\n}\n\nprivate IQueryable&lt;Lead&gt; QueryLeadsByHeat(int? ownerUserId, bool warmLeads)\n{\n var predicate = PredicateBuilder.False&lt;Lead&gt;();\n predicate = predicate.Or(GetHeatCondition&lt;Lead&gt;(DecreaseUnitTime.Day));\n predicate = predicate.Or(GetHeatCondition&lt;Lead&gt;(DecreaseUnitTime.Month));\n predicate = predicate.Or(GetHeatCondition&lt;Lead&gt;(DecreaseUnitTime.Year));\n\n var query = _activeLeads(ownerUserId) \n .AsExpandable().Where(predicate);\n\n return query;\n}\n</code></pre>\n\n<p>I'm pretty sure that Linq query could be better optimized. Have to think some more on that one...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T20:00:47.447", "Id": "9096", "ParentId": "9095", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:06:31.613", "Id": "9095", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "How can this LINQ query using SqlFunctions.Datediff and LINQKit's PredicateBuilder be improved" }
9095
<p>Is there any simple way to detect user keystrokes that result in character input? In other words, ignore all soft keys and modifier keys? This works but seems sort of hacky:</p> <pre><code>var keycode = event.keyCode ? event.keyCode : event.charCode if((keycode&gt;=48 &amp;&amp; keycode&lt;=90) || (keycode&gt;=96 &amp;&amp; keycode&lt;=111) || (keycode&gt;=186 &amp;&amp; keycode&lt;=192) || (keycode&gt;=219 &amp;&amp; keycode&lt;=222)){ alert("realkey") } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:17:41.847", "Id": "14270", "Score": "1", "body": "Perhaps if you described what you were trying to achieve we could help more. Is this typing in a text input? Can you use the `keyup` event and see if the `.value` has changed as a result?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:19:21.923", "Id": "14271", "Score": "0", "body": "What you're doing looks like the best way to go. If you want something that doesn't look \"hacky\" you'll need a library like jQuery (which under the hood is hacky)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:22:27.050", "Id": "14272", "Score": "0", "body": "Sorry no its a contentEditable div. I'd hoped there was some easy way to check this range of keys but from the sounds of the comments there isn't...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:31:02.557", "Id": "14273", "Score": "0", "body": "I think you're using the best method." } ]
[ { "body": "<p>You can use <code>String.fromCharCode</code> in combination with a Regular Expression test as alernative:</p>\n\n<pre><code>var cando = /[a-z0-9]/i\n .test(String.fromCharCode(event.keyCode || event.charCode));\nif( cando ){\n alert(\"realkey\")\n}\n</code></pre>\n\n<p>In the <code>RegExp</code> you can put all the characters you want to allow, in this case all a to z (case insensitive) and the digits 0 to 9. Best to use the <code>keypress</code> event here.</p>\n\n<p>BTW, what kind of criterium is 'seeming sort of hacky'?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-28T00:32:46.507", "Id": "339796", "Score": "0", "body": "What about unicode?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-28T07:48:00.067", "Id": "339815", "Score": "0", "body": "\"In the RegExp you can put all the characters you want to allow\" ... So, put them between `/ ... /i`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-24T10:47:19.697", "Id": "397726", "Score": "0", "body": "typo: `String.fromCharCode`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-02-17T17:30:53.453", "Id": "9099", "ParentId": "9098", "Score": "0" } }, { "body": "<p>Yes, use keypress events instead of keydown events. See example: <a href=\"http://jsfiddle.net/7fmjh/6/\" rel=\"nofollow\">http://jsfiddle.net/7fmjh/6/</a> - or a non-jquery example: <a href=\"http://jsfiddle.net/7fmjh/11/\" rel=\"nofollow\">http://jsfiddle.net/7fmjh/11/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T18:30:39.933", "Id": "14274", "Score": "0", "body": "This is a cool solution. I can't fathom how to do it on contentEditable div tho?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T18:37:37.513", "Id": "14275", "Score": "0", "body": "Works just the same: http://jsfiddle.net/7fmjh/13/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T19:30:07.457", "Id": "14276", "Score": "0", "body": "What I mean is if its contenteditable then we'll need to append the keypress at the caret position rather than at the end of the div. I'm not actually using jQuery but the examples are great. thanks a lot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T21:04:43.903", "Id": "14277", "Score": "0", "body": "so...what exactly are you trying to do for YOUR page that you still can't do? I'm assuming you don't want to append the word \"keypress\" every time they keypress haha." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-23T10:31:09.347", "Id": "152569", "Score": "1", "body": "This will not work in FireFox" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:32:52.370", "Id": "9100", "ParentId": "9098", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:15:05.267", "Id": "9098", "Score": "2", "Tags": [ "javascript" ], "Title": "Detect real \"hard\" character keys only" }
9098
<p>I have been working on a parser generator, in which I want to employ a sort of fluent configuration interface - avoiding the pre-compile step that usually comes with parser generators. It's supposed to be a tool not just for language construction, but also for generalized parsing tasks that you usually end up coding manually since it's not worth the effort to drag in a full-blown language construction kit.</p> <p>What I'm concerned about is if I'm missing the mark, since the code quickly becomes a bit complex when configuring a parser. Here's my demo for a JSON parser:</p> <pre><code>using System.Collections.Generic; using Piglet.Parser; namespace Piglet.Demo.Parser { public class JsonParser { public class JsonElement { public string Name { get; set; } public object Value { get; set; } }; public class JsonObject { public List&lt;JsonElement&gt; Elements { get; set; } }; public static void Run() { var parser = ParserFactory.Configure&lt;object&gt;(configurator =&gt; { var quotedString = configurator.Terminal("\"(\\.|[^\"])*\"", f =&gt; f.Substring(1, f.Length - 2)); var doubleValue = configurator.Terminal(@"\d+\.\d+", f =&gt; double.Parse(f)); var integerValue = configurator.Terminal(@"\d+", f =&gt; int.Parse(f)); var jsonObject = configurator.NonTerminal(); var optionalElementList = configurator.NonTerminal(); var elementList = configurator.NonTerminal(); var element = configurator.NonTerminal(); var value = configurator.NonTerminal(); var array = configurator.NonTerminal(); var optionalValueList = configurator.NonTerminal(); var valueList = configurator.NonTerminal(); jsonObject.Productions(p =&gt; p.Production("{", optionalElementList, "}") .OnReduce( f =&gt; new JsonObject { Elements = (List&lt;JsonElement&gt;) f[1]} )); optionalElementList.Productions(p =&gt; { p.Production(elementList) .OnReduce(f =&gt; f[0]); p.Production() .OnReduce(f =&gt; new List&lt;JsonElement&gt;()); }); elementList.Productions(p =&gt; { p.Production(elementList, ",", element) .OnReduce(f =&gt; { var list = (List&lt;JsonElement&gt;)f[0]; list.Add((JsonElement)f[2]); return list; }); p.Production(element) .OnReduce(f =&gt; new List&lt;JsonElement&gt; { (JsonElement)f[0] }); }); element.Productions(p =&gt; p.Production(quotedString, ":", value) .OnReduce(f =&gt; new JsonElement { Name = (string)f[0], Value = f[2]})); value.Productions(p =&gt; { p.Production(quotedString) .OnReduce(f =&gt; f[0]); p.Production(integerValue) .OnReduce(f =&gt; f[0]); p.Production(doubleValue) .OnReduce(f =&gt; f[0]); p.Production(jsonObject) .OnReduce(f =&gt; f[0]); p.Production(array) .OnReduce(f =&gt; f[0]); p.Production("true") .OnReduce(f =&gt; true); p.Production("false") .OnReduce(f =&gt; false); p.Production("null") .OnReduce(f =&gt; null); }); array.Productions(p =&gt; p.Production("[", optionalValueList, "]") .OnReduce( f =&gt; ((List&lt;object&gt;)f[1]).ToArray() )); optionalValueList.Productions(p =&gt; { p.Production(valueList) .OnReduce(f =&gt; f[0]); p.Production() .OnReduce(f =&gt; new List&lt;object&gt;()); }); valueList.Productions(p =&gt; { p.Production(valueList, ",", value) .OnReduce(f =&gt; { var list = (List&lt;object&gt;)f[0]; list.Add(f[2]); return list; }); p.Production(value) .OnReduce(f =&gt; new List&lt;object&gt;{f[0]}); }); configurator.LexerSettings.EscapeLiterals = true; configurator.LexerSettings.Ignore = new [] { @"\s+" }; }); var jObject = (JsonObject)parser.Parse("{ \"Property1\":\"value\", \"IntegerProperty\" : 1234 }"); } } } </code></pre> <p>Questions:</p> <ol> <li>Is it clear what this configuration achieves to you? </li> <li>Is there any way you can see to improve the interface of the library?</li> </ol> <p>Of course, this should be considerably more understandable if you have previous experience of parser generators, but even if you don't it would be valuable to me to know how much of this someone unfamiliar with parser generators can figure out from just seeing the code.</p> <p>The full library is on <a href="https://github.com/Dervall/Piglet" rel="nofollow">GitHub</a>, if you feel the need to delve deeper into the internals. But since this is the interface that users of the library would see, this is probably the most important part I want to get right.</p> <p>To clarify exactly what I would like people to take a shot at is not the actual JSON parsing grammar in this example, or the <code>Run</code> method in general. Rather it is the structure of the <code>ParserFactory</code> and the way the <code>Production</code>, <code>OnParse</code> and such methods are called. For example: </p> <ol> <li>Is my way of designing the library configuration interface good? </li> <li>Does it use the lambdas in a good way? </li> <li>Are the method names understandable?</li> <li>Do you understand what it does given whatever background you have on context free grammar parsing?</li> </ol>
[]
[ { "body": "<p>Refactor the Run()-method into seperate methods. It's barely readable now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T20:49:19.527", "Id": "14307", "Score": "0", "body": "I agree. That would be the first step I would take as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T21:31:10.677", "Id": "14309", "Score": "0", "body": "Oh, I think you're missing the point. The `Run` method is not really what I want reviewed. That is just the demo code. What I want peoples opinion on is if the way of using the `configurator` object is looking intuitive, and the way of configuring productions and reduction rules for the grammar is a nice way of doing it. I'll clarify the question" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:37:24.477", "Id": "9117", "ParentId": "9104", "Score": "2" } }, { "body": "<p>I like the idea of a Fluent Parser, but I find the syntax you're using very confusing, which probably isn't what you wanted to hear.</p>\n\n<p>Some feedback:</p>\n\n<ul>\n<li>Productions, Production, Onreduce, these terms have no meaning for me. So they don't feel fluent at all. They might be fluent in the world of a parser, but as you want to abstract the parser away, I think you need to think more in terms of the resulting structure or the expressions. Kind of <code>Parser.Add(\"ElementList\").AddOption().Start().FollowedByLiteral(\"{\").FollowedByList&lt;int&gt;(\",\").FollowedByLiteral(\"}\");</code> or something, that expresses the structure being parsed, but not the process underneath. (not the best example, but still more understandable than <code>Productions.AddProduction.OnReduce(f =&gt; f[0][1].ToString());</code></li>\n<li>What's meant by <code>f =&gt; f[1]</code>? It's unclear for the reader, can't you write this as <code>OnReduce&lt;returnType&gt;().SkipLiteral(\"}\").Take&lt;returnType&gt;();</code> or something else that stays fluent and removed the need for these lambda's if possible? </li>\n<li>I'd try to refactor OnReduce (whatever it does) to be a generic method, so that <code>OnReduce(f =&gt; ((List&amp;lt;object&amp;gt;)f[1]).ToArray())</code> would become <code>OnReduce&lt;object[]&gt;(f =&gt; f[1]);</code> And then you need to figure out a way to remove the f => f[1] part.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:17:54.763", "Id": "14410", "Score": "0", "body": "Very good input! That's exactly the sort of stuff I want to know. Thanks a lot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:27:04.360", "Id": "14411", "Score": "0", "body": "The `f=>f[0]` will select the first parameter used in the production of the parser as the resulting value of a rule. The syntax I have right now is pretty much a code version of whatever is found in flex and bison. I really like the `FollowedBy` method, with the type parameter!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:34:59.607", "Id": "14412", "Score": "0", "body": "I really like your idea :) But don't have much time on my hand... if you manage to \"abstract away\" the parser details and leave us to describe the structure of what we're parsing, then I'd probably use your library a lot, it is a lot easier to read than that of many others. Does the parser then generate something that evaluates the data being fed to it lazily, or do you need to use it as a serializer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:39:17.030", "Id": "14413", "Score": "0", "body": "Well, it takes a stream of characters and parses according to whatever given rules. The output is always a single object of the given type that you declared the parser to produce. It will consume the input in one swoop, since that's needed to confirm the validity of the grammar, usually. It'll execute it's actions as soon as possible though, if that makes sense to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T21:37:42.397", "Id": "14416", "Score": "0", "body": "Makes sense, was just wondering if the root element were a list, if it would support `IEnumerable` for improved streaming. Sometimes you just don't care about the correctness of the grammar if performance is important. Just expect it to be correct and handle the issues when they occur ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T23:33:12.487", "Id": "32287", "Score": "0", "body": "I love where you've been taking this... I might use your library in the near future :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:01:37.370", "Id": "9199", "ParentId": "9104", "Score": "3" } }, { "body": "<p>The <code>Productions()</code> method is clearly something with side effects, since you are calling it and not saving any return value; shouldn't its name include a verb, then?</p>\n\n<p>Something like <code>SetProductions()</code> or <code>AddProductions()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:54:47.157", "Id": "14439", "Score": "0", "body": "It probably should, I have been too seduced by functional programming and lambdas to miss what actually was my goal. I'm working on redesigning the configuration interface. The new version will probably have this named `IsMadeUpBy()` which is followed by a bunch of `FollowedBy`. Something to that effect. Thanks for your input!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:46:31.537", "Id": "9219", "ParentId": "9104", "Score": "2" } } ]
{ "AcceptedAnswerId": "9199", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T10:32:50.813", "Id": "9104", "Score": "1", "Tags": [ "c#", "parsing", "library" ], "Title": "Parsing library interface" }
9104
<p>I'm trying to implement <a href="http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml" rel="nofollow">this algorithm for computing LCM</a> (from the cut-the-knot website). This is my Java code:</p> <pre><code>public class LcmAlgorithm { public static void main(String[] args) { long[] input = { 28, 50, 14 }; System.out.println(lcm(input)); } private static long lcm(long[] inputs) { long[] compute = inputs.clone(); while (!allEqual(compute)) { int minIx = minValueIndex(compute); compute[minIx] += inputs[minIx]; } return compute[0]; } private static boolean allEqual(long[] arr) { for (int i = 0; i &lt; arr.length - 1; i++) { if (arr[i] != arr[i + 1]) return false; } return true; } private static int minValueIndex(long[] arr) { long min = java.lang.Long.MAX_VALUE; int ix = 0; for (int i = 0; i &lt; arr.length; i++) { if (arr[i] &lt; min) { min = arr[i]; ix = i; } } return ix; } } </code></pre> <p>It works, but I'm pretty new to Java and I'm not sure my code is optimal (or maybe it's embarrassing...?). I'd like to hear what do you think of my code and how I can improve it. (BTW, I have a background in .NET programming.)</p> <p>Thanks.</p>
[]
[ { "body": "<p>I've included my review comments in the revised code below as program comments, \nunmistakable because there weren't any comments in the OP.\nHmm. That's not a good sign. Though, I can't say that I've helped that much. Backward-looking reviewer comments make a poor substitute for useful forward-looking developer comments.</p>\n\n<pre><code>public class LcmAlgorithm {\n\n /* Making \"main\" the only public member clearly limits this as a \n stand-alone \"toy\", and that's OK -- it is what it is.\n\n Yet, you might want to get in the habit of deciding up front which\n functions are purposely permanently private and which you'd\n consider exposing as public in a \"real world\" implementation.\n This makes your intent clearer to a reviewer (or your future self).\n\n On the other hand, arguably, you should only expose something as public \n when/if you have to \n (because you have an actual external caller -- at least a unit test).\n With that in mind, a good short-term compromise might be to comment \n your intent on the private declaration with e.g. '// candidate for public'.\n */\n\n public static void main(String[] args) {\n long[] input = { 28, 50, 14 };\n // Use the Object, Luke.\n LcmAlgorithm lcmAlgorithm = new LcmAlgorithm(input);\n System.out.println(lcmAlgorithm.lcm());\n }\n\n // Was named \"inputs\" but its role is more important than its origin.\n // Note: some people prefer plurals for collection names.\n // Whatever you choose, be consistent \n // -- not \"input\" here and \"inputs\" there.\n private final long[] increment;\n\n // Was \"compute\" -- don't verb your data names\n // (\"sum\" sits on the verb/noun fence).\n private long[] sum;\n\n private LcmAlgorithm(long[] input) { // candidate for public\n assert input.length &gt; 0;\n // Initializing 'increment' here \n // (vs. with an argument to lcm) allows declaration as final\n increment = input.clone();\n // Initializing both 'increment' and initial 'sum' here\n // saves re-computes if lcm is called more than once.\n sum = input.clone();\n }\n\n // The name LcmAlgorithm.lcm seems a little redundant\n // -- some alternatives are \"compute\", stressing the action\n // (perhaps too much?) or \"result\".\n // \"result\" may be especially apropos since if you call the\n // function a second time on the same object, you get the\n // result again with very little computation.\n private long lcm() { // candidate for public\n while (!allSumsEqual()) {\n int minIx = minSumIndex();\n sum[minIx] += increment[minIx];\n }\n return sum[0];\n }\n\n // The next two methods have been slightly simplified, including\n // being made instance methods to get implicit\n // access to the array member, and better leveraging\n // the asserted first element.\n private boolean allSumsEqual() {\n final long firstSum = sum[0];\n for (int i = 1; i &lt; sum.length; i++) {\n if (firstSum != sum[i])\n return false;\n }\n return true;\n }\n\n private int minSumIndex() {\n long min = sum[0];\n int minIx = 0;\n\n for (int i = 1; i &lt; sum.length; i++) {\n if (sum[i] &lt; min) {\n min = sum[i];\n minIx = i;\n }\n }\n return minIx;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:18:06.220", "Id": "9113", "ParentId": "9106", "Score": "3" } }, { "body": "<p>Your code is fine and should be pretty fast. The only downside is that it takes a while to understand exactly what you are doing. Also if you have no control about the input of your program you need to validate that it at some point (normally right after the user made his input). Your code would throw <code>NullPointerException</code>s and <code>ArrayIndexOutOfBoundsException</code>s.</p>\n\n<p>You stated that you are new with Java so I rewrote your code to use some of the standard libraries and used classes for an easier understanding of the used algorithm. </p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class LcmAlgorithm {\n\n public static void main(String[] args) {\n //ArrayList implements the interface List\n List&lt;LcmNumber&gt; input = new ArrayList&lt;LcmNumber&gt;();\n input.add(new LcmNumber(3));\n input.add(new LcmNumber(6));\n input.add(new LcmNumber(8));\n System.out.println(lcm(input)); \n }\n\n private static long lcm(List&lt;LcmNumber&gt; input) {\n //I added this to show how to validate parameters\n //The left part of the condition will be executed first and if already returning false the right part won't be executed\n //This is important because no NullPointerException will be thrown this way\n if(input == null || input.size() == 0){\n throw new IllegalArgumentException(\"The argument must have at least a size of one\");\n }\n\n //Collections provide a lot of useful methods for manipulating Lists\n //If you work with Arrays the class Arrays will be helpful\n while (Collections.min(input).compareTo(Collections.max(input))!=0) {\n Collections.min(input).increment();\n }\n\n return input.get(0).getCurrentValue();\n }\n}\n\n//Comparable is necessary so the Collections class can do its magic. It defines the method compareTo\nclass LcmNumber implements Comparable&lt;LcmNumber&gt;{\n\n private long currentValue;\n private long startValue;\n\n public LcmNumber(long number){\n startValue = currentValue = number;\n }\n\n public long getCurrentValue(){\n return currentValue;\n }\n\n public void increment(){\n currentValue += startValue;\n }\n\n @Override\n // compareTo expects the following for the returned integer:\n // - negative means this number is smaller than otherNumber\n // - zero means this number is equal to otherNumber\n // - positive means this number is larger than otherNumber\n public int compareTo(LcmNumber otherNumber) {\n //I am using the already implemented compareTo Method of the Long class for convenience\n return (Long.valueOf(currentValue)).compareTo(otherNumber.getCurrentValue());\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T11:11:24.287", "Id": "9412", "ParentId": "9106", "Score": "1" } }, { "body": "<p>You can use an enhanced for loop here:</p>\n\n<pre><code>private static boolean allEqual(long[] arr) {\n for (long value : arr) {\n if (arr[0] != value)\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>An optimization idea would be computing <code>allEqual</code> and <code>minValueIndex</code> in one go, but I guess that would hurt readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T17:36:09.447", "Id": "9424", "ParentId": "9106", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T11:07:59.970", "Id": "9106", "Score": "3", "Tags": [ "java", "algorithm" ], "Title": "Algorithm for computing LCM (least common multiple)" }
9106
<pre><code>def as_size( s ) prefix = %W(TiB GiB MiB KiB B) s = s.to_f i = prefix.length - 1 while s &gt; 512 &amp;&amp; i &gt; 0 s /= 1024 i -= 1 end ("%#{s &gt; 9 ? 'd' : '.1f'} #{prefix[i]}" % s).gsub /\.0/, '' end </code></pre> <p>I'd like a clean and fast code to convert raw file size to human-readable format. Any hints?</p> <p>Update (faster format):</p> <pre><code>def as_size( s ) prefix = %W(TiB GiB MiB KiB B) s = s.to_f i = prefix.length - 1 while s &gt; 512 &amp;&amp; i &gt; 0 s /= 1024 i -= 1 end ((s &gt; 9 || s.modulo(1) &lt; 0.1 ? '%d' : '%.1f') % s) + ' ' + prefix[i] end </code></pre> <p>Update (freeze the constant):</p> <pre><code>PREFIX = %W(TiB GiB MiB KiB B).freeze def as_size( s ) s = s.to_f i = PREFIX.length - 1 while s &gt; 512 &amp;&amp; i &gt; 0 i -= 1 s /= 1024 end ((s &gt; 9 || s.modulo(1) &lt; 0.1 ? '%d' : '%.1f') % s) + ' ' + PREFIX[i] end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:47:36.467", "Id": "25098", "Score": "2", "body": "I wouldn't worry so much about the performance of this code. I ran the benchmark that you provided, and found that your code is 1 microsecond faster than Jordan's, which is 1 microsecond faster than Alex's. If you need to worry about microseconds in string formatting, you ought not be using Ruby. Use whatever version of the code reads best and makes the most sense to you and the guy who will have to maintain your code." } ]
[ { "body": "<p>Possible solution: <code>reduce</code> your input to required precision. Returned result construction also reads cleaner with this approach:</p>\n\n<pre><code>def as_size(s)\n units = %W(B KiB MiB GiB TiB)\n\n size, unit = units.reduce(s.to_f) do |(fsize, _), utype|\n fsize &gt; 512 ? [fsize / 1024, utype] : (break [fsize, utype])\n end\n\n \"#{size &gt; 9 || size.modulo(1) &lt; 0.1 ? '%d' : '%.1f'} %s\" % [size, unit]\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:25:49.163", "Id": "14373", "Score": "0", "body": "Thanks for the modulo and format tips, but the reduce approach here is a bit cryptic and 1.5 times slower. Here's a gist https://gist.github.com/1868681 of the benchmark." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T14:23:50.643", "Id": "9108", "ParentId": "9107", "Score": "5" } }, { "body": "<p>It's worth looking at <a href=\"https://github.com/lifo/docrails/blob/master/actionpack/lib/action_view/helpers/number_helper.rb#L305-368\" rel=\"nofollow\">how Rails does this</a> in its <code>number_to_human_size</code> helper. Rather than iteration it just calculates the exponent (log x / log 1024). Paring it down to the bare essentials it looks something like this:</p>\n\n<pre><code>UNITS = %W(B KiB MiB GiB TiB).freeze\n\ndef as_size number\n if number.to_i &lt; 1024\n exponent = 0\n\n else\n max_exp = UNITS.size - 1\n\n exponent = ( Math.log( number ) / Math.log( 1024 ) ).to_i # convert to base\n exponent = max_exp if exponent &gt; max_exp # we need this to avoid overflow for the highest unit\n\n number /= 1024 ** exponent\n end\n\n \"#{number} #{UNITS[ exponent ]}\"\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T07:40:10.217", "Id": "15282", "Score": "0", "body": "Good one on freezing the constant, thanks, it speeds up a lot! But still, your suggestion is ~20% slower than simple loop. You can run the benchmark, I updated it with the new code: https://gist.github.com/1868681" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T03:28:17.897", "Id": "9661", "ParentId": "9107", "Score": "3" } }, { "body": "<p>Another solution is to add the method to the Numeric class,</p>\n<pre><code>class Numeric\n PREFIX = %W(TiB GiB MiB KiB B).freeze\n\n def to_bibyte\n s = self.to_f\n i = PREFIX.length - 1\n while s &gt; 512 &amp;&amp; i &gt; 0\n i -= 1\n s /= 1024\n end\n ((s &gt; 9 || s.modulo(1) &lt; 0.1 ? '%d' : '%.1f') % s) + ' ' + PREFIX[i]\n end\nend\n</code></pre>\n<p>and then call it like,</p>\n<p>i=123049158\nputs i.to_bibyte</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T11:23:24.113", "Id": "252585", "ParentId": "9107", "Score": "1" } } ]
{ "AcceptedAnswerId": "9661", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T13:16:35.503", "Id": "9107", "Score": "3", "Tags": [ "ruby" ], "Title": "Printing human-readable number of bytes" }
9107
<p>I figure there is a better way that I should be doing this:</p> <pre><code>if !db.collection_names.include?("reports".to_s) db.create_collection("reports") end if !db.collection_names.include?("days".to_s) db.create_collection("days") end if !db.collection_names.include?("users".to_s) db.create_collection("users") end </code></pre>
[]
[ { "body": "<p>Well, firstly: <code>\"string\".to_s</code> is entirely redundant. That's already a <code>String</code>, so converting it again is just wasting your (processor's) time. </p>\n\n<p>Secondly, writing <code>if</code> blocks with just one line and no <code>else</code> wastes a good deal of vertical real estate. I'd recommend that instead of </p>\n\n<pre><code>if condition\n statement\nend\n</code></pre>\n\n<p>you should write</p>\n\n<pre><code>statement if condition\n</code></pre>\n\n<p>Ruby has <code>unless</code> as the opposite to <code>if</code>, and when you find yourself writing <code>if !...</code>, it's better to use <code>unless ...</code> instead. This is mostly because of convention -- Ruby programmers use <code>unless</code> a lot more, so it's quicker to parse.</p>\n\n<p>As for shortening the method calls themselves, you could just pass <code>strict: false</code> in with the name, so each individual call becomes more like this:</p>\n\n<pre><code>db.create_collection('name', strict: false)\n</code></pre>\n\n<p>Then you don't need the condition at all.</p>\n\n<p>Then, since you have three objects on which you want to perform the same action, you can put them in an array:</p>\n\n<pre><code>['reports', 'days', 'users']\n</code></pre>\n\n<p>(or use the fancier <code>%w{ reports days users }</code>, like I do below, but you'll want to read up on its gotchas first)</p>\n\n<p>Then we can loop through that array:</p>\n\n<pre><code>%w{ reports days users }.each do |name|\n #...\nend\n</code></pre>\n\n<p>And in place of <code>#...</code> we put the code to create the table:</p>\n\n<pre><code>db.create_collection(name, strict: false)\n</code></pre>\n\n<p>Or, if you don't want to rely on swallowing errors:</p>\n\n<pre><code>db.create_collection(name) unless db.collection_names.include?(name)\n</code></pre>\n\n<p>If we put that all together, it becomes this:</p>\n\n<pre><code>%w{ reports days users }.each do |name|\n db.create_collection(name) unless db.collection_names.include?(name)\nend\n</code></pre>\n\n<p>Now, to add a collection, all you have to do is add it to the list. For example, if you wanted to add one called \"years\", add <code>years</code> in to the <code>%w</code>:</p>\n\n<pre><code>%w{ reports days users years }.each do |name|\n db.create_collection(name) unless db.collection_names.include?(name)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-28T15:25:19.910", "Id": "95001", "ParentId": "9109", "Score": "2" } } ]
{ "AcceptedAnswerId": "95001", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T16:14:23.583", "Id": "9109", "Score": "3", "Tags": [ "ruby" ], "Title": "Validating Mongo collections" }
9109
<blockquote> <p><strong><em>K&amp;R</em> 1.8 exercise:</strong></p> <p>Write a program to count blanks,tabs, and newlines.</p> </blockquote> <p>Is this a viable solution to the problem and is it properly formatted? I have never programmed in C before, so I just wanted to see if this is proper c programming as it were.</p> <pre><code>#include &lt;stdio.h&gt; /* count blanks,tabs and new lines*/ int main(void) { /* initializes blank,tab,newline and c sets them all to 0*/ int blank,tab,newline; int c; blank = 0; tab = 0; newline = 0; while((c = getchar()) != EOF) if (c =='\n') ++newline; if (c == ' ') ++blank; if (c == '\t') ++tab; printf("Blanks: %d\nTabs: %d\nLines: %d\n", blank, tab, newline); return 0; } </code></pre>
[]
[ { "body": "<p>That is a great start. It's almost perfect logically.</p>\n\n<p>First thing that caught my eye however is the lack of indentation. It could just be that something got lost in the transition between your code and your post here, I don't know. But you should indent whenever starting a new block. You indented the <code>if</code> bodies, that's good, but you missed the function body of <code>main()</code>, the <code>while</code> block. Had you done this, you would have been able to identify the following problem in your code.</p>\n\n<p>The body of the while loop consists only of the first <code>if</code> statement that is counting newlines. You are effectively counting only newlines and not counting the blanks or tabs. This is how you have your code written but let's include some correct indentation:</p>\n\n<pre><code>while((c = getchar()) != EOF)\n if (c == '\\n')\n ++newline;\nif (c == ' ')\n ++blank;\nif (c == '\\t')\n ++tab;\n</code></pre>\n\n<p>Do you see the problem now?</p>\n\n<p>There's a couple of ways to fix this but let me start with what you should have done always. If you ever have a block that would span multiple lines, you should <em>always</em> wrap the block in curly braces. That way there's no confusion what goes where. It's more forgivable to not include them if it's just a single line (just like you have in your individual <code>if</code> statements) but all three of them belongs to the <code>while</code> body so they should be in braces.</p>\n\n<p>The other thing to about this code is that those three <code>if</code> statements are mutually exclusive. Only one of them could ever be hit for a given character, <code>c</code>. So you shouldn't have created a series of <code>if</code> statements like you did here, but instead a set of <code>if</code>/<code>else</code> blocks. That way the following <code>if</code> statements don't get executed if the preceding one was satisfied.<br>\n<sub>This could have fixed the logical error for the <code>while</code> loop too but it's still important to include the braces regardless so there's no confusion.</sub></p>\n\n<p>That block should have looked more like this:</p>\n\n<pre><code>while((c = getchar()) != EOF)\n{\n if (c == '\\n')\n ++newline;\n else if (c == ' ')\n ++blank;\n else if (c == '\\t')\n ++tab;\n}\n</code></pre>\n\n<hr>\n\n<p>Now there's some minor style issues in your code. You can follow these if you wish, it's just personal preference. But it could help other people read your code easier with little chance for confusion.</p>\n\n<p>Your variable declarations should go on separate lines and the initializations of the variable should occur in the declaration. I'd also pluralize the variables since they are used as counters. In your head, if you read out the values of the variables what makes more sense? \"I have 5 <code>tab</code>,\" or \"I have 5 <code>tabs</code>? The comment was off a bit, we're not initializing <code>c</code> here, just declaring it.</p>\n\n<p>Do this:</p>\n\n<pre><code>/* initializes blanks, tabs, and newlines and sets them all to 0 */\n/* declares c to hold the read-in characters */\nint c;\nint blanks = 0;\nint tabs = 0;\nint newlines = 0;\n</code></pre>\n\n<p>And to a lesser degree, a call to <code>printf()</code> with parameters should be printed a single line at a time. The newline characters sprinkled in the format string makes it less clear how many lines this will print out.</p>\n\n<p>Do this:</p>\n\n<pre><code>printf(\"Blanks: %d\\n\", blanks);\nprintf(\"Tabs: %d\\n\", tabs);\nprintf(\"Lines: %d\\n\", newlines);\n</code></pre>\n\n<p>So applying all of the above, your code would look like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n /* count blanks, tabs and newlines */\n\nint main(void)\n{\n /* initializes blanks, tabs, and newlines and sets them all to 0 */\n /* declares c to hold the read-in characters */\n int c;\n int blanks = 0;\n int tabs = 0;\n int newlines = 0;\n\n while((c = getchar()) != EOF)\n {\n if (c =='\\n')\n ++newlines;\n else if (c == ' ')\n ++blanks;\n else if (c == '\\t')\n ++tabs;\n }\n\n printf(\"Blanks: %d\\n\", blanks);\n printf(\"Tabs: %d\\n\", tabs);\n printf(\"Lines: %d\\n\", newlines);\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-02T00:56:24.523", "Id": "30751", "Score": "1", "body": "A few remarks: (1) Some argue that even single-line blocks should be surrounded with curly-braces; (2) It can be argued that for mutually exclusive conditions on a single integer variable `switch` is a better choice than `if-else-if-else-if-else-...`, and (3) Splitting what is basically a single print into 3 distinct `printf`s can cause issues regarding flushing etc. and is unnecessary to address the issue you raised. A better alternative might be `printf(\"Blanks: %d\\n\" <nl> \"Tabs: %d\\n\" <nl> \"Lines: %d\\n\", <nl> blank, tab, newline);`, where <nl> represents newline in the source file." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:29:50.943", "Id": "9116", "ParentId": "9111", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T16:52:20.337", "Id": "9111", "Score": "2", "Tags": [ "c", "beginner" ], "Title": "Counting blanks, tabs, and newlines" }
9111
<p>I wrote a simple class to deal with parsing and handling URIs for the project I'm currently working on, since it relies a lot on that functionality (eg the Router class and some HTML helpers). Here is the code already commented:</p> <pre><code>&lt;?php # URI class class uri { # URI scheme public $scheme; # URI host public $host; # URI user public $user; # URI password public $password; # URI port public $port; # URI path public $path; # URI query public $query; # URI fragment public $fragment; # Default constructor for the URI public function __construct($uri = null) { # No URI is set, the current request URI will be used if($uri == null) { # Predefine the empty parts array $uri_parts = array(); # Extract the scheme part of the URI and add it the to array if https if(array_key_exists('HTTPS', $_SERVER)) array_push($uri_parts, 'https://'); # Extract the scheme part of the URI and add it the to array if http if(!array_key_exists('HTTPS', $_SERVER)) array_push($uri_parts, 'http://'); # Extract the host part of the URI and add it to the array if https if(array_key_exists('SERVER_NAME', $_SERVER)) array_push($uri_parts, $_SERVER['SERVER_NAME']); # Extract the request URI itself and add it to the array if(array_key_exists('REQUEST_URI', $_SERVER)) array_push($uri_parts, $_SERVER['REQUEST_URI']); # Set the URI string to be processed later $uri = implode($uri_parts); } # An URI is provided in string form if($uri != null and !is_array($uri)) { # Regular Expression from RFC 2396 (appendix B) preg_match('"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?"', $uri, $matches); # Extract the URI scheme from the string if(array_key_exists(2, $matches)) $this-&gt;scheme = $matches[2]; # Extract the URI authority from the string if(array_key_exists(4, $matches)) $authority = $matches[4]; # Extract the URI path from the string if(array_key_exists(5, $matches)) $this-&gt;path = $matches[5]; # Extract the URI query from the string if(array_key_exists(7, $matches)) $this-&gt;query = $matches[7]; # Extract the URI fragment from the string if(array_key_exists(9, $matches)) $this-&gt;fragment = $matches[9]; # Extract username, password, host and port from authority preg_match('"(([^:@]*)(:([^:@]*))?@)?([^:]*)(:(.*))?"', $authority, $matches); # Extract the URI username from the authority part if(array_key_exists(2, $matches)) $this-&gt;user = $matches[2]; # Extract the URI password from the authority part if(array_key_exists(4, $matches)) $this-&gt;password = $matches[4]; # Extract the URI hostname from the authority part if(array_key_exists(5, $matches)) $this-&gt;host = $matches[5]; # Extract the URI port from the authority part if(array_key_exists(7, $matches)) $this-&gt;port = $matches[7]; # Get the rid of the leading path slash if its present in the string if(substr($this-&gt;path, 0, 1) == '/') $this-&gt;path = substr($this-&gt;path, 1); # Get the rid of the ending path slash if its present in the string if(substr($this-&gt;path, -1, 1) == '/') $this-&gt;path = substr($this-&gt;path, 0, -1); # Set the path to an array by exploding it with the default delimiter $this-&gt;path = explode('/', $this-&gt;path); # Make sure that the array is really empty if the path was empty from the beginning if(array_key_exists(0, $this-&gt;path) and empty($this-&gt;path[0])) $this-&gt;path = array(); # Split the query string into an array parse_str($this-&gt;query, $query); $this-&gt;query = $query; } # An URI is provided in array form if($uri != null and is_array($uri)) { # Set the scheme of the URI if(array_key_exists('scheme', $uri)) $this-&gt;scheme = $uri['scheme']; # Set the hostname of the URI if(array_key_exists('host', $uri)) $this-&gt;host = $uri['host']; # Set the user of the URI if(array_key_exists('user', $uri)) $this-&gt;user = $uri['user']; # Set the password of the URI if the pass key is used if(array_key_exists('pass', $uri)) $this-&gt;scheme = $uri['pass']; # Set the password of the URI if the password key is used if(array_key_exists('password', $uri)) $this-&gt;password = $uri['password']; # Set the port of the URI if(array_key_exists('port', $uri)) $this-&gt;port = $uri['port']; # Set the path of the URI if(array_key_exists('path', $uri)) $this-&gt;path = $uri['path']; # Set the query of the URI if(array_key_exists('query', $uri)) $this-&gt;path = $uri['query']; # Set the fragment of the URI if the anchor key is used if(array_key_exists('anchor', $uri)) $this-&gt;fragment = $uri['anchor']; # Set the fragment of the URI if the fragment key is used if(array_key_exists('fragment', $uri)) $this-&gt;fragment = $uri['fragment']; } } # Returns the URI as a string # You can specify what parts should be built public function build(array $parts = array('scheme', 'user', 'password', 'host', 'path', 'query', 'fragment')) { # Predefine an array of parts $uri_parts = array(); # Attach the URI scheme to the parts array if not empty if(in_array('scheme', $parts) and !empty($this-&gt;scheme)) array_push($uri_parts, $this-&gt;scheme . '://'); # Attach the URI user to the parts array if not empty if(in_array('user', $parts) and !empty($this-&gt;user)) array_push($uri_parts, $this-&gt;user); # Attach the URI password to the parts array if not empty if(in_array('password', $parts) and !empty($this-&gt;password)) array_push($uri_parts, ':' . $this-&gt;password); # Attach the URI user prefix to the parts array if not empty if(in_array('user', $parts) and !empty($this-&gt;user)) array_push($uri_parts, '@'); # Attach the URI host to the parts array if not empty if(in_array('host', $parts) and !empty($this-&gt;host)) array_push($uri_parts, $this-&gt;host.'/'); # Attach the URI path to the parts array if not empty if(in_array('path', $parts) and count($this-&gt;path) &gt; 0) array_push($uri_parts, implode('/', $this-&gt;path)); # Attach the URI query to the parts array if not empty if(in_array('query', $parts) and count($this-&gt;query) &gt; 0) array_push($uri_parts, '?' . http_build_query($this-&gt;query, '', '&amp;')); # Attach the URI fragment to the parts array if not empty if(in_array('fragment', $parts) and !empty($this-&gt;fragment)) array_push($uri_parts, '#' . $this-&gt;fragment); # Return the URI string return implode($uri_parts); } # Default convertion to a string, returns the complete URI public function __toString() { return $this-&gt;build(); } } </code></pre> <p>The most simple usage of the class would be something like that</p> <pre><code>$uri = new uri; $uri-&gt;path = array('some', 'real', 'path'); echo $uri; </code></pre> <p>which would output <a href="http://localhost/some/real/path" rel="nofollow">http://localhost/some/real/path</a> given that you test it on localhost.</p> <ol> <li>Are there any problems you see with the possible usage of that class?</li> <li>Is there any way you would improve its functionality?</li> </ol> <p>EDIT: Please notice that leading and trailing slashes are stripped from the path string on purpose, because they are unwanted in my current environment and should never appear in the URI.</p>
[]
[ { "body": "<h1>Information Hiding</h1>\n\n<p><br/>\nYour class contains all public properties and methods.</p>\n\n<p>This means that users of the class are exposed to all of the internal properties, causing the following problems:</p>\n\n<ol>\n<li><strong>Confusion</strong> - With so many publicly accessible properties and methods the user doesn't know which property or method to interact with first. There are more choices for them to look at.</li>\n<li><strong>Accident Prone</strong> - The user has full power over the public properties. This could lead them to modify them in harmful ways (accidentally). Without restricting the access to only tested public methods we cannot limit the scope of possible errors (accidents) that can be created.</li>\n</ol>\n\n<p><br/></p>\n\n<h1>Work in the Constructor</h1>\n\n<p><br/>\nYour constructor does real work rather than just configuring the object.</p>\n\n<p>Doing real work in the constructor makes it harder for you to test and extend from this class. Miško Hevery says it better than i could <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\" rel=\"nofollow\">here</a>.</p>\n\n<p><br/></p>\n\n<h1>Suggested Interface</h1>\n\n<p><br/>\nI would try to keep the interface as simple as possible. What I suggest below is mainly to take the work away from the constructor. You can modify it to your own needs.</p>\n\n<pre><code>class uri\n{\n # URI scheme\n protected $scheme;\n\n # URI host\n protected $host;\n\n # URI user\n protected $user;\n\n # URI password\n protected $password;\n\n # URI port\n protected $port;\n\n # URI path\n protected $path;\n\n # URI query\n protected $query;\n\n # URI fragment\n protected $fragment;\n\n # Default constructor for the URI\n public function __construct()\n {\n # No setup required.\n }\n\n # Set the URI current URI.\n public function setCurrent()\n {\n # I would also use isset rather than array_key_exists in this case.\n # $_SERVER['HTTP'] does not exist, use an if/else on the HTTPS key.\n # The property values can be set directly.\n\n # This is basically the if($uri == null) {} code.\n $this-&gt;scheme = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';\n\n if (isset($_SERVER['SERVER_NAME']))\n {\n $this-&gt;host = $_SERVER['SERVER_NAME'];\n }\n\n if (isset($_SERVER['REQUEST_URI']))\n {\n # Process the URI into the object properties.\n }\n }\n\n # Set the URI from a string according to RFC 2396 (appendix B)\n public function setFromString($uri)\n {\n if (!is_string($uri))\n {\n throw new \\InvalidArgumentException(\n __METHOD__ . ' uri must be a string.');\n }\n\n # if($uri != null and !is_array($uri)) {} code goes here. \n }\n\n # An URI is provided in array form\n public function setFromArray(Array $uri)\n {\n # if($uri != null and is_array($uri)) {} code goes here.\n }\n\n # Returns the URI as a string.\n public function __toString()\n {\n # Ensure that all required properties are set.\n if (!isset($this-&gt;host, $this-&gt;scheme)) # etc.\n {\n throw new \\BadMethodCallException(\n __METHOD__ . ' url properties have not been set.');\n }\n\n $uri = $this-&gt;scheme . $this-&gt;host;\n\n if (isset($this-&gt;query))\n {\n # Add optional uri part here.\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T17:08:23.453", "Id": "14335", "Score": "0", "body": "Thanks for your feedback, I'm already refactoring this class to become somewhat close to what you have suggested. Still, one little notice, the __toString() method allows for URI's without the scheme and authority set being returned as well by design. By the way, thanks for that article, I will look into it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T08:07:58.793", "Id": "9136", "ParentId": "9114", "Score": "2" } }, { "body": "<p>The big one is all your properties (variables) are public! This is really bad, because it means that an instance of this object has no real control whatsoever over what its own state is. Any external agent can inject anything it wants into public properties and it can all too easily result, through accident of malicious intent, in the internal state of the class being corrupted. </p>\n\n<p>You need tighter control over your class state. There are two methods involved with doing this. The first is simply to set your instance variables protected instead of public. Now they can't be messed with from outside. </p>\n\n<p>Of course now you also don't have any legitimate access to the instance variables either, but this is where the second technique comes in. For each instance variable you want to make accessible to the outside in some way, you need to create a pair of methods for getting and setting its value. </p>\n\n<p>Example:</p>\n\n<pre><code>class Uri\n{\n protected $protocol = '';\n\n // Getter\n public function getProtocol ()\n {\n return ($this -&gt; protocol);\n }\n\n // Setter\n public function setProtocol ($newProto)\n {\n $this -&gt; protocol = $newProto;\n return (true);\n }\n}\n</code></pre>\n\n<p>At first glance this might seem like unnecessary extra work, but because this is the most basic example of getters and setters it doesn't illustrate the benefits that such an approach bestows on the programmer. </p>\n\n<p>First, you can now have read-only/write-only properties. If you need a read-only property, for example, simply don't implement a setter for the property in question. Now it can't be modified from outside. </p>\n\n<p>More importantly, it allows a lot of control over what happens when an instance variable has changed. It can be used to restrict their values to valid states, notify some other internal part of the class that a property has changed, and so on. </p>\n\n<p>Say you want to limit the protocol to http and https in my above example class:</p>\n\n<pre><code>public function setProtocol ($newProto)\n{\n switch ((string) $newProto) // Casting to the expected data type is a good idea here because PHP type juggling can cause serious screwups otherwise\n {\n case 'http' :\n case 'https' :\n $this -&gt; protocol = $newProto;\n return (true);\n break;\n default :\n throw new InvalidArgumentException ('Only HTTP or HTTPS allowed');\n break;\n }\n}\n</code></pre>\n\n<p>As you can see, it is now impossible to set the protocol variable to any state other than the ones you allow. </p>\n\n<p>This isn't the extent of the power of getters and setters, the benefits they confer are huge. You can, for example, use a getter to do lazy loading of instance variables. Say you have one instance variable that isn't used that often and requires an expensive operation (a DB lookup, a file load and parse, connection to a potentially slow external server, etc), you can write your class to only load the data on demand, and have the getter do the actual data fetch the first time its called. It can then cache the result and skip the data fetching state on subsequent calls. Doing this improves performance because the expensive operation is only done if its results are actually needed, and it's only done once per object instance. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T17:02:12.227", "Id": "14334", "Score": "0", "body": "While I see your point and absolutely agree on that, I was trying to move away from setters and getters to keep that class as simple as possible. The best solution I came up with to this moment is setting properties, which, if modified wrong, could lead to an unexpected result to private and writing a magic __set($property, $value) method which will call a private method set_property($value), which then will do any validation whatsoever. Same applies to getters. Does this approach sound better to you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T17:54:12.597", "Id": "14336", "Score": "0", "body": "I'd tend to avoid the magic setters and getters. They can cause a hell of a lot of confusion, and the IDE you're using won't be able to help you out with hinting (if it supports that. Netbeans does and I'm fairly sure Eclipse does too). Also __get and __set have pretty poor performance compared to real setters and getters. I know it's a PITA writing getters and setters for everything but in the long run it will make your life a lot easier." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T09:06:48.007", "Id": "9137", "ParentId": "9114", "Score": "1" } }, { "body": "<p>Reviewing your code only leads to one clear statement: You've done too much. Code for that already exists. As you use PHP build in functions, you should use a class that does URL parsing itself since longer and is tested. I suggest you to take <a href=\"http://pear.php.net/package/Net_URL2/\" rel=\"nofollow\"><code>Net_URL2</code></a> from the pear repository.</p>\n\n<p>Even if you don't want to use it for obscure reasons (you want to eat your own dogfood probably), you can review the code that exists.</p>\n\n<p><a href=\"http://php.net/parse_url\" rel=\"nofollow\"><code>parse_url</code></a> - which you use - is not following the standards btw. .</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T12:43:08.890", "Id": "11901", "ParentId": "9114", "Score": "2" } }, { "body": "<p>I think you need to look first at the problem you're trying to solve rather than the code you've written.</p>\n\n<p><strong>Is a class necessary</strong></p>\n\n<p>A url is just a string (or an array if it's split into component parts) - is a class <em>really</em> necessary to represent a url? Or are a couple of functions required in the (e.g.) router class to parse and build urls? Reviewing existing code that does a similar things (php frameworks, pear, github, the blogsphere) would help evaluate whether the uri class is appropriate - bear in mind a web page typically has 10s or 100s of urls on it, and it's not free to instanciate many objects.</p>\n\n<p>This is likely to be faster to execute, and effectively easier to use:</p>\n\n<pre><code>$url = Router::url($args);\n</code></pre>\n\n<p>Than</p>\n\n<pre><code>echo new Uri($args);\n</code></pre>\n\n<p>If you find you're only using each instance of a class once - that's a relatively good indicator that a class is the wrong approach.</p>\n\n<p><strong>Is <em>so much</em> code necessary</strong></p>\n\n<p>The question states that the objective is:</p>\n\n<blockquote>\n <p>a simple class to deal with parsing and handling URIs</p>\n</blockquote>\n\n<p>Yet the code in the question isn't simple. It's 180 lines of code that mostly duplicates built-in php functions. To wrap the functionality in a class, simple would be (example and almost pseudo-code):</p>\n\n<pre><code>class url {\n protected $_url;\n\n function __construct($url) {\n $this-&gt;_url = parse_url($url);\n }\n\n function build() {\n return implode($this-&gt;_url);\n }\n\n function __get($key) {\n return $this-&gt;_url[$key];\n }\n\n function __set($key, $value) {\n $this-&gt;_url[$key] = (string)$value;\n }\n}\n</code></pre>\n\n<p><strong>Is the API intuitive</strong></p>\n\n<p>It would appear you'd use this class like so:</p>\n\n<pre><code>$url = new uri($args);\n$absolute = (string)$url; // implied\n$absolute = $url-&gt;build();\n$relative = $url-&gt;build(array('path', 'query', 'fragment'));\n</code></pre>\n\n<p>But the way the class works also permits:</p>\n\n<pre><code>$emptyString = $url-&gt;build(array('made', 'up', 'or', 'typos'));\n$nonsense = $url-&gt;build(array('password', 'path', 'fragment'));\n</code></pre>\n\n<p>Neither of these permutations should be possible and indicate that you need to know the internals of the class to use it. If you don't know how the class is storing the parts of a url, you can't use the class and/or will get no errors with mistakes, just nothing useful.</p>\n\n<p>This would be easier to use, and a lot less error prone:</p>\n\n<pre><code>$absolute = $url-&gt;absolute();\n$relative = $url-&gt;relative();\n</code></pre>\n\n<p>Since all the properties are public - it's not necessary to have a method which just returns a public property.</p>\n\n<p>Assuming the code in the question will be used in one form or another, here are some tips for refactoring the code to be easier to read, use and maintain:</p>\n\n<p><strong>Don't repeat yourself (DRY) #1</strong></p>\n\n<pre><code>if($uri == null) {\n ...\nif($uri != null and !is_array($uri)) {\n ...\nif($uri != null and is_array($uri)) {\n</code></pre>\n\n<p>That means in all cases the variable is tested 3 times if it's null, and twice if it's an array.</p>\n\n<p>A couple of side points: The first use of <code>is_array</code> is really testing if the variable is a string by inferrance - it would therefore be more appropriate to use <code>is_string</code>. Also by using type-insensitive checks an empty array or empty string are caught by the first if block (perhaps that's deliberate but it isn't obvious).</p>\n\n<p>Instead the code can be written as:</p>\n\n<pre><code>if(!$uri) {\n //get currenturl\n ...\n}\nif(!is_array($uri)) {\n ...\n} else {\n</code></pre>\n\n<p>Or, less nesting by using the principle of \"return early\":</p>\n\n<pre><code>if(!$uri) {\n //get currenturl\n ...\n}\nif(!is_array($uri)) {\n ...\n return;\n}\n// it's not empty and it's an array.\n</code></pre>\n\n<p>Also note that using negative checks can be harder to read - so it would infact be preferable to write as:</p>\n\n<pre><code>if(!$uri) {\n //get currenturl\n ...\n}\nif(is_string($uri)) {\n ...\n return;\n}\n// it's not empty and it's not a string.\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>if(!$uri) {\n ...\n return;\n}\nif(is_array($uri)) {\n ...\n return;\n}\n// it's not empty and its NOT an array.\n</code></pre>\n\n<p><strong>Don't repeat yourself (DRY) #2</strong></p>\n\n<pre><code>if(array_key_exists('HTTPS', $_SERVER)) array_push($uri_parts, 'https://');\n...\nif(!array_key_exists('HTTPS', $_SERVER)) array_push($uri_parts, 'http://');\n</code></pre>\n\n<p>In this block, the array key <code>HTTPS</code> is tested twice. But, unless it's a cli request it's not possible for <code>SERVER_NAME</code> or <code>REQUEST_URI</code> to be missing. This code is more approproate to acheive identical functionality:</p>\n\n<pre><code>if (empty($_SERVER['HTTPS'])) {\n $uri = 'http://';\n} else {\n $uri = 'https://';\n}\n$uri = $uri . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\n</code></pre>\n\n<p>That's one logical test instead of 4</p>\n\n<p><strong>Don't rewrite php functions</strong></p>\n\n<p>Built-in php functions are much faster to execute than equivalent user-land php code, and are more robust.</p>\n\n<pre><code>preg_match('\"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\"', $uri, $matches);\n...\npreg_match('\"(([^:@]*)(:([^:@]*))?@)?([^:]*)(:(.*))?\"', $authority, $matches);\n</code></pre>\n\n<p>This is exactly what <a href=\"http://php.net/manual/en/function.parse-url.php\" rel=\"nofollow\">parse_url</a> is for, this whole block appears to be identical to:</p>\n\n<pre><code>$parsed = parse_url($uri);\nforeach($parsed as $key =&gt; $value) {\n $this-&gt;$key = $value;\n}\n$this-&gt;path = explode('/', trim($this-&gt;path, '/'));\nparse_str($this-&gt;query, $this-&gt;query);\n</code></pre>\n\n<p><strong>Be consistent</strong></p>\n\n<p>This is the only reference to anchor:</p>\n\n<pre><code>if(array_key_exists('anchor', $uri)) $this-&gt;fragment = $uri['anchor'];\n</code></pre>\n\n<p>This is the only reference to pass:</p>\n\n<pre><code>if(array_key_exists('pass', $uri)) $this-&gt;scheme = $uri['pass'];\n</code></pre>\n\n<p>But it <em>should</em> be \"pass\" and not \"password\" (internally) so that the code used is consistent with the output of the <code>parse_url</code> function - on which the class <em>should</em> rely.</p>\n\n<p><strong>Don't repeat yourself (DRY) #3</strong></p>\n\n<p>The build method could be written as:</p>\n\n<pre><code>public function build($parts) {\n $this-&gt;_prepare($parts);\n foreach($parts as $field) {\n $return .= $this-&gt;_prepared[$field];\n }\n return $return;\n}\n\n/**\n * Ensure all bits of the url are in a position to just be concatenated\n */\nprotected function _prepare($parts) {\n $this-&gt;_prepared = array();\n foreach($parts as $field) {\n $this-&gt;_prepared[$field] = $this-&gt;$field;\n }\n if (!empty($this-&gt;_prepared['scheme'])) {\n $this-&gt;_prepared['scheme'] .= '://';\n }\n if (!empty($this-&gt;_prepared['user'])) {\n $this-&gt;_prepared['password'] .= '@';\n }\n if (!empty($this-&gt;_prepared['path'])) {\n if (is_array($this-&gt;_prepared['path'])) {\n $this-&gt;_prepared['path'] = implode('/', $this-&gt;_prepared['path']);\n }\n if ($this-&gt;_prepared['path'][0] !== '/') {\n $this-&gt;_prepared['path'] = '/' . $this-&gt;_prepared['path'];\n }\n }\n if (!empty($this-&gt;_prepared['query'])) {\n $this-&gt;_prepared['query'] = '?' . http_build_query($this-&gt;_prepared['query']);\n }\n if (!empty($this-&gt;_prepared['fragment'])) {\n $this-&gt;_prepared['fragment'] = '#' . $this-&gt;_prepared['fragment'];\n }\n}\n</code></pre>\n\n<p>In this way the embedded logic in the build method is separated and more obvious - and the repetative <code>in_array</code> <code>!empty</code> logic is avoided. It also becomes possible to run the <code>_prepare</code> function whenever the data changes rather than each time a call is made to return output.</p>\n\n<p><strong>Concusion</strong></p>\n\n<p>Some of the other answers have focussed on the use of public properties, on that: what does it matter. There are more fundamental concerns to address with the code presented in the question.</p>\n\n<p>Whenever writing code, try to apply the DRY principle not only to the code you write but also to the code as executed. In this way you get code that's easier and faster to read and run.</p>\n\n<p>The way the class works is only 'easy' to use if you want an absolute url. The build method should be refactored to permit only real possibilities. If you're already using the class with more permutations than just absolute and relative urls - you'll need to decide whether to change the calls or the code so that it still works.</p>\n\n<p>Assuming your code already works you're in a <em>perfect</em> position to write a few <a href=\"http://www.phpunit.de/manual/current/en/index.html\" rel=\"nofollow\">unit tests</a> for your class (if you don't already have some) - and then start tweaking it. Writing unit tests will give you the confidence to rip the guts out of any code and know that if/when the tests pass - you've safe to commit your changes and benefit from your shiny(er) code and/or new-found knowledge.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T17:30:57.167", "Id": "11928", "ParentId": "9114", "Score": "1" } } ]
{ "AcceptedAnswerId": "9137", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:20:35.280", "Id": "9114", "Score": "4", "Tags": [ "php", "parsing" ], "Title": "URI parsing and handling class" }
9114
<p>I'm not a programmer, but am playing around with a binary tree Class in Python and would like help with a recursive method to count interior nodes of a given tree.</p> <p>The code below seems to work, but is this solution the clearest, in terms of logic, for counting interior nodes? I'm keen that the code is the cleanest and most logical solution, whilst remaining recursive.</p> <p>The qualifier for being an interior node, as far as I'm aware here is, that an interior node should have a parent, and at least one child node.</p> <pre><code>def count_interior_nodes(self, root): """Return number of internal nodes in tree""" if(root.parent == None): # Root node so don't count, but recurse tree return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 0 elif (root.left != None or root.right != None): # Has parent, but isn't leaf node, so count and recurse return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 1 else: # Leaf node, so return zero return 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:42:02.770", "Id": "14300", "Score": "0", "body": "Just to get your head thinking about this, suppose we were at the root node (so `parent` == `None`), what would happen if one of the children were `None`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:58:03.423", "Id": "14301", "Score": "0", "body": "Hi @Jeff, All nodes have a `left` and `right` attribute, so leaf nodes would both be set to `None` in which case `root.left == None and root.right == None` and would return `0` up the recursion tree, this would be a base case wouldn't it? So zero would be added to the cumulative total." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T18:02:18.840", "Id": "14302", "Score": "0", "body": "I guess you need a specific example to see what I'm hinting at. Consider the tree where you have the root and it has a left child which is a leaf and no right child. So something like this: `Tree(left = Tree(left = None, right = None), right = None)`. Step through this with your code (or run it) and see what happens." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T23:30:42.133", "Id": "14312", "Score": "1", "body": "The more classic way of implementing this recursively is not to care if you are the root. `If you are NULL then it is 0. Otherwise it is 1 + Count(left) + Count(right)`. You can the wrap this with a function that prints information and calls Count(root)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T10:34:31.007", "Id": "14317", "Score": "0", "body": "@Jeff, Is it that I haven't accounted for the exception where `root == None`? @Loki I'm looking to count interior nodes only, so the node must have a parent and should have at most one `Null` child node (i.e not interested in counting all nodes)." } ]
[ { "body": "<p>So after our little discussion, I hope you see that you're missing some key cases here, when the <code>root</code> given is <code>None</code>.</p>\n\n<p>Some things that should be pointed out, when comparing to <code>None</code>, you should be checking if it <code>is</code> or <code>is not</code> <code>None</code>. Don't use (in)equality here, it is just not correct.</p>\n\n<p>Assuming this is a method on your tree node objects, I'd rewrite this to make use of <code>self</code>. That way we don't even need to worry about the case when <code>self</code> is <code>None</code>, that just shouldn't happen.</p>\n\n<pre><code>def count_interior_nodes(self):\n count = 0\n hasLeft, hasRight = self.left is not None, self.right is not None\n if hasLeft:\n count += self.left.count_interior_nodes()\n if hasRight:\n count += self.right.count_interior_nodes()\n if (hasLeft or hasRight) and self.parent is not None:\n count += 1\n return count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:29:47.347", "Id": "14483", "Score": "0", "body": "Hi @Jeff, thanks for the great advice. So when the `root is None` the `count` is returned? Good to make use of `self` as it is indeed a method of the Tree Node object. I didn't know and the rule when comparing `None` either, so I've gone through and corrected all my code on this note! I've also some other methods, such as `get_height()` I've also got them to make use of `self`. Great advice. Cheers Alex" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T23:51:22.203", "Id": "14492", "Score": "0", "body": "In your code, the big issue is that when the `root` given is `None`, you'll get an attribute error on the `None` object (which is equivalent to a \"NullReferenceException\" in other languages). In that case, the `count` wouldn't be returned. In fact, nothing is returned since an exception was raised and unhandled. That should not be an issue when running the code I've provided. We can assume that `self` will always be set to an instance of your class so we avoid that case. We're also checking beforehand if the children are `None` so no chance of the attribute error." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T17:48:27.873", "Id": "9148", "ParentId": "9115", "Score": "1" } } ]
{ "AcceptedAnswerId": "9148", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:23:37.727", "Id": "9115", "Score": "1", "Tags": [ "python" ], "Title": "Method to count interior nodes of a binary tree" }
9115
<p>This is the code I came up with.It seems correct. </p> <p>I am interested in:<br> 1) Improvements on code<br> 2) How can it be better than this? i.e. this is <code>O(N^2)</code> Could I have done better in complexity? What should I have read to do it? </p> <p>Thanks</p> <pre><code> public int lengthOfLongestSubstringNoRepetitions(String s) { if(s == null || s.trim().equals("")) return 0; Map&lt;Character,Boolean&gt; seen = new HashMap&lt;Character,Boolean&gt;(); int max = Integer.MIN_VALUE; for(int i = 0; i &lt; s.length(); i++){ for(int j = i; j &lt; s.length(); j++){ char c = s.charAt(j); if(seen.containsKey(new Character(c))){ //duplicate in substring int tmp = j - i; if(max &lt; tmp) max = tmp; break; } else{ seen.put(new Character(c),true); if(j == s.length() -1){ //Reached the end of string.Add one to get the range if(max &lt; (j - i + 1)) max = (j - i + 1); } } } seen.clear(); } return (max == Integer.MIN_VALUE)?s.length():max; } </code></pre>
[]
[ { "body": "<p>I think, that after founding the first char that is present in the substring being checked, you should not stop checking it, but cut off the part up to the first appearance of the char, add to the second appearance and <strong>continue</strong> to check the string. So the algorithm remains be O(n^2), but will be faster anyway.</p>\n\n<p>The other (additional) possibility to fasten the algorithm is to make an integer array address[2^16] that will have address of every char in that current substring. So you don't have to seek into the substring, but can take the address at once from the array. So, the difficulty becomes O(n). </p>\n\n<p>Make empty list of possibly longest substrings. Make all <code>address[i]=-1;</code></p>\n\n<p>Keep substring as a pair of start/end indexes in the source string. Start from them both<code>=0</code>;</p>\n\n<p>with every <code>newChar</code> on position <code>iPosition</code> you check, if it is already in the substring. So, that simply check <code>currentArrdess=address[(long)newChar]</code>. </p>\n\n<p>If <code>currentArrdess=0</code>, you add the <code>newChar</code> to the current substring. Increase end index and put <code>address[(long)newChar]=endIndex;</code></p>\n\n<p>If <code>currentArrdess&gt;0</code>, remember the current sunstring into the list of possibly longest substring and after that use <code>currentArrdess+1</code> as a new start index. </p>\n\n<pre><code>String findLongestSubstr(String source){\n final int charsNum=2^16;\n int[] address=new int[charsNum];\n int startSubstr= 0;\n int endSubstr= -1;\n ArrayList&lt;String&gt; pretendents=new ArrayList&lt;String&gt;();\n for (int i=0; i&lt;charsNum; i++) address[charsNum]=-1;\n // find all pretendents\n while(endSubstr&lt;source.length()-1){\n endSubstr++;\n int currentCharInt=source.charAt(endSubstr);\n if(address[currentCharInt]&gt;=0) {\n // old char - \n int newStartSubstr=address[currentCharInt]+1;\n //remove addresses up to (inclusive) the first appearance of the current char \n for(int i=startSubstr; i&lt;=address[currentCharInt];i++) {\n address[(int)source.charAt(i)]=-1;\n }\n // remember the string already found, before cutting it\n pretendents.add(source.substring(startSubstr, endSubstr+1));\n // cut the currently being checked string from the start\n startSubstr=newStartSubstr;\n }\n address[currentCharInt]=endSubstr;\n }\n // find max length pretendent\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:22:47.463", "Id": "14388", "Score": "0", "body": "+1 by me thank you I will study this.Is this a standard approach?Where could I read about such techniques?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T21:10:12.157", "Id": "14415", "Score": "0", "body": "Yes, remembering something instead of counting it many times is a standard technology. I don't think, there is books on exactly this theme, but as for optimization and algorithms, the classic book is Knuth (here http://www-cs-staff.stanford.edu/~uno/taocp.html is the bibliography)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T22:52:07.557", "Id": "9126", "ParentId": "9120", "Score": "2" } }, { "body": "<p>It won't make a huge difference but you could use a Set instead of a Map, since all the values in your Map are <code>true</code>, and therefore not very useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T23:33:57.767", "Id": "9128", "ParentId": "9120", "Score": "1" } }, { "body": "<p>Here's an O(n) solution. It replaces the Map with a char-indexed vector of the index where each char was last seen.</p>\n\n<pre><code>public static int lengthOfLongestSubstringNoRepetitions(String s) {\n\n if (s == null)\n return 0;\n\n // Trimming input even for the non-empty case is more consistent.\n final String str = s.trim();\n\n if (str.equals(\"\"))\n return 0;\n\n int seen[] = new int[Character.MAX_VALUE+1];\n for (int i = 0; i &lt;= Character.MAX_VALUE; ++i)\n seen[i] = -1;\n\n int max = 1;\n int len = 0;\n\n for (int j = 0; j &lt; str.length(); ++j) {\n char ch = str.charAt(j);\n // If ch was recently seen,\n // counting must restart after the last place it was seen.\n // Otherwise, it adds 1 to the length.\n len = Math.min(j-seen[ch], len+1);\n if (len &gt; max)\n max = len;\n seen[ch] = j;\n }\n return max;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:23:27.870", "Id": "14389", "Score": "0", "body": "+1 by me thank you. I will study this.Is this a standard approach?Where could I read about such techniques?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T13:12:27.777", "Id": "14649", "Score": "0", "body": "1. You have forgotten all type casting. 2. The question was to find the longest substring, not its length. 3. You have forgotten to give a reference to this very algorithm description that appeared here 2 days before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T16:22:16.063", "Id": "14683", "Score": "0", "body": "@Gangnus 1. Where/why would a cast be needed? 2. The OP *title* was longest substring, the function of the OP *code* was only *its length*. 3. I should have ack'ed the prior answer's common feature, the vector of offsets indexed by char. But it would have been wrong to claim to be using \"the very algorithm\". So much of the other detail in that answer -- start indexes and lists of substrings and even casts -- didn't enter into my algorithm at all. The code added later to clarify that answer confirms the difference in the algorithms." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T17:11:47.693", "Id": "14690", "Score": "0", "body": "1. you can't simply use char as int, or we use different Java -- 2. Yes, the questioner has to choose, what he wants exactly. So, he has both variants. 3. Ah. After moving the start point, you restart, and so throw away the info already got... And you think, that such deterioration of the algorithm is enough to consider this variant as original? It is up to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T21:13:04.377", "Id": "14707", "Score": "0", "body": "@Gangnus 1. javac 1.6.0_23 likes this use of char as a small unsigned value. I highly recommend it for readability. -- 2. Agreed, but not much of a choice since both answers are identical and one is deteriorated -- or so I'm told. -- 3. I'm not claiming \"originality\", just significant difference from the alternative as described earlier and expanded later, an alternative that I am still trying to understand, to see if I can upvote it in good conscience." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T22:00:12.580", "Id": "14717", "Score": "0", "body": "Thank you for the info. I work on java 1.6, too. And I had got compiler errors when not casting char into int in []. Interesting... Maybe, some options - I am trying to catch maximum at compiling stage.... As for expanding later - even now I am not sure that providing the ready answer is up to the rules of the site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T00:36:08.933", "Id": "102950", "Score": "0", "body": "Quite clever and easy to follow." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T06:11:55.597", "Id": "9171", "ParentId": "9120", "Score": "5" } }, { "body": "<p>Expression <code>s.equals(\"\")</code> is a bad practice. It should be <code>\"\".equals(s)</code> if you are comparing const and string. Class String also has method <em>isEmpty()</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T07:43:33.923", "Id": "9175", "ParentId": "9120", "Score": "2" } } ]
{ "AcceptedAnswerId": "9171", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T21:35:55.613", "Id": "9120", "Score": "4", "Tags": [ "java", "algorithm", "strings" ], "Title": "Longest substring with no repetitions" }
9120
<p>I have implemented the structure below at least 5 times, and it is getting cumbersome. Is there a better approach?</p> <h3>Current code-segment implemented</h3> <pre><code>public XmlNodeList Templates { get { return this.GetElementsByTagName( &quot;Templates&quot; ); } set { foreach( UITemplateAssoc nd in value ) { this.AddTemplate( nd ); } } } public UITemplateAssoc GetTemplate (string name) { foreach( UITemplateAssoc nd in this.Templates ) { if( nd.Name == name ) { return nd; } } return null; } public void AddTemplate ( UITemplateAssoc val ) { for( int i = this.Templates.Count - 1 ; i &gt;= 0 ; i-- ) { if( this.Templates[i].Name == val.Name ) { this.ReplaceChild( val , this.Templates[i] ); return; } } this.AppendChild( val ); } </code></pre>
[]
[ { "body": "<p>There's a couple of nice alternatives for you.</p>\n\n<p><strong>Extensions</strong></p>\n\n<p>If you don't need to encapsulate the <code>XmlNodeList</code> instances, you could make your methods extensions for <code>XmlDocument</code> or whatever you've extended:</p>\n\n<pre><code>public static class TemplateExtensions\n{\n public static XmlNodeList GetTemplates(this XmlDocument document) \n {\n return document.GetElementsByTagName(\"Templates\");\n }\n\n public static UITemplateAssoc GetTemplate(this XmlNodeList list, string name)\n {\n foreach(var nd in list)\n {\n if (nd.Name == name) return nd;\n }\n }\n\n // ...\n}\n\n// ...\nvar templates = yourDocument.GetTemplates();\nvar template = templates.GetTemplate(\"abc\");\n</code></pre>\n\n<p>More on extensions methods here: \n<a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb383977.aspx</a></p>\n\n<p><strong>Inheritance</strong></p>\n\n<p>Put these methods in a base class and have the behavior that differs in inherited classes.</p>\n\n<p>[edit]Updated to show how the base class can be generic[/edit]</p>\n\n<pre><code>public abstract class TemplateListBase&lt;T&gt;\n where T : XmlNode\n{\n private XmlNodeList templates;\n\n public XmlNodeList Templates \n { \n get \n { \n return templates.GetElementsByTagName( \"Templates\" ); \n } \n } \n\n protected TemplateListBase(XmlNodeList initialList)\n {\n templates = initialList;\n }\n\n public void AddRange(XmlNodeList list) \n { \n foreach( T nd in list ) \n { \n AddTemplate( nd ); \n } \n }\n\n public T GetTemplate (string name) \n { \n foreach( T nd in templates ) \n { \n if( nd.Name == name ) return nd; \n }\n return null;\n } \n\n public void AddTemplate ( T val ) \n { \n for( int i = templates.Count - 1 ; i &gt;= 0 ; i-- ) \n { \n if( templates[i].Name == val.Name ) \n { \n templates.ReplaceChild( val , templates[i] ); \n return; \n } \n } \n templates.AppendChild( val ); \n } \n}\n\npublic class UITemplateAssocList : TemplateListBase&lt;UITemplateAssoc&gt;\n{\n public UITemplateAssocList(XmlNodeList listOfUITemplates)\n : base(listOfUITemplates)\n {\n }\n\n public void FancyLogicA(string data)\n {\n foreach(var node in Templates)\n {\n // differing logic\n }\n }\n}\n\npublic class ConcreteTemplateB : TemplateListBase&lt;SomeOtherKindOfNode&gt;\n{\n // ..\n\n public void FancyLogicB(XmlNodeList list)\n {\n for (var node in list)\n {\n if (LikeThisNode(node)) AddTemplate(node);\n }\n }\n}\n</code></pre>\n\n<p>Notice that I replaced your setter with an <code>AddRange</code> method.\nIt's ususally good practice not to replace an entire encapsulated collection using a setter. \nAlthough you can validate the entries in the setter, a property should not do much logic other than returning or setting privates.\nIf you have a look at the collections in the BCL, they all expose an <code>AddRange</code> method and a method <code>Clear</code> to empty the collection. The <code>AddRange</code> method also gives you the option of adding multiple sets in turn.</p>\n\n<p>If you need different logic when stuff is added etc, have a look at the template method pattern:\n<a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Template_method_pattern</a></p>\n\n<p>If you need multiple base classes with differing logic, you could combine the inheritance with the extension methods, or another base class. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:26:39.980", "Id": "14399", "Score": "0", "body": "I already have several extensions at the base library for similar actions but they are foreseeable. Problem with this is that i really want to create a XMLNodeList that overrides the return type from the generic XmlNode to the specified class. not having much success though ;(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:45:38.303", "Id": "14402", "Score": "0", "body": "Tried using generics?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T19:04:09.200", "Id": "14404", "Score": "0", "body": "yeah but couldnt get the pattern to overload the return values. Ran into a brick wall. Tried doing `XmlNodeList<T>: XmlNodeList` but XmlNodeList evidently is a final class and is not inheritable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:00:24.490", "Id": "14409", "Score": "0", "body": "Make a wrapper for XmlNodeList instead of inheriting it, or make the methods working with the elements generic. For instance `public static T GetElement<T>(this XmlNodeList list, string name)`. Post some more code if you want, I'm sure it's possible. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T23:47:45.070", "Id": "14419", "Score": "0", "body": "I see I forgot to include the wrapping in the example. I've updated the example with a private instance of the XmlNodeList and made the base class generic for the items, not the list. Notice the base class does not inherit XmlNodeList, it wraps it. Unless stated that you're supposed to in the documentation, a rule of thumb is never to inherit stuff from the BCL. Much better to wrap. As an added bonus, you often get less dependencies in code using your class." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T08:38:25.837", "Id": "9178", "ParentId": "9127", "Score": "2" } } ]
{ "AcceptedAnswerId": "9178", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T22:57:03.490", "Id": "9127", "Score": "2", "Tags": [ "c#", "xml" ], "Title": "Collection of XmlNode control" }
9127
<p>How could this constructor code be improved? I feel like I'm not doing something optimally here...</p> <pre><code>@interface JGProduct : NSObject { NSString *identifier; } +(JGProduct *)productWithIdentifier:(NSString *)identifier_; -(JGProduct *)initWithIdentifier:(NSString *)identifier_; @end @implementation JGProduct +(JGProduct *)productWithIdentifier:(NSString *)identifier_ { return [[[[self class] alloc] initWithIdentifier:identifier_] autorelease]; } -(JGProduct *)initWithIdentifier:(NSString *)identifier_ { self = [super init]; if (self) { _identifier = [identifier_ retain]; } return self; } @end </code></pre> <p><strong>id or JGProduct return type?</strong></p> <p>I see a lot of people writing</p> <pre><code>-(id)initWithIdentifier:(NSString *)identifier_ { </code></pre> <p>instead - why is this? </p> <p>Surely any subclass of JGProduct would be exchangeable for the superclass... Or should I be returning something that is <code>id</code> but conforms to a protocol (if present)?</p> <p><strong>JGProduct or [self class] in initialiser?</strong></p> <p>I also see this:</p> <pre><code>+(JGProduct *)productWithIdentifier:(NSString *)identifier_ { return [[[JGProduct alloc] initWithIdentifier:identifier_] autorelease]; } </code></pre> <p>or</p> <pre><code>+(JGProduct *)productWithIdentifier:(NSString *)identifier_ { return [[[self alloc] initWithIdentifier:identifier_] autorelease]; } </code></pre> <p>Why would someone write either of these? The top one surely would not make the right kind of object if ran by a subclass. And what's the difference between <code>self</code> and <code>[self class]</code> if you're in a class method?</p> <p>Thanks for any feedback!</p>
[]
[ { "body": "<p><strong>Why <code>-init...</code> should be declared to return <code>id</code></strong></p>\n\n<p>Imagine you have class A and its subclass B sharing the same designated initializer, <code>initWithString:</code>.</p>\n\n<pre><code>@interface A : NSObject\n-(A *) initWithString: (NSString *) string;\n@end\n\n@interface B : A\n-(B *) initWithString: (NSString *) string;\n@end\n</code></pre>\n\n<p>As you can see, the declarations have a conflicting return type, which unavoidably causes a compiler warning. You can trivially fix it by changing the methods to return <code>id</code>, which, given Objective-C dynamic typing, doesn't change anything about how these methods work. So it has become a well-established, but not as well-understood, tradition.</p>\n\n<p><strong>Why class initializers should use <code>self</code> rather than the class name</strong></p>\n\n<p>As you correctly noticed, using <code>JGProduct</code> instead of <code>self</code> will allocate an instance of <code>JGProduct</code> for any subclass, which is not what you want in 99% cases.</p>\n\n<p><strong>Why write <code>+[JGProduct productWithIdentifier:]</code>?</strong></p>\n\n<p>Most of the time, it's just a shortcut to <code>alloc</code>, <code>init</code> and <code>autorelease</code> to make calling code more readable. However, these initializers may be much more complicated and more efficient when implemented in <em>class clusters</em>. When you write a class cluster, you have one public superclass and several private subclasses. In such cases the superclass's <code>alloc</code> has to return a placeholder object which will allocate and instantiate an object of the right subclass in its <code>init...</code> implementation. The class initializer, on the other hand, can immediately return an already inited object of the right subclass.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T18:44:56.683", "Id": "9152", "ParentId": "9130", "Score": "4" } } ]
{ "AcceptedAnswerId": "9152", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T00:46:36.433", "Id": "9130", "Score": "3", "Tags": [ "objective-c", "constructor", "cocoa" ], "Title": "How could this constructor code be improved?" }
9130
<p>Some time ago I wrote myself a simple blog. The index page is generated with PHP5, using an SQLite3 database via the variable <code>id</code> handed to it via the URL.</p> <p>The SQLite database contains a table called <code>pages</code>. The <code>id</code> refers of course to the id intergers in this table. Other columns are <code>title</code>, <code>body</code>, <code>time</code> and <code>timezone</code>.</p> <p>The <code>title</code> and <code>body</code> are <code>text</code> as you'd expect, the <code>timezone</code> is usually <code>"Asia/Tokyo"</code>, and the time is seconds from the epoch (I just use <code>date +%s</code>, when I add an entry, nothing fancy).</p> <p>I use the following code to get these variables from a table, and fill in a generic page with them.</p> <pre><code>&lt;?php // Open the database. $db = new PDO("sqlite:pagesdatabase.db"); // Is id set? If not get id of last page and put it in $id. if (!isset($_GET["id"])) { foreach ($db-&gt;query("select max(id) from pages") as $lastid) { $id = $lastid[0]; } } // If id is set, get the value and put it in $id. else { $id = $_GET['id']; } // Using the id number, grab the title, body, time and timezone of post. foreach ($db-&gt;query("select * from pages where id = $id") as $page) { $title = $page['title']; $body = $page['body']; $time = $page['time']; date_default_timezone_set($page['timezone']); } ?&gt; </code></pre> <p>This code works, but seems rather clumsy to me. For example, <code>foreach</code> appears twice, but shouldn't be necessary. To be honest, it's been a while since I wrote this code, and for some reason I had trouble using <code>sqlite_open</code> and other more obvious functions. Can someone help me write the above in a more terse way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T00:29:45.730", "Id": "14345", "Score": "0", "body": "I don't know PHP, but I can tell you the first foreach is useless. A max query like that will return the same single value every call until an insert or an update changes the table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T00:30:49.223", "Id": "14346", "Score": "0", "body": "For the second, does foreach in PHP mean each row or each column?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T00:31:28.677", "Id": "14347", "Score": "0", "body": "And do yourself a favour, list the columns you're getting explictly instead of doing \"select *\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T02:52:46.543", "Id": "14352", "Score": "0", "body": "Be fair, I *do* state that the `foreach` should not be necessary. As for your last two comments, it doesn't matter since there's only one element." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T03:46:19.493", "Id": "14353", "Score": "0", "body": "Sorry, I missed that statement." } ]
[ { "body": "<p>You are right, the foreaches can be eliminated. The first foreach which grabs the highest id, can be eliminated by taking advantage of the fact that the query will only ever return a single cell and using the <a href=\"http://www.php.net/manual/en/pdostatement.fetchcolumn.php\" rel=\"nofollow\">PDOStatement::fetchColumn()</a> method. Since page ids are unique, the second foreach can be removed because the second query will only ever return a single row.</p>\n\n<p>An additional problem is that you are not sanitizing user input in your SQL. This is easy to fix with PDO by using a parameterized statement:</p>\n\n<pre><code>&lt;?php\n// Open the database.\n$db = new PDO(\"sqlite:pagesdatabase.db\");\n\n// Is id set? If not get id of last page and put it in $id.\nif (!isset($_GET[\"id\"])) {\n $id = $db-&gt;query(\"select max(id) from pages\")-&gt;fetchColumn();\n}\n// If id is set, get the value and put it in $id.\nelse {\n $id = $_GET['id'];\n}\n\n// You may consider doing an additional check here in case there are no pages, in which\n// case id will be null\nif ($id === null) {\n // ...\n exit;\n}\n\n// Using the id number, grab the title, body, time and timezone of post.\n$page = $db-&gt;prepare(\"select * from pages where id = :id\")\n -&gt;execute(array('id' =&gt; $id))\n -&gt;fetch();\n\n// A check for an invalid id should be made here\nif ($page === null) {\n // ...\n exit;\n}\n\n$title = $page['title'];\n$body = $page['body'];\n$time = $page['time'];\ndate_default_timezone_set($page['timezone']);\n?&gt;\n</code></pre>\n\n<p>I have only quickly prepared this answer from experience and have not actually run the code above. It should be enough to give you an idea but may have syntax errors. If it does, comment on the post and I will fix it. Also, if reducing this code to the fewest lines possible is your goal, setting <code>$id</code> can be accomplished with a ternary and the actual retrieval of the page along with the error checks can be encapsulated in a function or a class.</p>\n\n<pre><code>&lt;?php\n// Open the database.\n$db = new PDO(\"sqlite:pagesdatabase.db\");\n\n// Determine if a page id is provided, if not use the most recent page\n$id = isset($_GET['id'])\n ? $_GET['id']\n : $db-&gt;query(\"select max(id) from pages\")-&gt;fetchColumn();\n\ntry {\n $page = Page::fetch($id, $db);\n\n $title = $page-&gt;getTitle();\n $body = $page-&gt;getBody();\n $time = $page-&gt;getTime();\n date_default_timezone_set($page-&gt;getTimezone());\n\n} catch (Exception $e) {\n // This exception should be thrown by Page::fetch if no pages exist or an invalid\n // id is given\n // ...\n exit;\n}\n?&gt;\n</code></pre>\n\n<p>If this is preferred I will leave the class definition to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T04:51:30.620", "Id": "15385", "Score": "0", "body": "Thanks for your answer. I haven't ignored it! Is there a particular reason that you have used PDO over SQLite specific functions? i.e. is there an advantage of one over the other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T17:47:03.193", "Id": "15917", "Score": "0", "body": "I have simply followed what you posted in your original example. Personally I only ever use PDO since I prefer the OO interface and because it provides parameterized queries which makes escaping user input much easier/safer. Not sure about the performance difference between the two." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T18:01:09.307", "Id": "15918", "Score": "0", "body": "This is not a high volume site. At most a few hits a day. I'm not overly concerned with performance, but I like my code to be a mixture of clear and uncluttered." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T17:53:17.087", "Id": "9376", "ParentId": "9135", "Score": "3" } } ]
{ "AcceptedAnswerId": "9376", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T07:32:39.160", "Id": "9135", "Score": "4", "Tags": [ "sql", "php5", "sqlite" ], "Title": "Clumsy PHP5 code reading from an SQLite3 database" }
9135
<p>I'm creating a website that parses in currency rates of the three major cities listed below in the <code>$cities</code> array.</p> <pre><code>&lt;?php // Feed URL's // $theMoneyConverter = 'http://themoneyconverter.com/rss-feed/'; // Define arrays // $cities = array( 'London', 'New York', 'Paris' ); $currencyCode = array( 'GBP', 'USD', 'EUR' ); // Arguments parsed onto theMoneyConverter URL to set position of the &lt;item&gt; tags declared in the XML document $currencySource = array( $theMoneyConverter . $currencyCode[0] . '/rss.xml?x=15', $theMoneyConverter . $currencyCode[1] . '/rss.xml?x=16', $theMoneyConverter . $currencyCode[2] . '/rss.xml?x=56' ); ?&gt; </code></pre> <p>Above is my configuration script that a developer will use if they wish to drop a city or add a new one. Notice in my <code>$currencySource</code> array that I add arguments to the end of each URL. For example, at index 0 in the array I add <code>?x=15</code>. This argument corresponds to the <code>&lt;item&gt;</code> element from the original source feed from themoneyconvert.com. In the case of <code>?x=15</code>, this would be the 15th <code>&lt;item&gt;</code> element from the XML document. </p> <p>The XML document to confirm <a href="http://themoneyconverter.com/rss-feed/GBP/rss.xml" rel="nofollow">this</a>. The 15th element contains the following element just to clarify: </p> <pre><code>&lt;item&gt; &lt;title&gt;EUR/GBP&lt;/title&gt; </code></pre> <p>The following is stored in a separate script called <code>getCurrency.php</code>:</p> <pre><code>function get_currency_rate($currencySource) { try { $xml = new SimpleXmlElement(file_get_contents($currencySource)); } catch (Exception $e) { echo 'Caught exception: An error has occured. Unable to get file contents'; } $vars = parse_url($currencySource, PHP_URL_QUERY); parse_str($vars); switch ($x) { case 15: get_rate($xml, 15); //EUR 15 get_rate($xml, 56); //USD 56 break; case 16: get_rate($xml, 16); //GBP 16 get_rate($xml, 15); //EUR 15 break; case 56: default : get_rate($xml, 15); // EUR 15 get_rate($xml, 56); // USD 56 break; } } // Get and return currency rate function get_rate(SimpleXMLElement $xml, $x) { $currency['rate'] = $xml-&gt;channel-&gt;item[$x]-&gt;description; echo $currency['rate'], '&lt;br /&gt;'; } </code></pre> <p>I call the <code>get_currency_rate()</code> function from my user interface like such:</p> <pre><code>echo get_currency_rate($currencySource[$index]) </code></pre> <p>After getting the file contents I extract the argument that I added to the URL from the configuration file listed above and store it as a variable <code>$x</code>. The XML feed and variable <code>$x</code> are parsed into the <code>get_rate function()</code>. </p> <p>The whole process doesn't seem very maintainable and particular readable. Adding a new city into the equation would become a nightmare for another developer. Can anyone think of any other alternatives?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T04:05:40.537", "Id": "81873", "Score": "0", "body": "I just ran your url with ?x=15 and 16 - it does not grab the 15th element. it returns the entire XML." } ]
[ { "body": "<p>I see some inconsistencies in your getCurrency.php code. There are many variables that are never declared within the functions, so I don't think that's going to work as expected.</p>\n\n<p>I think the best approach would be to make a parser which looks for whatever currency code you need, regardless of the item order because that might change in the future. I mean, the most performance-expensive part of the job is to parse the whole XML into a SimpleXML structure which you're doing anyway, so looping through the items seaching for the right one wouldn't be much worse and your code will be more straight-forward and escalable.</p>\n\n<p>On the other hand, you might also want to have some cache of the parsed XML to avoid re-parsing the same file on each request. But that depends on the variability of the XML feed. Maybe you can check with The Money Converter how often the feed is updated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:26:42.100", "Id": "9192", "ParentId": "9138", "Score": "1" } }, { "body": "<p>At configuration script you really need two (three) indexed arrays? I prefer associative arrays, or Objects.</p>\n\n<p>At getCurrency.php You catch the exception, but the code doesn't exit, and You are using Exception to handle two types of error, the file_get_contents returned false or the returned XML was invalid. At the first case you create an Exception which is an expensive opertaion.</p>\n\n<p>parse_url + parse_str is not the cleanest way to read the parameter and confusing. Instead of using indexed arrays and get paramters You should create an Object, and You don't need to trick with the url.</p>\n\n<p>The switch is horrible, the only thing what I can say is throw it out.</p>\n\n<p>Missing error handler get_rate if there is no record.</p>\n\n<p>My suggestion is to learn Object Oriented Paradigm, make Your life better, and Your code maintainable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-04T06:22:45.040", "Id": "64705", "ParentId": "9138", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T10:13:19.597", "Id": "9138", "Score": "2", "Tags": [ "php", "parsing", "xml", "url", "finance" ], "Title": "Parse in currency rates of major cities" }
9138
<p>I'm working on a webpage with language detection and I have the following script so far (it's simple). I still haven't done the user detection, so it's not available to find the user language (yet), but this will be easily implemented. Though I'm not asking for that, I'm asking for other ways to improve this code. So far as I've tested it, it's bug-free, but I want it to be bulletproof. How can I improve or expand it?</p> <pre><code>//LANGUAGES //Language detection if ( !empty($_POST['lang']) ) { $Lang = $_POST['lang']; $_SESSION['lang']= $_POST['lang']; } else { if ( !empty ($_SESSION['lang'])) $Lang = $_SESSION['lang']; else $Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); } //After this, $Lang will have the webpage preference </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:18:48.847", "Id": "14320", "Score": "0", "body": "Beware of that `$_SERVER['HTTP_ACCEPT_LANGUAGE']` might not be set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:25:39.637", "Id": "14321", "Score": "0", "body": "@Marcus so what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:33:24.763", "Id": "14322", "Score": "0", "body": "@Col. Shrapnel If you solely rely on something that might not be set, or set to a value not desired by the user, it might not get the desired result in some cases?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:40:27.790", "Id": "14323", "Score": "0", "body": "@Marcus THIS code does not solely relies on this header but rather on users choice. What's the problem then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:49:47.717", "Id": "14324", "Score": "1", "body": "@Col Okey, my mistake there. It relies on the $_SERVER var if the user has not made any input, which might be the case the first time he/she enters the site. But THIS code does not prevent someone to tamper with the sent value. Anyway, since he has a script later on that validates the lang it's no problem." } ]
[ { "body": "<p>On principle the code is sound except for one issue: <strong>you do not check if the language is \"valid\"</strong>. This raises some questions:</p>\n\n<ul>\n<li>How will your localization code behave if I added a <code>lang</code> parameter with the value <code>\"foobar\"</code>?</li>\n<li>How will it behave if I try to do an SQL injection using the parameter value?</li>\n</ul>\n\n<p>In both cases, the sane outcome would be to default to your \"main\" language, which would probably be hardcoded in your application.</p>\n\n<p>Another issue you may want to consider is that <em>nobody knows that there is an Accept-Language header and how to use it</em>, so using that as a source of the user's preferred locale is <a href=\"http://www.w3.org/International/questions/qa-accept-lang-locales\">not recommended</a>:</p>\n\n<blockquote>\n <p>It is not a good idea to use the HTTP Accept-Language header alone to\n determine the locale of the user. If you use Accept-Language\n exclusively, you may handcuff the user into a set of choices not to\n his liking.</p>\n</blockquote>\n\n<p>In your shoes I would totally scrap using <code>$_SERVER['HTTP_ACCEPT_LANGUAGE']</code> (IMHO it's useless in practice). If you want to go the extra mile and auto-detect the user's locale, use an IP database (I have used MaxMind GeoIP in the past myself) or the upcoming <a href=\"http://dev.w3.org/geo/api/spec-source.html\">W3C geolocation spec</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:34:20.647", "Id": "14325", "Score": "0", "body": "I forgot to say that, if the language is not detected, later there's a little script that uses the \"en\" as default\n\nBut this has a lot to do with the displaying options, asigning a language string to each of that why I totally forgot to say it... sorry!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:41:09.510", "Id": "14326", "Score": "0", "body": "About the SQL injection, I still haven't learned about that, I'm still learning the basics, but I know it'll be important.\nAnd about the HTTP Accept-Language header, it's still too early for me to use php geolocation, but I'll definitely keep it in mind.\nThank you so much for the whole explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:44:47.087", "Id": "14327", "Score": "0", "body": "@FrankPresenciaFandos: It's almost certain that there is no SQL injection or other type of vulnerability with your code (it would need to be very unusual to be vulnerable). But since we don't see exactly how `$Lang` ends up being used, I had to mention it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-07T16:25:51.920", "Id": "131525", "Score": "1", "body": "This is extremely bad advice. You should never rely on IP to choose language. If you pick any country in this world you will find different languages spoken there. Not to mention that GeoIP is only reliable in certain parts of the world. `Accept-Language` is the best you can get to actually detecting which language user prefers." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:23:22.393", "Id": "9142", "ParentId": "9141", "Score": "6" } }, { "body": "<p>I would add an array with supported languages and check this with the post.</p>\n\n<p>If there is no match change to some default language:</p>\n\n<pre><code>$languages = new stdClass();\n$languages-&gt;default = 'en';\n$languages-&gt;list = array('en', 'de', 'fr', 'es');\n\nif (!empty($_POST['lang']) &amp;&amp; in_array($_POST['lang'], $languages-&gt;list)) {\n $Lang = $_POST['lang'];\n $_SESSION['lang']= $_POST['lang'];\n} else {\n if (!empty($_SESSION['lang'])) {\n $Lang = $_SESSION['lang'];\n else\n $Lang = get_browser_language($languages-&gt;list);\n }\n if (!in_array($Lang, $languages-&gt;list)) {\n $Lang = $languages-&gt;default;\n }\n $_SESSION['lang'] = $Lang;\n}\n\n// I always use the following function to get the browser language (don't know anymore where I found it on the web)\nfunction get_browser_language($available_languages,$http_accept_language='auto')\n{\n if ($http_accept_language == 'auto') $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];\n\n $pattern = '/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?(\\s*;\\s*q\\s*=\\s*(1\\.0{0,3}|0\\.\\d{0,3}))?\\s*(,|$)/i';\n\n preg_match_all($pattern, $http_accept_language, $hits, PREG_SET_ORDER);\n\n $bestlang = $available_languages[0];\n $bestqval = 0;\n\n foreach ($hits as $arr) {\n $langprefix = strtolower ($arr[1]);\n if (!empty($arr[3])) {\n $langrange = strtolower ($arr[3]);\n $language = $langprefix . \"-\" . $langrange;\n }\n else $language = $langprefix;\n $qvalue = 1.0;\n if (!empty($arr[5])) $qvalue = floatval($arr[5]);\n\n // find q-maximal language\n if (in_array($language,$available_languages) &amp;&amp; ($qvalue &gt; $bestqval)) {\n $bestlang = $language;\n $bestqval = $qvalue;\n }\n // if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)\n else if (in_array($langprefix,$available_languages) &amp;&amp; (($qvalue*0.9) &gt; $bestqval)) {\n $bestlang = $langprefix;\n $bestqval = $qvalue*0.9;\n }\n }\n return $bestlang;\n}\n</code></pre>\n\n<p>You could also add an extra check based on a translation table from ip to country by using for example the data of: <a href=\"http://www.ip2nation.com/\" rel=\"nofollow\">http://www.ip2nation.com/</a></p>\n\n<p>Or perhaps even use GEO location to get the info. Although this would not be my preferred way since users will / should get a warning stating that the site tries to use GEO location of the visitor. If I see that I never accept although it may just be me :)</p>\n\n<p>I would also have created a cookie with the user's preferred language, so that when the user visits the site again at a later time he/she doesn't have to select the language again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:36:01.320", "Id": "14328", "Score": "0", "body": "The same that I said in the last post (but I forgot to say it in the main question), it is checked later, and there's no problem, as if there's no string for the language detected, the string used is the default, \"en\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:44:32.587", "Id": "14329", "Score": "0", "body": "@Frank Presencia Fandos: Why would you check it later? You do set the `session` var right here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:58:36.700", "Id": "14330", "Score": "0", "body": "@session because (in the future) will be intended to be used at a user-maintained webpage, so each string will be independent, and if there's no string at French, it would be displayed at English (default), waiting for someone to correct it, while the rest of the page would be at French" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:24:04.640", "Id": "9143", "ParentId": "9141", "Score": "3" } } ]
{ "AcceptedAnswerId": "9143", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:10:29.107", "Id": "9141", "Score": "4", "Tags": [ "php", "http", "session", "i18n" ], "Title": "Language-detection PHP script" }
9141
<p>the question is simple, for a input [apple, banana, orange, apple, banana, apple], the program will count it as a map: {apple : 3, orange: 1, banana: 2}, then sort this map by it's values, get [(apple, 3), (banana, 2), (orange, 1)] below is my go version, I'm a go newbie, could you please review it and lecture me how to polish the code? I add a python version for reference</p> <pre><code>package main //input, a url.log file, like "apple\nbanana\norange\napple\nbanana\napple\n" //output, a output.txt file, should be "apple: 3\nbanana: 2\norange: 1\n" import ( "fmt" "bufio" "os" "sort" "strings" "io" ) func main() { m := make(map[string]int) // read file line by line filename := "url.log" f, err := os.Open(filename) if err != nil { fmt.Println(err) return } defer f.Close() r := bufio.NewReader(f) for line, err := r.ReadString('\n'); err == nil; { url := strings.TrimRight(line, "\n") m[url] += 1 // build the map line, err = r.ReadString('\n') } if err != nil { fmt.Println(err) return } //sort the map by it's value vs := NewValSorter(m) vs.Sort() // output f_out, _ := os.Create("output.go.txt") defer f_out.Close() var line string for i, k := range vs.Keys { line = fmt.Sprintf("%s: %d\n", k, vs.Vals[i]) io.WriteString(f_out, line) } } type ValSorter struct { Keys []string Vals []int } func NewValSorter(m map[string]int) *ValSorter { vs := &amp;ValSorter { Keys: make([]string, 0, len(m)), Vals: make([]int, 0, len(m)), } for k, v := range m { vs.Keys = append(vs.Keys, k) vs.Vals = append(vs.Vals, v) } return vs } func (vs *ValSorter) Sort() { sort.Sort(vs) } func (vs *ValSorter) Len() int { return len(vs.Vals) } func (vs *ValSorter) Less(i, j int) bool { return vs.Vals[i] &gt; vs.Vals[j] } func (vs *ValSorter) Swap(i, j int) { vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i] vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i] } </code></pre> <p>python version:</p> <pre><code>from collections import Counter def main(): count = Counter() with open("url.log", "rb") as f: for line in f: url = line.rstrip() count[url] += 1 with open("output.py.txt", "wb") as f: for key, value in count.most_common(): f.write("%s: %d\n" %(key, value)) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>In Go, I would write:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io\"\n \"os\"\n \"sort\"\n)\n\ntype Key string\ntype Count int\n\ntype Elem struct {\n Key\n Count\n}\n\ntype Elems []*Elem\n\nfunc (s Elems) Len() int {\n return len(s)\n}\n\nfunc (s Elems) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\ntype ByReverseCount struct{ Elems }\n\nfunc (s ByReverseCount) Less(i, j int) bool {\n return s.Elems[j].Count &lt; s.Elems[i].Count\n}\n\nfunc main() {\n m := make(map[Key]Count)\n fi, err := os.Open(\"keys.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fi.Close()\n r := bufio.NewReader(fi)\n for {\n line, err := r.ReadString('\\n')\n if err != nil {\n if err == io.EOF &amp;&amp; len(line) == 0 {\n break\n }\n fmt.Println(err)\n return\n }\n key := line[:len(line)-1]\n m[Key(key)] += 1\n }\n fi.Close()\n\n e := make(Elems, 0, len(m))\n for k, c := range m {\n e = append(e, &amp;Elem{k, c})\n }\n sort.Sort(ByReverseCount{e})\n\n fo, err := os.Create(\"counts.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fo.Close()\n for _, e := range e {\n line := fmt.Sprintf(\"%s: %d\\n\", e.Key, e.Count)\n fo.WriteString(line)\n }\n}\n</code></pre>\n\n<p>Input (<code>keys.txt</code>):</p>\n\n<pre><code>apple\nbanana\norange\napple\nbanana\napple\n</code></pre>\n\n<p>Output (<code>counts.txt</code>):</p>\n\n<pre><code>apple: 3\nbanana: 2\norange: 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:44:03.120", "Id": "12396", "ParentId": "9146", "Score": "4" } }, { "body": "<p>Here's another approach using ioutils, which has some shortcuts for reading/writing files (assuming they are short enough to fit into memory). If you're writing a quick util, this might be easier than dealing with bufio in many cases. I've kept the sorting simple and in one function.</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"io/ioutil\"\n \"sort\"\n \"strings\"\n)\n\nfunc main() {\n // Read the input file\n input := \"./input.txt\"\n input_text, err := ioutil.ReadFile(input)\n if err != nil {\n panic(err)\n }\n\n // Store line counts\n lines := strings.Split(string(input_text), \"\\n\")\n counts := map[string]int{}\n for _, l := range lines {\n counts[l] += 1\n }\n\n // Get keys sorted\n keys := []string{}\n for k, _ := range counts {\n keys = append(keys, k)\n }\n sort.Strings(keys)\n\n // Output sorted counts using ordered keys\n output_text := \"\"\n for _, k := range keys {\n output_text += fmt.Sprintf(\"%s : %d\\n\", k, counts[k])\n }\n\n // Write results to a file\n output := \"./output.txt\"\n err = ioutil.WriteFile(output, []byte(output_text), 0644)\n if err != nil {\n panic(err)\n }\n fmt.Print(\"File written\\n\", output_text)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:33:35.227", "Id": "24125", "ParentId": "9146", "Score": "3" } } ]
{ "AcceptedAnswerId": "12396", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T14:03:36.133", "Id": "9146", "Score": "3", "Tags": [ "python", "go" ], "Title": "code review for count then sort problems (go lang)" }
9146
<p>Here is my code to do it:</p> <pre><code>import Random (randomR, Random, StdGen) generateRandoms :: (Random a, Num a) =&gt; StdGen -&gt; a -&gt; a -&gt; [b] -&gt; [a] generateRandoms gen min max = map fst . tail . scanl f (0, gen) where f (x, g) _ = randomR (min, max) g </code></pre> <p>The problem I have with this is that I need to pass a list to it e.g., via:</p> <pre><code>generateRandoms initialgen min max [1..10] </code></pre> <p>The values of this list end up being ignored and are just there to drive the <code>scanl</code> function.</p> <p>I'm wondering if there is a better way to do this (e.g., is there something like <code>scanl</code> that doesn't need a list to make it generate values?</p>
[]
[ { "body": "<p>If you just need to generate a stream of random numbers, you can use standard \"randomRs\" function from System.Random:</p>\n\n<pre><code>randomRs :: (RandomGen g, Random a) =&gt; (a, a) -&gt; g -&gt; [a]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Prelude System.Random&gt; newStdGen &gt;&gt;= print . take 5 . randomRs (1,10)\n[2,10,10,3,5]\n</code></pre>\n\n<p>If you want to implement it by yourself, it can be done with <em>unfoldr</em> function instead of scanl. unfoldr allows to (surprise!) unfold a list from the seed value. Exactly what you need! Let's examine its type:</p>\n\n<pre><code>unfoldr :: (b -&gt; Maybe (a, b)) -&gt; b -&gt; [a]\n</code></pre>\n\n<p>First argument is unfolding function and the second argument is the seed value. Unfolding function takes current seed value and produces Nothing or Just (a, b). Nothing means we should stop generating the list and Just (a, b) produces a new value of type \"a\" which is added to the genererated list and a new value of seed. </p>\n\n<p>Since we want to produce a stream of random values, we never return Nothing from our unfolding function. Here is the code:</p>\n\n<pre><code>generateRandoms2 :: (RandomGen g, Random a) =&gt; a -&gt; a -&gt; g -&gt; [a]\ngenerateRandoms2 min max = unfoldr (Just . randomR (min, max))\n</code></pre>\n\n<p>randomR takes a range for generation and (implicitly here!) a generator and returns a random value and a new value of the generator. Informally:</p>\n\n<pre><code>randomR (1, 2) :: (RandomGen g) =&gt; g -&gt; (a, g)\n</code></pre>\n\n<p>That's exactly what a typical unfolding function needs to do! So we just wrap this in Just and we are done.</p>\n\n<p>Usage:</p>\n\n<pre><code>*Random Data.List&gt; newStdGen &gt;&gt;= print . take 10 . generateRandoms2 1 10\n[10,6,2,7,3,7,5,9,4,5]\n</code></pre>\n\n<p>In fact, we don't use the full power of unfoldr here (since we do not need to distinguish whether we should finish the generation or not), so we can even write a simpler recursive function:</p>\n\n<pre><code>generateRandoms3 :: (RandomGen g, Random a) =&gt; a -&gt; a -&gt; g -&gt; [a]\ngenerateRandoms3 min max g = x : generateRandoms3 min max g'\n where (x, g') = randomR (min, max) g\n</code></pre>\n\n<p>Here we just produce random number one by one in a lazy fashion.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T23:25:23.583", "Id": "14343", "Score": "0", "body": "Thanks for this very detailed answer. Learning about the built in functions and the different options on how to do it from scratch (if I wanted to) is exactly what I was after when I asked the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T18:58:08.747", "Id": "9153", "ParentId": "9149", "Score": "6" } } ]
{ "AcceptedAnswerId": "9153", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T18:04:56.923", "Id": "9149", "Score": "3", "Tags": [ "haskell" ], "Title": "(Ab)using scanl to generate a random number stream, is there a better way?" }
9149
<p>This was a code test I was asked to complete by employer, and since they rejected me, I wonder what should I have done differently.</p> <pre><code>var w = 7, h = 6; var currentPlayer = 1; var animationInProgress = 0; var winner = 0; var map = new Array(h); var mapHtml = ""; for (var i = 0; i &lt; w; i++) { map[i] = new Array(h); mapHtml = mapHtml + "&lt;div class='col' id='col"+i+"' onclick='makeTurn("+i+")'&gt;&lt;span class='ball next-ball player1'&gt;&lt;/span&gt;"; for (var j = 0; j &lt; h; j++) { map[i][j] = 0; mapHtml = mapHtml + "&lt;div&gt;&lt;/div&gt;"; } mapHtml = mapHtml + "&lt;/div&gt;"; } $("#map").html(mapHtml); function makeTurn(col) { if (animationInProgress == 0 &amp;&amp; winner == 0) { for (var i = h-1; i &gt;= 0; i--) { if (map[col][i] == 0) { map[col][i] = currentPlayer; animateTurn(col, i); checkForWin(col, i); currentPlayer = 3 - currentPlayer; break; } } } } function animateTurn(col, row) { animationInProgress = 1; $("#map #col"+col+" .next-ball").addClass("animation-in-progress"); $("#map #col"+col+" .next-ball").animate({ top: '+='+(52*(row+1)-1) }, { duration: Math.round((row+1)*500/h), complete: function() { $("#map #col"+col+" div:nth-child("+(row+2)+")").html("&lt;span class='ball player"+(3-currentPlayer)+"'&gt;&lt;/span&gt;"); $("#map #col"+col+" .next-ball").css("top", "0px"); $("#map .animation-in-progress").removeClass("animation-in-progress"); $("#map .next-ball").removeClass("player"+(3-currentPlayer)); $("#map .next-ball").addClass("player"+currentPlayer); animationInProgress = 0; } }); } function checkForWin(x, y) { var delta, dx, dy, n = 0; //horizontal win for (i = 0; i &lt; w; i++) { if (map[i][y] == currentPlayer) { n++; if (n == 4) win(currentPlayer); } else { n = 0; } } //vertical win n = 0; for (i = 0; i &lt; h; i++) { if (map[x][i] == currentPlayer) { n++; if (n == 4) win(currentPlayer); } else { n = 0; } } //diagonal / win n = 0; delta = Math.min(x, h-y-1); for (dx = x-delta, dy = y+delta; dx &lt; w &amp;&amp; dy &gt; 0; dx++, dy--) { if (map[dx][dy] == currentPlayer) { n++; if (n == 4) win(currentPlayer); } else { n = 0; } } //diagonal \ win n = 0; delta = Math.min(x, y); for (dx = x-delta, dy = y-delta; dx &lt; w &amp;&amp; dy &lt; h; dx++, dy++) { if (map[dx][dy] == currentPlayer) { n++; if (n == 4) win(currentPlayer); } else { n = 0; } } } function win(player) { alert('Win by player '+player+'. Refresh page to restart'); winner = 1; } </code></pre> <p>What are the problems with this code?</p> <ul> <li>Non-descriptive variable names?</li> <li>Too many constants in code?</li> <li>Not using comments?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T22:37:56.417", "Id": "14342", "Score": "2", "body": "What were the rules/requirements/limitations of the project?" } ]
[ { "body": "<p>I'll start with a list of observations:</p>\n\n<ol>\n<li><p>Hardly any comments. There are several places where it would be nice if you added some comments to explain how the main logic works for someone who has not seen the code before.</p></li>\n<li><p>A bunch of global variables and ones using very generic names - lots of opportunities for clashes. I'd suggest either using a function closure to isolate your variables or make them properties of one global object or eliminate the need for them.</p></li>\n<li><p>There is NO need for a selector like this: <code>\"#map #col2\"</code>. It should just be <code>\"#col2\"</code>.</p></li>\n<li><p>A bunch of places where you're evaluating the same selector more than once. For example, in the <code>animateTurn</code> function, you evaluate <code>$(\"#map .next-ball\")</code> multiple times when you could just chain. This:</p>\n\n<pre><code>$(\"#map .next-ball\").removeClass(\"player\"+(3-currentPlayer));\n$(\"#map .next-ball\").addClass(\"player\"+currentPlayer);\n</code></pre>\n\n<p>could be changed to this:</p>\n\n<pre><code>$(\"#map .next-ball\").removeClass(\"player\"+(3-currentPlayer))\n .addClass(\"player\"+currentPlayer);\n</code></pre>\n\n<p>Or, in the whole function this:</p>\n\n<pre><code>function animateTurn(col, row) { \n animationInProgress = 1; \n $(\"#map #col\"+col+\" .next-ball\").addClass(\"animation-in-progress\");\n\n $(\"#map #col\"+col+\" .next-ball\").animate({\n top: '+='+(52*(row+1)-1)\n }, {\n duration: Math.round((row+1)*500/h),\n complete: function() {\n $(\"#map #col\"+col+\" div:nth-child(\"+(row+2)+\")\").html(\"&lt;span class='ball player\"+(3-currentPlayer)+\"'&gt;&lt;/span&gt;\"); \n $(\"#map #col\"+col+\" .next-ball\").css(\"top\", \"0px\"); \n $(\"#map .animation-in-progress\").removeClass(\"animation-in-progress\");\n $(\"#map .next-ball\").removeClass(\"player\"+(3-currentPlayer));\n $(\"#map .next-ball\").addClass(\"player\"+currentPlayer);\n animationInProgress = 0;\n }\n }); \n}\n</code></pre>\n\n<p>could be changed to this to use chaining and avoid re-evaluating the same selector multiple times:</p>\n\n<pre><code>function animateTurn(col, row) { \n animationInProgress = 1; \n $(\"#map #col\"+col+\" .next-ball\").addClass(\"animation-in-progress\") \n .animate({top: '+='+(52*(row+1)-1)}, {\n duration: Math.round((row+1)*500/h),\n complete: function() {\n $(\"#col\"+col+\" div:nth-child(\"+(row+2)+\")\").html(\"&lt;span class='ball player\"+(3-currentPlayer)+\"'&gt;&lt;/span&gt;\"); \n $(\"#col\"+col+\" .next-ball\").css(\"top\", \"0px\"); \n $(\"#map .animation-in-progress\").removeClass(\"animation-in-progress\");\n $(\"#map .next-ball\").removeClass(\"player\"+(3-currentPlayer))\n .addClass(\"player\"+currentPlayer);\n animationInProgress = 0;\n }\n }); \n}\n</code></pre></li>\n<li><p>I generally find it cleaner to use eventListeners rather than onclick handlers because you don't have to worry about multiple listeners stomping on each other.</p></li>\n<li><p>You have a bunch of constants in the code that aren't very self documenting. There's a <code>500</code> and a <code>52</code> which I have no idea where they came from or when they would have to be changed if the game was modified.</p></li>\n<li><p>Is there a reason that the HTML for the game is generated via javascript rather than specified separately? Usually, it's advantageous for the presentation of the app to be separate from the code for the app and for the code to adapt to whatever the presentation is. This allows separate people to work on the visual aspects of the app vs. the logic of the app and allows you to change one without affecting the other.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T01:55:47.590", "Id": "9160", "ParentId": "9156", "Score": "10" } }, { "body": "<p>In addition to jfriend00's suggestions:</p>\n\n<ul>\n<li>You should look into the separation of model and view (<a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\">MVC</a>), which would give the code much more structure and make it easier to read IMHO.</li>\n<li>I would have used a <code>&lt;table&gt;</code> for the grid.</li>\n<li>Extending on jfriend00's point 5: A single click event handler for the whole grid instead of one for each column would make sense.</li>\n<li>Finally a bit more polish for the GUI would have gone a long way, especially in one aspect: The winner shouldn't be announced until the animation has completed.</li>\n</ul>\n\n<p>EDIT:</p>\n\n<p>One more point: Depending on the requirements of the job, it may make sense to write this without using jQuery (or any another framework) since this simple example hardly has any stumbling stones that require it. That way you can demonstrate that the actually understand JavaScript and the DOM, plus you could use some current technologies such as CSS 3 animations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T12:25:51.890", "Id": "9183", "ParentId": "9156", "Score": "5" } }, { "body": "<p>I concur with jfriend00 and RoToRa, and would add the following.</p>\n\n<p>A style point: single var declarations are popular in JavaScript. I don't think there is anything wrong with multiple var statements, and there are even arguments for a return to this style (easier to refactor). My concern would be some people see multiple var statements as \"noobish\", and your potential employer may be \"some people\".</p>\n\n<pre><code>var w = 7,\n h = 6,\n currentPlayer = 1,\n ...\n mapHtml = \"\";\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1800594/in-javascript-why-is-preferred-over-new-array\">Prefer the array literal to new Array()</a></p>\n\n<pre><code>var map = [];\n</code></pre>\n\n<p>I agree with previous answers on putting the html for the game in the html file directly, then using JavaScript to size the game from that. So I would remove the html construction code, and set w, h (renamed) like this:</p>\n\n<pre><code>var cols = $('.cols').length,\n rows = $('.rows').length;\n</code></pre>\n\n<p>where the html was either a table or something like:</p>\n\n<pre><code>&lt;div class=\"row\"&gt;\n &lt;div class=\"col\"&gt;&lt;/div&gt;\n ... \n &lt;div class=\"col\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n...\n</code></pre>\n\n<p>Function <code>checkForWin(x, y)</code> looks ripe for breaking up into four functions. I suspect that some of the common code in the for loops can be factored out into one function as well.</p>\n\n<p>I would make <code>checkForWin</code> look something like this:</p>\n\n<pre><code>function checkForWin(x, y) {\n if (isHorizontalWin(x, y) ||\n isVerticalWin(x, y) ||\n isDiagonalToTopRightWin(x, y) ||\n isDiagonalToBottomRightWin(x, y)) {\n win(currentPlayer);\n }\n}\n</code></pre>\n\n<p>These function names take your comments from the <code>win</code> function and embed them in the code.</p>\n\n<p>Polluting the window namespace is a common but easily avoidable bad practice. There are quite a few ways of avoiding this, see <a href=\"http://addyosmani.com/blog/essential-js-namespacing/\" rel=\"nofollow noreferrer\">this JS Namespacing article</a> for an overview.</p>\n\n<p>I would suggest an Immediately-invoked Function Expression, which is a fancy name for a self-executing anonymous function (although they do not have to be anonymous).</p>\n\n<p>Wrap your code in this:</p>\n\n<pre><code>(function(){ /* your existing code goes here */})();\n</code></pre>\n\n<p>and you are no longer polluting the window namespace.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T21:46:04.673", "Id": "21315", "ParentId": "9156", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T22:10:31.513", "Id": "9156", "Score": "11", "Tags": [ "javascript", "jquery", "game", "interview-questions" ], "Title": "Animated JavaScript/jQuery game" }
9156
<p>I basically want to convert all categorical column in an R dataframe to several binary columns:</p> <p>For example, a categorical column like</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Company ------- IBM Microsoft Google </code></pre> </blockquote> <p>will be converted to 3 columns:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Company_is_IBM Company_is_Microsoft Company_is_Google 1 0 0 0 1 0 0 0 1 </code></pre> </blockquote> <p>However, my code runs very slowly on my testing data, which should generate a 900 column*367 row data frame.</p> <p>I'm attaching the code in to test with my dataset, simply by extracting the source code package, set working directory (setwd) to the source code files directory like shown in the picture (in archive), and run:</p> <pre class="lang-r prettyprint-override"><code>gpudataf = read.table("gpudataf.txt") gpudataf_bin = ConvertCategoricalDataFrameToBinaryKeepingOriginals(gpudataf) </code></pre> <p>and you will see how slow it is.</p> <p><a href="http://dl.dropbox.com/u/7361939/Cat2Bin.zip" rel="nofollow">Source code archive</a></p> <pre class="lang-r prettyprint-override"><code>source("IsCategorical.R") # Function CategoricalToBinary: Take a data.frame, determine which columns are categorical, # if categorical, convert the categorical column to several binary columns with values 0 and 1 #input: a Categorical Column, name of that column. Output: a data frame of multiple binary columns. ConvertCategoricalColumnToBinaryColumns &lt;- function(catecol,prefix = "") { set_values = unique(catecol) returnvalue = data.frame("ru9uGEQu" = catecol) #temporary frame no one will hit returnvalue[["ru9uGEQu"]] &lt;- NULL #I just did it for the number_rows compatible! for(val in set_values){ newcolName = paste(prefix, val, sep = "_is_") returnvalue[[newcolName]] &lt;- Map(function(x){return (if(x==val) 1 else 0)}, catecol) } return(returnvalue) } #input: a dataframe_with_categorical columns, and extra categorical column names, # if that column is categorical # but all of numerical denotations #output: the categorical columns are replaces by binary columns. ConvertCategoricalDataFrameToBinary &lt;- function(dataframe_with_cat_column, categoricalColumns=list()) { colNames= colnames(dataframe_with_cat_column) returnvalue = data.frame("ru9uGEQu" = dataframe_with_cat_column[[colNames[1]]]) returnvalue[["ru9uGEQu"]] &lt;- NULL for(columnName in colnames(dataframe_with_cat_column)){ # print(columnName) if(IsCategorical(dataframe_with_cat_column[[columnName]]) || (columnName %in% categoricalColumns)){ binary_dataframe = ConvertCategoricalColumnToBinaryColumns(dataframe_with_cat_column[[columnName]],prefix = columnName) # attach/insert it to the returnvalue for(binColName in colnames(binary_dataframe)){ returnvalue[[binColName]] = binary_dataframe[[binColName]] } } else{ # that column is numerical, don't change it. returnvalue[[columnName]] = dataframe_with_cat_column[[columnName]] } } return(returnvalue) } # if you want to keep the original values in the returned dataframe. ConvertCategoricalDataFrameToBinaryKeepingOriginals &lt;- function(dataframe_with_cat_column, categoricalColumns=list()) { without = ConvertCategoricalDataFrameToBinary(dataframe_with_cat_column, categoricalColumns) returnvalue = dataframe_with_cat_column existing_colNames = colnames(returnvalue) for(coln in colnames(without)){ if(!(coln %in% existing_colNames)){ returnvalue[[coln]] = without[[coln]] } } return(returnvalue) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T01:05:47.023", "Id": "14356", "Score": "5", "body": "I suspect you under-estimate peoples' willingness to download anonymous executable code from person's they are unfamiliar with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T01:06:26.507", "Id": "14357", "Score": "1", "body": "General strategies for speeding up R performance: http://stackoverflow.com/a/8474941/636656" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T05:10:47.187", "Id": "14358", "Score": "0", "body": "Try to replace Map(function(x){return (if(x==val) 1 else 0)}, catecol) with (catecol==val)*1" } ]
[ { "body": "<p><code>model.matrix</code> already does most of what you want:</p>\n\n<pre><code>company &lt;- c(\"IBM\", \"Microsoft\", \"Google\");\nmodel.matrix( ~ company - 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T01:03:14.310", "Id": "9165", "ParentId": "9164", "Score": "15" } }, { "body": "<p>This is a general do-it-yourself answer to \"my code is slow, what can I do?\": Use the profiler.</p>\n\n<pre><code>Rprof(tmp &lt;- tempfile())\n\n#############################\n#### YOUR CODE GOES HERE ####\n#############################\n\nRprof()\nsummaryRprof(tmp)\nunlink(tmp)\n</code></pre>\n\n<p>Yes, there is a bit of a learning curve about interpreting the output, but you could try to find the bottleneck in your code and test alternatives of your own. If those don't work, ask again with a more specific \"My code is slow doing this, what would be a better way?\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T01:21:07.653", "Id": "9166", "ParentId": "9164", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T00:48:11.663", "Id": "9164", "Score": "8", "Tags": [ "performance", "r" ], "Title": "Converting dataframe columns to binary columns" }
9164
<p>Currently I'm displaying a news feed from an XML file and using a counter to limit the number of news articles that are displayed. But I'm unsure if this is the best way to do it.</p> <p>Here is my code.</p> <pre><code>&lt;?php function get_news($feed) { $xml = new SimpleXmlElement(uwe_get_file($feed)); $counter = 0; foreach ($xml-&gt;channel-&gt;item as $item) { echo '&lt;a href="' . $item-&gt;link . '" target="_blank"&gt;' . $item-&gt;title . '&lt;/a&gt;&lt;br /&gt;' . '&lt;i&gt;' . $item-&gt;description . '&lt;/i&gt;' . '&lt;strong&gt;' . $item-&gt;pubDate . '&lt;/strong&gt;' . '&lt;br /&gt;' . '&lt;br /&gt;'; ++$counter; if ($counter == 5) { break; } } } ?&gt; </code></pre> <p>Any suggestions on how I could improve this counter?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:58:30.207", "Id": "14359", "Score": "0", "body": "You could shorten your `++$counter;` and `if($counter == 5)` line to `if (++$counter == 5)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:59:16.243", "Id": "14360", "Score": "0", "body": "You could shorten it by one line like this `if(++$counter === 5) {`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T20:05:04.877", "Id": "14361", "Score": "0", "body": "Your loop is about as efficient as it will get, unless your XML file contains radically more than 5 elements, such as 2,000. Your reader is DOM-based and a SAX-style parser may save you from scanning the whole input. That is about the only optimization I can think of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T20:22:59.063", "Id": "14362", "Score": "0", "body": "@Graham The counter is working fine just thought that there may have been a better way of coding it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T04:47:59.680", "Id": "14363", "Score": "0", "body": "I'd use printf($fmt) instead of `echo this . that . the_other`. But unless there's more than one way to skin any cat, and whatever method is going to be most readable in 6 or 12 months is probably the one you should pick. Supporting your code is always more work than writing it." } ]
[ { "body": "<p>That's a perfectly good and valid way of doing it. Personally, I'd write <code>$counter++</code> rather than <code>++$counter</code>, but that's just my personal preference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:57:08.930", "Id": "9168", "ParentId": "9167", "Score": "2" } }, { "body": "<p>Assuming standard key values (0-based integers). You could change the loop to:</p>\n\n<pre><code>for($i=0;$i&lt;5;$i++)\n{\n $item = $xml-&gt;channel-&gt;item[$i];\n echo '&lt;a href=\"' . $item-&gt;link . '\" target=\"_blank\"&gt;' . $item-&gt;title . '&lt;/a&gt;&lt;br /&gt;' . '&lt;i&gt;' . $item-&gt;description . '&lt;/i&gt;' . '&lt;strong&gt;' . $item-&gt;pubDate . '&lt;/strong&gt;' . '&lt;br /&gt;' . '&lt;br /&gt;';\n}\n</code></pre>\n\n<p>But I can't see it performing any better, just less code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:58:29.843", "Id": "9169", "ParentId": "9167", "Score": "1" } }, { "body": "<p>If you use a <code>for</code> loop you could get rid of the <code>if($counter == 5)</code> check:</p>\n\n<pre><code>function get_news($feed) {\n\n $xml = new SimpleXmlElement(uwe_get_file($feed));\n $count = count($xml-&gt;channel-&gt;item);\n for ($x = 0; ($x &lt; $count &amp;&amp; $x &lt;= 5); $x++) {\n echo '&lt;a href=\"' . $xml-&gt;channel-&gt;item[$x]-&gt;link . '\" target=\"_blank\"&gt;' . $xml-&gt;channel-&gt;item[$x]-&gt;title . '&lt;/a&gt;&lt;br /&gt;' . '&lt;i&gt;' . l-&gt;channel-&gt;item[$x]-&gt;description . '&lt;/i&gt;' . '&lt;strong&gt;' . l-&gt;channel-&gt;item[$x]-&gt;pubDate . '&lt;/strong&gt;' . '&lt;br /&gt;' . '&lt;br /&gt;';\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:59:38.873", "Id": "9170", "ParentId": "9167", "Score": "0" } } ]
{ "AcceptedAnswerId": "9169", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T19:55:08.417", "Id": "9167", "Score": "0", "Tags": [ "php" ], "Title": "PHP Counter Improvement" }
9167
<p>I'm sure there's a better way to approach the following. I'm writing a plugin where users can enter settings in the following format:</p> <p>Setting: "object1setting -> object2setting"</p> <p>It's done this way to allow for multiple objects to be passed within the same JS call. I'm breaking the the strings apart at the "->" symbol and saving them, however there are many settings and I'm thinking there has to be a more efficient way of writing this:</p> <pre><code>// START PLUGIN, SETUP DEFAULT OPTIONS, EXTEND OPTIONS TO "O" ..... // I'VE JUST PULLED SOME RANDOM SETTINGS AS AN EXAMPLE. bg_x_speed_in_set = o.bg_x_speed_in.toString().split("-&gt;"), // X PROPERTY SPEED IN bg_x_speed_out_set = o.bg_x_speed_out.toString().split("-&gt;"), // X PROPERTY SPEED OUT bg_y_speed_out_set = o.bg_y_speed_out.toString().split("-&gt;"), // Y PROPERTY SPEED OUT ... // ETC </code></pre> <p>This continues on and gets lengthy. Everything works perfectly in all browsers. I'm just trying to clean up the code.</p>
[]
[ { "body": "<p>I think you can use object literals. The user of your plugin can pass in an array of object literals: </p>\n\n<pre><code>var settings = [\n {bg_x_speed_in: ..., bg_x_speed_out_set : ...}\n , {bg_x_speed_in: ..., bg_y_speed_out_set : ....} \n , {bg_x_speed_in: ..., bg_x_speed_out_set : ....} \n]; \n</code></pre>\n\n<p>In your code, loop through the array; each element contains the settings for one object. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T18:29:47.403", "Id": "14368", "Score": "0", "body": "Trying to keep the user settings as simple as possible, or I would definitely go this route" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T19:53:19.870", "Id": "14369", "Score": "0", "body": "This actually seems easier to me than delimited strings. Most reusable js libraries are using object literals to pass in settings." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T18:07:25.177", "Id": "9174", "ParentId": "9172", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T17:47:28.907", "Id": "9172", "Score": "1", "Tags": [ "javascript", "jquery", "strings" ], "Title": "Splitting multiple strings" }
9172
<p>I have 3 tables: <code>students</code> and <code>classes</code> and <code>years</code>. In a fourth table called <code>StudentsInClass</code>, I'm saving students classes in each year. Now I want to show a list of students with their <code>className</code> in Current Year.</p> <p>This is the query I use but I'm not feeling good with it:</p> <pre><code> @StartRow int, @EndRow int As SET NOCOUNT ON; begin declare @YearID int; set @YearID= (select top 1 ID from Years where IsCurrent =1 ); select * from( select top 10000 S.*,T2.Title as ClassName,Row_Number() over (order by S.ID) as ResultSetRowNumber from Students S left outer join ( select SC.StudentCode,T1.Title from (select * from StudentsInClass where YearID=@YearID) SC left outer join Classes T1 on SC.ClassID = T1.ID ) T2 on S.Code= T2.StudentCode order by S.Family asc ) as PagedResults where ResultSetRowNumber &gt; @StartRow and ResultSetRowNumber &lt;= @EndRow; end </code></pre>
[]
[ { "body": "<p>Not entirely sure I got your schema right, but something like this should be possible.\n(omitted a bit of ordering, and I assume you only have one current year)</p>\n\n<pre><code>select top 10000\n s.*,\n c.Title classname,\n row_number() over (order by s.id) rownumber,\nfrom\n students s\n inner join years\n on years.iscurrent = 1\n inner join studentsinclass sc\n on s.code = sc.studentcode and sc.yearid = years.id\n inner join class c \n on c.id = sc.classid\nwhere\n row_number() over (order by s.id) &gt;= @StartRow\n and\n row_number() over (order by s.id) &lt;= @EndRow\n</code></pre>\n\n<p>You could possibly swap <code>on years.iscurrent = 1</code> with <code>on years.id = year(getdate())</code>.</p>\n\n<p>If you can, you should generally try to avoid too many subqueries. At least attempt to indent them properly.</p>\n\n<p>You could also benefit from having a look at common table expressions. These can help you group up the subqueries in predefined results for your query. Makes it a lot easier to read.\n<a href=\"http://msdn.microsoft.com/en-us/library/ms190766.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms190766.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T15:07:14.880", "Id": "19133", "Score": "0", "body": "+1 Joins rule; Something that helped me as a beginner was looking at the table schemas printed out on paper, this gets almost mechanical - just have to get from table A to table B traversing by keys, doing joins along the way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:04:47.743", "Id": "9179", "ParentId": "9176", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T07:57:01.100", "Id": "9176", "Score": "2", "Tags": [ "sql", "sql-server" ], "Title": "List of students with their classname in current year" }
9176
<p>As an exercise in learning Haskell, I implemented a simple key value store, where you can put and get values (as <code>ByteString</code>s). (For reference this is inspired by this <a href="http://downloads.basho.com/papers/bitcask-intro.pdf" rel="nofollow">short note describing bitcask's design</a>). I'd appreciate feedback on any aspect (style, <em>'haskellyness'</em>, library usage etc.) of my implementation:</p> <pre><code>{-# LANGUAGE OverloadedStrings #-} module KV ( evalKV, putKV, getKV, liftIO ) where import Prelude hiding (mapM) import Data.Traversable (mapM) import Control.Monad (liftM, liftM2) import Control.Monad.State (StateT, evalStateT, get, put, liftIO) import qualified System.IO as IO import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as L import qualified Data.Binary as B import qualified Data.Binary.Get as G import qualified Data.Map as M type Header = (Integer, Integer) -- keysize valuesize type ValueInfo = (Integer, Integer) -- offset valuesize type Key = ByteString type Pair = (Key, ValueInfo) type Index = M.Map Key ValueInfo data KVState = KVState { kvHandle :: IO.Handle , kvIndex :: Index } deriving (Show) type KV a = StateT KVState IO a evalKV :: FilePath -&gt; KV a -&gt; IO a evalKV p s = IO.withBinaryFile p IO.ReadWriteMode $ \h -&gt; do i &lt;- readIndex h evalStateT s $ KVState h i putKV :: ByteString -&gt; ByteString -&gt; KV () putKV k v = do (KVState h i) &lt;- get vi &lt;- liftIO $ writePair h k v let i' = M.insert k vi i put $ KVState h i' getKV :: ByteString -&gt; KV (Maybe ByteString) getKV k = do (KVState h i) &lt;- get liftIO $ lookupKV h i k readHeader :: ByteString -&gt; (Header, Integer) readHeader c = (h, fromIntegral o) where (h, _, o) = G.runGetState B.get c 0 readAt :: IO.Handle -&gt; Integer -&gt; Integer -&gt; IO ByteString readAt h o sz = do IO.hSeek h IO.AbsoluteSeek o L.hGet h $ fromIntegral sz readPair :: IO.Handle -&gt; Integer -&gt; IO (Maybe Pair) readPair h o = do IO.hSeek h IO.AbsoluteSeek o b &lt;- L.hGet h 10 -- TODO: qualify this arbitrary number if L.null b then return Nothing else do let ((ksz, vsz), l) = readHeader b k &lt;- readAt h (o + l) ksz return $ Just (k, (o + l + ksz, vsz)) writePair :: IO.Handle -&gt; ByteString -&gt; ByteString -&gt; IO ValueInfo writePair h k v = do IO.hSeek h IO.SeekFromEnd 0 let l = fromIntegral . L.length let vsz = l v let t = (l k, vsz) :: Header L.hPut h (B.encode t) L.hPut h k p &lt;- IO.hTell h L.hPut h v return (p, vsz) readIndex :: IO.Handle -&gt; IO Index readIndex h = liftM M.fromList $ ri 0 where ri o = do mp &lt;- readPair h o case mp of Just p@(k, (vo, vsz)) -&gt; do t &lt;- ri (vo + vsz) return $ p : t Nothing -&gt; return [] lookupKV :: IO.Handle -&gt; Index -&gt; ByteString -&gt; IO (Maybe ByteString) lookupKV h i k = mapM r mv where r = uncurry $ readAt h mv = M.lookup k i </code></pre> <p>And usage would look like:</p> <pre><code>{-# LANGUAGE OverloadedStrings #-} import KV import Data.ByteString.Lazy.Char8 main = evalKV "test" $ do u &lt;- getKV "asdf" liftIO $ print u putKV "asdf" "qwer" v &lt;- getKV "asdf" liftIO $ print v </code></pre> <p>Which would result in the following output:</p> <pre><code>Nothing Just (Chunk "qwer" Empty) </code></pre> <p>One concern I have, in particular, is that I've currently made no consideration for allowing concurrent access to the store, if people have opinions on the best approach for this I'd be really interested to hear them. I have this concern as, if I get time to work on this some more, my intention is to create a way to access the store over HTTP/TCP.</p>
[]
[ { "body": "<p>Why not:</p>\n\n<pre><code>type KeySize = Integer\ntype ValueSize = Integer\ntype Header = (KeySize, ValueSize)\n</code></pre>\n\n<p>Instead of commenting, like you did here:</p>\n\n<pre><code>type Header = (Integer, Integer)\n -- keysize valuesize\n</code></pre>\n\n<p>Same about <code>ValueInfo</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T11:33:13.553", "Id": "11920", "ParentId": "9177", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T08:25:03.417", "Id": "9177", "Score": "4", "Tags": [ "haskell", "functional-programming" ], "Title": "Simple Haskell key value file store" }
9177
<p>I'm studying C on K&amp;R and now I'm facing a recursion exercise that states:</p> <blockquote> <p>Write a recursive version of the function reverse(s), which reverses the string <code>s</code> in place.</p> </blockquote> <p>I've written the code below and I'm pretty sure that it works. I'll be glad to receive some critiques about it.</p> <p><strong>Reverse function:</strong></p> <pre><code>/* reverse: reverse string s in place */ void reverse(char s[]) { static int i, j = 0; int c; if (i == 0) { i = 0; j = strlen(s)-1; } c = s[i]; s[i] = s[j]; s[j] = c; i++; j--; while(i &lt; j) reverse(s); } </code></pre> <p><strong>Main:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAXLINE 100 void reverse(char s[]); int main(void) { char s[MAXLINE] = "foo bar baz"; reverse(s); printf("%s\n", s); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T12:01:34.777", "Id": "14375", "Score": "1", "body": "What do you mean, you can't find a similar solution? The solution [on that page from David Kachlon](http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_4:Exercise_13) is pretty much the same, except that he does not use static variables and no while-loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T13:20:35.177", "Id": "14381", "Score": "0", "body": "That's right. Thank you.\nShould I delete my question since it isn't very useful?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T14:03:10.117", "Id": "14382", "Score": "0", "body": "If you don't need it anymore now, then yes. If you still want a review, leave it here but edit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T14:44:10.377", "Id": "14386", "Score": "5", "body": "Probably not worth an answer but I don't think you really need to set `0` to `i` when `i == 0`." } ]
[ { "body": "<p>While this is recursive, it entirely misses the point. As the while loop will only ever execute once (because the function it calls only returns when <code>i &lt; j</code> it could just as well have been an if, and thus all you've got is tail-recursion.</p>\n\n<p>What you have is equivalent to the following, but impossible to call twice and maybe less efficient:</p>\n\n<pre><code>void reverse(char s[])\n{\n int i = 0, j = strlen(s)-1;\n int c;\n while (i &lt; j) {\n c = s[i];\n s[i] = s[j];\n s[j] = c;\n i++;\n j--;\n }\n}\n</code></pre>\n\n<p>That's obviously not recursive. The way you'd do it recursively is always swap the outer two characters of the string and then pass pointers to the beginning and end of a substring along.</p>\n\n<p>Apart from that, you're initialising <code>j</code> but not <code>i</code>, which makes little sense: both will be 0 initially anyway, so at least be consistent. You're also not using <code>MAXLINE</code>, so you might as well get rid of it (if C allows it). You're also not checking for a <code>NULL</code> being passed in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T08:57:39.157", "Id": "14616", "Score": "0", "body": "Can you explain in more detail why it **entirely** misses the point?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T15:51:58.173", "Id": "14677", "Score": "1", "body": "@cimere: Because it doesn't function recurvively. The call you have could be replaced with a goto and nothing would change. By the way, Jerry's suggestion is better than mine (mine is also tail-recursion)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-23T16:13:48.397", "Id": "17702", "Score": "0", "body": "I disagree, the function as written is properly recursive. Incidentally, it is not tail recursive because the recursive call is in a while statement. He shouldn't have used a `while` instead of an `if` and he should have used arguments instead of static variables (the `if (i == 0)` bug makes it a one shot function), but that doesn't make the function non recursive." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T20:09:51.510", "Id": "9200", "ParentId": "9181", "Score": "6" } }, { "body": "<p>Simple worked example of Anton's suggestion:</p>\n\n<pre><code>void reverse_rec(char *begin, char *end)\n{\n if (begin &lt; end) {\n char swp = *begin;\n *begin = *end;\n *end = swp;\n reverse_rec(begin+1, end-1);\n }\n}\n\nvoid reverse(char s[])\n{\n if (s)\n reverse_rec(s, s+strlen(s)-1);\n}\n</code></pre>\n\n<p>Note that you don't need a <code>while</code>, because <code>recurse_rec</code> stops recursing when <code>begin &gt;= end</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T10:40:08.733", "Id": "64691", "Score": "0", "body": "Helper function should be declared `static`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T09:23:52.273", "Id": "66887", "Score": "0", "body": "I think, you meant to subtract 1 from `end` rather than adding." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T22:27:41.163", "Id": "9204", "ParentId": "9181", "Score": "5" } }, { "body": "<p>This doesn't work if you call reverse () more than once in one run of program:</p>\n\n<pre><code>char s[MAXLINE] = \"foo bar baz\";\nreverse(s);\nprintf(\"%s\\n\", s); // get \"zab rab oof\"\nreverse(s);\nprintf(\"%s\\n\", s); // get \"zab rab oof\"\n</code></pre>\n\n<p>This happens because of your use of static variables in function.\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-30T15:26:42.290", "Id": "140027", "ParentId": "9181", "Score": "1" } } ]
{ "AcceptedAnswerId": "9200", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:57:30.597", "Id": "9181", "Score": "8", "Tags": [ "c", "strings", "recursion" ], "Title": "Recursive string reverse function" }
9181
<p>I've written this "little" <code>typeof</code> extension for my JS. What do you think about it?</p> <p>Its aim is to provide a single reliable <code>typeof</code> in JavaScript, consistent between native vars and objects. I've tested it both in FF 4+, IE 7+, Chrome 12, Safari 5. Also, if you have a different browser (also the version), can you test it?</p> <pre><code>typeOf = function(e) { if (typeof e === "undefined") { return "undefined"; } else if (typeof e === "object") { if (e === null) { // null è un oggetto return "null"; } else if (e instanceof String) { return "string"; } else if (e instanceof Number) { return "number"; } else if (e instanceof Boolean) { return "boolean"; } else if (e instanceof Date) { return "date"; } else if (e instanceof RegExp) { return "regexp"; } else if (e instanceof Error) { return "error"; } else if (e.isArray || e instanceof Array) { return "array"; } else if (e instanceof Window) { return "window"; } else if (e.nodeType) { switch (e.nodeType) { case 1: return "element"; case 2: return "attribute"; case 3: return "text"; case 9: return "document"; } } else if (e.call) { return "function"; } } else if (typeof e === "function") { if (e.call) { return "function"; } else if (e instanceof RegExp) { // V8 return "regexp"; } } return typeof e; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:19:17.767", "Id": "14387", "Score": "0", "body": "`e.isArray` is a bit silly, try `Array.isArray(e)`" } ]
[ { "body": "<p>I don't think much of it, to be honest. It's not as reliable as you might think, because once you start passing objects between contexts (e.g. different windows) it will fail miserably. Add to that the fact that </p>\n\n<pre><code>Object.prototype.toString.call(&lt;any value&gt;);\n</code></pre>\n\n<p>could do most of your work for you and your extension starts to look a little redundant and unnecessary.</p>\n\n<p>Here's a detailed article on this problem: <a href=\"http://whattheheadsaid.com/2010/10/cross-context-isarray-and-internet-explorer\" rel=\"nofollow\">Cross-context isArray and Internet Explorer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:34:40.400", "Id": "14390", "Score": "1", "body": "damn, you beat me to it by a minute... i'll just add to your answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:37:19.583", "Id": "14391", "Score": "1", "body": "@seand: lol, thanks for adding a link to my own blog post ;-) I should add that the article there raises a bug in Internet Explorer, but the specific problem mentioned in this answer applies to all browsers. An object created in another window is not an instance of the Object constructor that belongs to the main window." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:15:59.880", "Id": "14396", "Score": "0", "body": "Wow, I didn't realize! Nice post, it was helpful :) And you're right... you link to another post which focuses more on the general problem: http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:33:27.203", "Id": "9185", "ParentId": "9184", "Score": "7" } }, { "body": "<p>Technically there's nothing wrong with your code, but I think it's a bad approach.</p>\n\n<p>As Andy E mentions, the cool kids are doing it like this now days:</p>\n\n<pre><code>Object.prototype.toString.call(foo);\n</code></pre>\n\n<p>However, I've personally never found a real use for this either.</p>\n\n<p>Consider this:</p>\n\n<pre><code>if (typeOf(foo) == 'function') { ... }\n</code></pre>\n\n<p>versus this:</p>\n\n<pre><code>if (foo.call) { ... }\n</code></pre>\n\n<p>It's actually easier just to do the feature test from your typeOf function than to use the typeOf function itself. It's also clearer what's going on, we don't have to look at typeOf to make sure it's not lying to us, and doing what we expect.</p>\n\n<p>I usually opt for in-line feature testing.</p>\n\n<ul>\n<li>function --> foo.call </li>\n<li>string --> foo.split</li>\n<li>mutable array --> foo.push</li>\n<li>immutable array-like thing --> foo.length</li>\n</ul>\n\n<p>Usually I find myself doing this because I wrote a function which accepts, say, either an object or a string, and follows two different code paths depending on what kind of argument it gets. I can fairly safely assume it is one of the accepted types (otherwise it's user error), so my tests don't really need to be that complex. Food for thought, perhaps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:09:58.943", "Id": "14397", "Score": "0", "body": "I would avoid this approach (duck typing) because it's not 100% accurate. But this would work in specific cases where you know exactly what your inputs will be (as opposed to a generic reusable function)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:27:42.773", "Id": "14400", "Score": "0", "body": "@seand that's the thing, I've personally never run into a situation where I don't know at least roughly what I expect the inputs to be, so duck typing has always worked fine and I've never seen a use for a \"general-purpose\" function. I'm having trouble imagining a situation where this would be useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:53:26.653", "Id": "9194", "ParentId": "9184", "Score": "3" } }, { "body": "<p>Outside of the other answers about the general utility of this function, I figured I would add some additional thoughts on the code itself. I do agree with those other opinions though that this function just seems to obfuscate your code behavior. 'typeof' is so universally used and understood, that I don't know why you would want to introduce this potential point of complexity and confusion.</p>\n\n<p>The first thing goat jumps out to me is all the unnecessary nesting. You are doing a good job of returning from the function as quickly as possible, but then still leave a bunch of unnecessary else code paths. If you return in the if. The else should not be there. Remove them and de-nest your code. You will also find this would eliminate need to check for function or regex multiple times.</p>\n\n<p>I do not understand why you would return lowercase first characters in your return values. If your are testing \"Object\" for example why return \"object\"? This especially seems odd when your very last line of code for the fall through use case does not apply this same pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-25T04:20:57.577", "Id": "188304", "ParentId": "9184", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T16:01:04.093", "Id": "9184", "Score": "3", "Tags": [ "javascript" ], "Title": "Extension of JavaScript \"typeof\"" }
9184
<p>I recently discovered that there is no free read-write lock implementation for Ruby available on the Internet, so I built one myself. The intention is to keep it posted on GitHub indefinitely for the Ruby community at large to use.</p> <p>The code is at <a href="https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb" rel="nofollow">https://github.com/alexdowad/showcase/blob/master/ruby-threads/read_write_lock.rb</a>. For convenience, it is also repeated below. (There is another version which goes further to avoid reader starvation; it is currently at <a href="https://github.com/alexdowad/showcase/blob/fair-to-readers/ruby-threads/read_write_lock.rb" rel="nofollow">https://github.com/alexdowad/showcase/blob/fair-to-readers/ruby-threads/read_write_lock.rb</a>.)</p> <p>Alex Kliuchnikau very kindly reviewed the first version and found a serious bug. To fix that bug, I had to rethink the implementation and make some major changes. I am hoping someone can review the new version, first for correctness, and then for any ways to increase performance. Also, if you have a multi-core processor, please try running the file (it has a built-in test script). Problems which don't show up on my single-core machine may show up much more easily with multiple cores.</p> <pre><code># Ruby read-write lock implementation # Allows any number of concurrent readers, but only one concurrent writer # (And if the "write" lock is taken, any readers who come along will have to wait) # If readers are already active when a writer comes along, the writer will wait for # all the readers to finish before going ahead # But any additional readers who come when the writer is already waiting, will also # wait (so writers are not starved) # Written by Alex Dowad # Bug fixes contributed by Alex Kliuchnikau # Thanks to Doug Lea for java.util.concurrent.ReentrantReadWriteLock (used for inspiration) # Usage: # lock = ReadWriteLock.new # lock.with_read_lock { data.retrieve } # lock.with_write_lock { data.modify! } # Implementation notes: # A goal is to make the uncontended path for both readers/writers lock-free # Only if there is reader-writer or writer-writer contention, should locks be used # Internal state is represented by a single integer ("counter"), and updated # using atomic compare-and-swap operations # When the counter is 0, the lock is free # Each reader increments the counter by 1 when acquiring a read lock # (and decrements by 1 when releasing the read lock) # The counter is increased by (1 &lt;&lt; 15) for each writer waiting to acquire the # write lock, and by (1 &lt;&lt; 30) if the write lock is taken require 'atomic' require 'thread' class ReadWriteLock def initialize @counter = Atomic.new(0) # single integer which represents lock state @reader_q = ConditionVariable.new # queue for waiting readers @reader_mutex = Mutex.new # to protect reader queue @writer_q = ConditionVariable.new # queue for waiting writers @writer_mutex = Mutex.new # to protect writer queue end WAITING_WRITER = 1 &lt;&lt; 15 RUNNING_WRITER = 1 &lt;&lt; 30 MAX_READERS = WAITING_WRITER - 1 MAX_WRITERS = RUNNING_WRITER - MAX_READERS - 1 def with_read_lock acquire_read_lock yield release_read_lock end def with_write_lock acquire_write_lock yield release_write_lock end def acquire_read_lock while(true) c = @counter.value raise "Too many reader threads!" if (c &amp; MAX_READERS) == MAX_READERS # If a writer is running OR waiting, we need to wait if c &gt;= WAITING_WRITER # But it is possible that the writer could finish and decrement @counter right here... @reader_mutex.synchronize do # So check again inside the synchronized section @reader_q.wait(@reader_mutex) if @counter.value &gt;= WAITING_WRITER end else break if @counter.compare_and_swap(c,c+1) end end end def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) # If one or more writers were waiting, and we were the last reader, wake a writer up if c &gt;= WAITING_WRITER &amp;&amp; (c &amp; MAX_READERS) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end end def acquire_write_lock while(true) c = @counter.value raise "Too many writers!" if (c &amp; MAX_WRITERS) == MAX_WRITERS if c == 0 # no readers OR writers running # if we successfully swap the RUNNING_WRITER bit on, then we can go ahead break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) # Now we have successfully incremented, so no more readers will be able to increment # (they will wait instead) # However, readers OR writers could decrement right here, OR another writer could increment @writer_mutex.synchronize do # So we have to do another check inside the synchronized section # If a writer OR reader is running, then go to sleep c = @counter.value @writer_q.wait(@writer_mutex) if (c &gt;= RUNNING_WRITER) || ((c &amp; MAX_READERS) &gt; 0) end # We just came out of a wait # If we successfully turn the RUNNING_WRITER bit on with an atomic swap, # Then we are OK to stop waiting and go ahead # Otherwise go back and wait again c = @counter.value break if (c &lt; RUNNING_WRITER) &amp;&amp; @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER) end break end end end def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) if (c &amp; MAX_WRITERS) &gt; 0 # if any writers are waiting... @writer_mutex.synchronize { @writer_q.signal } else @reader_mutex.synchronize { @reader_q.broadcast } end break end end end end if __FILE__ == $0 # for performance comparison with ReadWriteLock class SimpleMutex def initialize; @mutex = Mutex.new; end def with_read_lock @mutex.synchronize { yield } end alias :with_write_lock :with_read_lock end # for seeing whether my correctness test is doing anything... # and for seeing how great the overhead of the test is # (apart from the cost of locking) class FreeAndEasy def with_read_lock yield # thread safety is for the birds... I prefer to live dangerously end alias :with_write_lock :with_read_lock end require 'benchmark' TOTAL_THREADS = 40 # set this number as high as practicable! def test(lock) puts "READ INTENSIVE (80% read, 20% write):" single_test(lock, (TOTAL_THREADS * 0.8).floor, (TOTAL_THREADS * 0.2).floor) puts "WRITE INTENSIVE (80% write, 20% read):" single_test(lock, (TOTAL_THREADS * 0.2).floor, (TOTAL_THREADS * 0.8).floor) puts "BALANCED (50% read, 50% write):" single_test(lock, (TOTAL_THREADS * 0.5).floor, (TOTAL_THREADS * 0.5).floor) end def single_test(lock, n_readers, n_writers, reader_iterations=50, writer_iterations=50, reader_sleep=0.001, writer_sleep=0.001) puts "Testing #{lock.class} with #{n_readers} readers and #{n_writers} writers. Readers iterate #{reader_iterations} times, sleeping #{reader_sleep}s each time, writers iterate #{writer_iterations} times, sleeping #{writer_sleep}s each time" mutex = Mutex.new bad = false data = 0 result = Benchmark.measure do readers = n_readers.times.collect do Thread.new do reader_iterations.times do lock.with_read_lock do mutex.synchronize { bad = true } if (data % 2) != 0 sleep(reader_sleep) mutex.synchronize { bad = true } if (data % 2) != 0 end end end end writers = n_writers.times.collect do Thread.new do writer_iterations.times do lock.with_write_lock do # invariant: other threads should NEVER see "data" as an odd number value = (data += 1) # if a reader runs right now, this invariant will be violated sleep(writer_sleep) # this looks like a strange way to increment twice; # it's designed so that if 2 writers run at the same time, at least # one increment will be lost, and we can detect that at the end data = value+1 end end end end readers.each { |t| t.join } writers.each { |t| t.join } puts "BAD!!! Readers+writers overlapped!" if mutex.synchronize { bad } puts "BAD!!! Writers overlapped!" if data != (n_writers * writer_iterations * 2) end puts result end test(ReadWriteLock.new) test(SimpleMutex.new) test(FreeAndEasy.new) end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:15:24.147", "Id": "14398", "Score": "0", "body": "And if someone were to test it on JRuby on an 864 core Azul Vega system, I'm sure Alex wouldn't complain, either :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:37:34.897", "Id": "14401", "Score": "0", "body": "Actually, anybody at all who can just run the test script and post the results is highly appreciated. I would feel irresponsible putting this up on the web for people to use, unless it has been tested on a variety of systems." } ]
[ { "body": "<p>Have you considered to join reader and writer queues into a single writer-waiting queue? This may make the code easier to synchronize and also solve the issue with readers starvation when constant writes are performed, something like this: </p>\n\n<ol>\n<li>if write lock is taken or queue is not empty, new operation (read or write) goes into queue</li>\n<li>if no write lock is taken and queue is empty, new read operation is performed. New write operation goes into queue and waits for read operations to end </li>\n<li>when write lock released, run next operation from the queue. If this is read operation, try run next operations until encounter write operation/queue is empty. If write operation is encounered, wait for reads (see item 2)</li>\n</ol>\n\n<hr>\n\n<p>I believe you should encapsulate operations on the counter into separate, say <code>ReadWriteCounter</code>, abstraction. It will hold <code>Atomic</code> <code>@counter</code> instance internally and will perform check and operations through methods like <code>new_writer</code>, <code>writer_running?</code> etc. This should improve code readability.</p>\n\n<hr>\n\n<p>I ran the code at Pentium(R) Dual-Core CPU E5400 @ 2.70GHz machine:</p>\n\n<p>MRI Ruby 1.9.2-p290:</p>\n\n<pre><code>READ INTENSIVE (80% read, 20% write):\nTesting ReadWriteLock with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.030000 0.030000 0.060000 ( 0.499945)\nWRITE INTENSIVE (80% write, 20% read):\nTesting ReadWriteLock with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.030000 0.010000 0.040000 ( 1.761913)\nBALANCED (50% read, 50% write):\nTesting ReadWriteLock with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.030000 0.010000 0.040000 ( 1.121450)\nREAD INTENSIVE (80% read, 20% write):\nTesting SimpleMutex with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.010000 0.020000 0.030000 ( 2.125943)\nWRITE INTENSIVE (80% write, 20% read):\nTesting SimpleMutex with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.010000 0.010000 0.020000 ( 2.114639)\nBALANCED (50% read, 50% write):\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.010000 0.010000 0.020000 ( 2.114838)\nREAD INTENSIVE (80% read, 20% write):\nTesting FreeAndEasy with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.000000 0.000000 0.000000 ( 0.058086)\nWRITE INTENSIVE (80% write, 20% read):\nTesting FreeAndEasy with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.010000 0.010000 0.020000 ( 0.060335)\nBALANCED (50% read, 50% write):\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.000000 0.000000 0.000000 ( 0.057053)\n</code></pre>\n\n<p>Jruby 1.6.5.1:</p>\n\n<pre><code>READ INTENSIVE (80% read, 20% write):\nTesting ReadWriteLock with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 0.875000 0.000000 0.875000 ( 0.875000)\nWRITE INTENSIVE (80% write, 20% read):\nTesting ReadWriteLock with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 1.880000 0.000000 1.880000 ( 1.880000)\nBALANCED (50% read, 50% write):\nTesting ReadWriteLock with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 1.201000 0.000000 1.201000 ( 1.201000)\nREAD INTENSIVE (80% read, 20% write):\nTesting SimpleMutex with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 2.196000 0.000000 2.196000 ( 2.196000)\nWRITE INTENSIVE (80% write, 20% read):\nTesting SimpleMutex with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 2.219000 0.000000 2.219000 ( 2.219000)\nBALANCED (50% read, 50% write):\nTesting SimpleMutex with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\n 2.229000 0.000000 2.229000 ( 2.229000)\nREAD INTENSIVE (80% read, 20% write):\nTesting FreeAndEasy with 32 readers and 8 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.074000 0.000000 0.074000 ( 0.074000)\nWRITE INTENSIVE (80% write, 20% read):\nTesting FreeAndEasy with 8 readers and 32 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.060000 0.000000 0.060000 ( 0.060000)\nBALANCED (50% read, 50% write):\nTesting FreeAndEasy with 20 readers and 20 writers. Readers iterate 50 times, sleeping 0.001s each time, writers iterate 50 times, sleeping 0.001s each time\nBAD!!! Readers+writers overlapped!\nBAD!!! Writers overlapped!\n 0.105000 0.000000 0.105000 ( 0.104000)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T18:44:19.753", "Id": "15105", "Score": "0", "body": "Alex, encapsulating operations on the counter is a great idea. I'm not sure if I should use a separate `ReadWriteCounter` class, or just some `private` methods on the `ReadWriteLock`. I think `private` methods may actually be enough. I really like the idea of using only 1 queue, primarily because it would reduce the memory footprint of each `ReadWriteLock` and make it more feasible to use very large numbers of them. (Have you seen the `ConcurrentHash` which I am working on? It's in my GitHub repo. I'm concerned about the memory used by `ReadWriteLock`s for that one.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T18:47:52.820", "Id": "15107", "Score": "0", "body": "I originally decided to use 2 queues because then I can release *all* readers with `@read_q.broadcast`. Since any number of readers can run concurrently, if you release one, it's best to release them all. But the scheme you described is workable and has definite advantages too. I think I should try another implementation using the scheme you described, and compare with the current implementation..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T20:28:41.170", "Id": "15113", "Score": "0", "body": "I tried a new implementation with only a single queue, and refactored for readability at the same time. It looks much nicer than before, but performance is terrible. I haven't done any testing to figure out why yet. It's the new 'alexs-ideas' branch on my GitHub repo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T10:07:39.550", "Id": "15667", "Score": "0", "body": "thanks for your input! I think I'm going to stick with 2 queues, but factoring out the operations on the counter is a great idea. BTW, I have a bounty which is expiring tomorrow, if you want it, please comment on this question: http://codereview.stackexchange.com/questions/9583/concurrent-stack-implementations-in-ruby-relative-performance-of-mutexes-cas" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T09:44:08.847", "Id": "9545", "ParentId": "9186", "Score": "2" } } ]
{ "AcceptedAnswerId": "9545", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:03:27.877", "Id": "9186", "Score": "2", "Tags": [ "ruby", "multithreading", "locking" ], "Title": "Read-write lock implementation for Ruby, new version" }
9186
<p>I've just implemented a background animate on some social media icons where the image goes from grey to color on <code>:hover</code>.</p> <p>I wanted to know if there's a better way to write the following but also implement a fade, so as the background animates, it's also fading in on hover.</p> <pre><code> &lt;script type="text/javascript"&gt; $(function(){ $('#facebook') .css( {backgroundPosition: "0 0"} ) .mouseover(function(){ $(this).stop().animate({backgroundPosition:"(-63px 0px)"}, {duration:150}) }) .mouseout(function(){ $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:150}) }) $('#twitter') .css( {backgroundPosition: "0 0"} ) .mouseover(function(){ $(this).stop().animate({backgroundPosition:"(-63px 0)"}, {duration:150}) }) .mouseout(function(){ $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:150}) }) }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>Instead of calling <code>mouseover</code> and <code>mouseout</code> separately, you can use <code>hover()</code> which takes care of this for you. Also, as both elements have the same code being executed you could employ DRY principles and group their selectors to use one block of code. Try this:</p>\n\n<pre><code>$(\"#facebook, #twitter\").css(\"backgroundPosition\", \"0 0\")\n .hover(function() {\n // mouseenter\n $(this).stop().animate({backgroundPosition:\"(-63px 0px)\"}, {duration:150})\n },\n function() {\n // mouseleave\n $(this).stop().animate({backgroundPosition:\"(0 0)\"}, {duration:150})\n });\n</code></pre>\n\n<p>With regards to the fading in of the image, you would need to have a separate hidden <code>img</code> element above the element which fades in as you cannot put animation on the CSS background property.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T11:01:31.763", "Id": "14392", "Score": "0", "body": "This is brilliant, thanks, much cleaner. Is there a way to as well a the animate, get a fade + the animate on hover? Or would i need a seprate block of code for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T11:20:35.513", "Id": "14394", "Score": "0", "body": "This was a massive help, but for what i need i'm using the above suggestion of two images instead of a sprite, absolute positioning. But as ever I'm very grateful for the help. Thanks again" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:55:00.103", "Id": "9188", "ParentId": "9187", "Score": "0" } }, { "body": "<blockquote>\n <p><em>I wanted to know if there's firstly a better way to write the following</em></p>\n</blockquote>\n\n<p>Well, not much to be improved but you can simplify things a little bit using <code>hover()</code></p>\n\n<pre><code>$('#facebook')\n.css('background-position', '0 0')\n.hover(function () {\n $(this).stop().animate({\n 'background-position' : '(-63px 0px)'\n }, 150);\n}, function () {\n $(this).stop().animate({\n 'background-position' : '(0 0)'\n }, 150);\n});\n</code></pre>\n\n<blockquote>\n <p><em>implement a fade so as the background animates it's also fading in on hover</em></p>\n</blockquote>\n\n<p>Your best bet is to implement it with two separate images instead of a sprite. You absolute position each image on top of each other, animate their <code>top</code> for the moving effect, and then <code>fadeIn()|fadeOut()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:55:36.027", "Id": "9189", "ParentId": "9187", "Score": "1" } }, { "body": "<p>You can do this CSS and JQuery:</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#facebook{\n background:url('/path/to/fb/icon/icon.png') no-repeat 0 0;\n}\n\n#twitter{\n background:url('/path/to/twitter/icon/icon.png') no-repeat 0 0;\n}\n</code></pre>\n\n<p>Then in your JQuery code you can do the following:</p>\n\n<pre><code>$(document).ready(function(){\n $('#facebook, #twitter').hover(function(){\n $(this).stop().animate({'backgroundPosition':'-63px 0'}, 150);\n }, function(){\n $(this).stop().animate({'backgroundPosition':'0 0'}, 150);\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:57:28.343", "Id": "9190", "ParentId": "9187", "Score": "0" } } ]
{ "AcceptedAnswerId": "9189", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T10:48:55.140", "Id": "9187", "Score": "1", "Tags": [ "javascript", "jquery", "css" ], "Title": "Adding fade to jquery background position animate" }
9187
<p>The Service:</p> <pre><code>&lt;?php namespace TestApp\Services\Ext; class ExtFilterParser { private $parsedFilters = array(); private $filters = ''; private $requestParam = 'filter'; public function __toString() { return $this-&gt;filters; } public function getParsedFilters() { return $this-&gt;parsedFilters; } public function getFilters() { return $this-&gt;filters; } public function setFilters($filters) { $this-&gt;filters = $filters; return $this; } public function __construct(\Symfony\Component\HttpFoundation\Request $request) { $this-&gt;filters = $this-&gt;pullFilterJsonFromRequest($request); } private function pullFilterJsonFromRequest($request) { $filterJson = ''; $filterFromGet = $request-&gt;query-&gt;get($this-&gt;requestParam); $filterFromPost = $request-&gt;request-&gt;get($this-&gt;requestParam); if(empty($filterFromGet) === FALSE) { $filterJson = $filterFromGet; } elseif(empty($filterFromPost) === FALSE) { $filterJson = $filterFromPost; } return $filterJson; } public function parse() { $decodedFilters = $this-&gt;decodeFilterJson($this-&gt;filters); foreach($decodedFilters as $filter) { switch($filter-&gt;type) { case 'numeric': $this-&gt;parsedFilters[] = $this-&gt;parseComparisonFilter($filter); break; case 'date': $this-&gt;parsedFilters[] = $this-&gt;parseDateFilter($filter); break; case 'list': $this-&gt;parsedFilters[] = $this-&gt;parseListFilter($filter); break; case 'string': $this-&gt;parsedFilters[] = $this-&gt;parseStringFilter($filter); break; default: throw new \UnexpectedValueException(__METHOD__ . " Unknown filter type '$filter-&gt;type'"); } } return $this; } public function parseIntoQueryBuilder(\Doctrine\ORM\QueryBuilder $queryBuilder) { $this-&gt;parse(); foreach($this-&gt;parsedFilters as $filter) { $queryBuilder-&gt;andWhere('p.' . $filter['expression'] . ' ' . $filter['value']); } return $queryBuilder; } private function decodeFilterJson($filterJson) { $decodedFilters = array(); if(empty($filterJson) === FALSE) { $decodedFilters = json_decode($filterJson); if($decodedFilters === NULL) { throw new \InvalidArgumentException(__METHOD__ . " Expects first parameter to be a valid JSON string"); } if(!is_array($decodedFilters)) { $decodedFilters = array($decodedFilters); } } return $decodedFilters; } private function translateComparisonOperator($comparisonOperator) { $operator = ''; switch($comparisonOperator) { case 'lt': $operator = '&lt;'; break; case 'gt': $operator = '&gt;'; break; case 'eq': $operator = '='; break; default: throw new \UnexpectedValueException(__METHOD__ . " Invalid comparison operator '$comparisonOperator'"); } return $operator; } private function parseComparisonFilter($filter) { $comparisonOperator = $this-&gt;translateComparisonOperator($filter-&gt;comparison); if(!is_numeric($filter-&gt;value)) { $filter-&gt;value = "'$filter-&gt;value'"; } return array( 'expression' =&gt; "$filter-&gt;field $comparisonOperator", 'value' =&gt; $filter-&gt;value ); } private function parseDateFilter($filter) { $value = $filter-&gt;value; if($value == '0000-00-00') { $value = ''; } $timestamp = strtotime($value); if($timestamp !== FALSE) { $value = date("Y-m-d", $timestamp); } $filter-&gt;value = $value; return $this-&gt;parseComparisonFilter($filter); } private function parseStringFilter($filter) { return array( 'expression' =&gt; "$filter-&gt;field LIKE", 'value' =&gt; "'%$filter-&gt;value%'" ); } private function parseListFilter($filter) { if(!is_array($filter-&gt;value)) { $filter-&gt;value = explode(',', $filter-&gt;value); } return array( 'expression' =&gt; "$filter-&gt;field IN", 'value' =&gt; "('" . implode("','", $filter-&gt;value) . "')" ); } } </code></pre> <p>The unit test for the Service:</p> <pre><code>&lt;?php namespace TestApp\Tests\Services\Ext; use TestApp\Services\Ext\ExtFilterParser; use Symfony\Component\HttpFoundation\Request; class ExtFilterParserTest extends \PHPUnit_Framework_TestCase { private $request; private $extFilterParser; public function dateDataProvider() { return array( array( '2011-06-30', 'June 30, 2011', '06/30/2011', '30/06/2011' ) ); } public function setUp() { $this-&gt;request = Request::createFromGlobals(); $this-&gt;extFilterParser = new ExtFilterParser($this-&gt;request); } /** * @param string $type The filter type to generate * @param string $field The field the filter applies to * @param mixed $value The value to filter by * @param string $comparison (Optional) Comparison Operator */ public function generateFilterJson($type, $field, $value, $comparison = '') { return json_encode(array('type' =&gt; $type, 'field' =&gt; $field, 'value' =&gt; $value, 'comparison' =&gt; $comparison)); } public function testForProperties() { $className = get_class($this-&gt;extFilterParser); $this-&gt;assertClassHasAttribute('parsedFilters', $className); $this-&gt;assertClassHasAttribute('filters', $className); $this-&gt;assertClassHasAttribute('requestParam', $className); } public function testPropertyDefaultValues() { $this-&gt;assertAttributeEmpty('parsedFilters', $this-&gt;extFilterParser, 'ExtFilterParser::parsedFilters should default to an empty array'); $this-&gt;assertAttributeEquals('filter', 'requestParam', $this-&gt;extFilterParser, 'ExtFilterParser::requestParam should default to \'filter\''); $this-&gt;assertAttributeEquals('', 'filters', $this-&gt;extFilterParser, 'ExtFilterParser::filters should default to an empty string'); } public function testPropertyDataTypes() { $this-&gt;assertAttributeInternalType('array', 'parsedFilters', $this-&gt;extFilterParser); $this-&gt;assertAttributeInternalType('string', 'filters', $this-&gt;extFilterParser); $this-&gt;assertAttributeInternalType('string', 'requestParam', $this-&gt;extFilterParser); } /** * @expectedException InvalidArgumentException * @expectedExceptionMessage ExtFilterParser::decodeFilterJson Expects first parameter to be a valid JSON string */ public function testParseBadJsonException() { $this-&gt;extFilterParser-&gt;setFilters('bad json')-&gt;parse(); } public function test__toString() { $filterJson = $this-&gt;generateFilterJson('string', 'firstName', 'Steve'); $this-&gt;extFilterParser-&gt;setFilters($filterJson); $objectAsString = "$this-&gt;extFilterParser"; $this-&gt;assertEquals($filterJson, $objectAsString); } /** * @expectedException UnexpectedValueException * @expectedExceptionMessage ExtFilterParser::translateComparisonOperator Invalid comparison operator 'bad' */ public function testParseUnknownComparisonOperatorException() { $this-&gt;extFilterParser-&gt;setFilters('{"type":"numeric", "field": "foo", "value":"bar", "comparison": "bad"}')-&gt;parse(); } /** * @expectedException UnexpectedValueException * @expectedExceptionMessage ExtFilterParser::parse Unknown filter type 'bad' */ public function testParseUnknownFilterTypeException() { $this-&gt;extFilterParser-&gt;setFilters('{"type":"bad", "field": "foo", "value":"1"}')-&gt;parse(); } public function testParseFromGetRequest() { $_GET['filter'] = $filter = $this-&gt;generateFilterJson('string', 'stringField', 'A'); $this-&gt;extFilterParser = new ExtFilterParser(Request::createFromGlobals()); $filter = $this-&gt;generateFilterJson('string', 'stringField', 'A'); $parsedFilter = $this-&gt;extFilterParser-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertEquals("stringField LIKE", $parsedFilter[0]['expression']); $this-&gt;assertEquals("'%A%'", $parsedFilter[0]['value']); $this-&gt;testParseStringFilter(); } public function testParseFromPostRequest() { $_POST['filter'] = $filter = $this-&gt;generateFilterJson('string', 'stringField', 'A'); $this-&gt;extFilterParser = new ExtFilterParser(Request::createFromGlobals()); $filter = $this-&gt;generateFilterJson('string', 'stringField', 'A'); $parsedFilter = $this-&gt;extFilterParser-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertEquals("stringField LIKE", $parsedFilter[0]['expression']); $this-&gt;assertEquals("'%A%'", $parsedFilter[0]['value']); $this-&gt;testParseStringFilter(); } /* * @expectedException UnexpectedValueException * @expectedExceptionMessage ExtFilterParser::setFilters Unknown filter type 'badValue' */ public function testParseUnexpectedFilterTypeException() { $this-&gt;extFilterParser-&gt;setFilters('{"type":"badValue", "field": "foo", "value":"1"}'); } public function testParseStringFilter() { $filter = $this-&gt;generateFilterJson('string', 'stringField', 'A'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertEquals("stringField LIKE", $parsedFilter[0]['expression']); $this-&gt;assertEquals("'%A%'", $parsedFilter[0]['value']); } /** * @dataProvider dateDataProvider * @param string $date The date to be parsed */ public function testParseDateFilter($date) { $filter = $this-&gt;generateFilterJson('date', 'dateField', $date, 'lt'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("dateField &lt;", $parsedFilter[0]['expression']); $this-&gt;assertEquals("'2011-06-30'", $parsedFilter[0]['value']); } public function testParseDateFilterEmptyDate() { $filter = $this-&gt;generateFilterJson('date', 'dateField', '0000-00-00', 'gt'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("dateField &gt;", $parsedFilter[0]['expression']); $this-&gt;assertEquals("''", $parsedFilter[0]['value']); } public function testParseNumericFilterLessThan() { $filter = $this-&gt;generateFilterJson('numeric', 'numericField', 1, 'lt'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("numericField &lt;", $parsedFilter[0]['expression']); $this-&gt;assertEquals("1", $parsedFilter[0]['value']); } public function testParseNumericFilterGreaterThan() { $filter = $this-&gt;generateFilterJson('numeric', 'numericField', 1, 'gt'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("numericField &gt;", $parsedFilter[0]['expression']); $this-&gt;assertEquals("1", $parsedFilter[0]['value']); } public function testParseNumericFilterEqualTo() { $filter = $this-&gt;generateFilterJson('numeric', 'numericField', 1, 'eq'); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("numericField =", $parsedFilter[0]['expression']); $this-&gt;assertEquals("1", $parsedFilter[0]['value']); } public function testParseListFilterAsArray() { $filter = $this-&gt;generateFilterJson('list', 'listField', array('a', 'b', 'c')); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("listField IN", $parsedFilter[0]['expression']); $this-&gt;assertEquals("('a','b','c')", $parsedFilter[0]['value']); } public function testParseListFilterAsCsv() { $filter = $this-&gt;generateFilterJson('list', 'listField', "a,b,c"); $parsedFilter = $this-&gt;extFilterParser-&gt;setFilters($filter)-&gt;parse()-&gt;getParsedFilters(); $this-&gt;assertCount(1, $parsedFilter); $this-&gt;assertEquals("listField IN", $parsedFilter[0]['expression']); $this-&gt;assertEquals("('a','b','c')", $parsedFilter[0]['value']); } public function testSetFiltersReturnsInstance() { $instance = $this-&gt;extFilterParser-&gt;setFilters($this-&gt;generateFilterJson('list', 'listField', "a,b,c"));- $this-&gt;assertInstanceOf(get_class($this-&gt;extFilterParser), $instance); } public function testParseReturnsInstance() { $instance = $this-&gt;extFilterParser-&gt;setFilters($this-&gt;generateFilterJson('list', 'listField', "a,b,c"))-&gt;parse(); $this-&gt;assertInstanceOf(get_class($this-&gt;extFilterParser), $instance); } } </code></pre> <p><strong>Facts</strong></p> <ul> <li>I know that the service works (I've used it).</li> <li>I know all unit tests pass.</li> </ul> <p><strong>Concerns</strong></p> <ul> <li>The unit test makes use of and is dependent on the Request Object.</li> <li>If I change the scope / configuration of my service via the YAML file that symfony uses (say to add another object to the constructor), these unit tests will all fail even though the code itself may not be "broken". </li> <li>I feel like I've too tightly coupled things and made the unit tests not accurately reflect what's going on in my application.</li> </ul>
[]
[ { "body": "<p>The concerns you have raised are valid. This test is currently relying on the Request object (and is testing that object where it shouldn't be).</p>\n\n<p>You have written the code well, injecting the dependency for the Request object into the constructor. This gives you the seam required for testing (<a href=\"http://misko.hevery.com/2009/10/07/design-for-testability-talk/\" rel=\"nofollow\">Misko Hevery talks about seams</a> and gives awesome advice on testing in many other places).</p>\n\n<p>In your test you can make your seam by using mocked objects. What you really want to test is that the mock (a friendly object that you control with your test code) receives the expected stimuli. This means that you should be testing that your Request object is used correctly by your service code. You also define what you want your mock to return to your service code so that you are able to ensure that your service code reacts to the stimuli received from your Request.</p>\n\n<p>PHPUnit makes it easy for you to <a href=\"http://www.phpunit.de/manual/3.6/en/test-doubles.html#test-doubles.mock-objects\" rel=\"nofollow\">create Mock objects</a>. The whole of Chapter 10 is a good read.</p>\n\n<p>The good news is that you only have tight coupling in your test code. Using the mock objects will remove this for you fairly easily.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T05:05:33.087", "Id": "10335", "ParentId": "9191", "Score": "2" } } ]
{ "AcceptedAnswerId": "10335", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:03:34.633", "Id": "9191", "Score": "3", "Tags": [ "php", "parsing", "unit-testing", "php5", "symfony2" ], "Title": "Unit-testing ExtFilterParser Symfony2 service" }
9191
<p>In my time off I thought I'd implement some idiomatic data structures, starting with a linked list. </p> <p>Here's my current version: </p> <pre><code>#include &lt;iostream&gt; using namespace std; struct node{ int data; node *next; }; void traverseList(node *head){ for(node *iterator = head ; iterator ; iterator = iterator-&gt;next) { cout &lt;&lt; iterator-&gt;data &lt;&lt; endl; } } int length(node *head){ int count = 0; for(node *iterator = head ; iterator ; iterator = iterator-&gt;next, count++) {} return count; } int main(){ //create the head of the list, assign it data node *head = new node; head-&gt;data = 0; //create a {1,2,3} list node *first = new node; node *second = new node; node *third = new node; //assign appropriate data first-&gt;data = 1; second-&gt;data = 2; third-&gt;data = 3; //assign pointees first-&gt;next = second; second-&gt;next = third; third-&gt;next = 0; //give the head the pointee head-&gt;next = first; traverseList(head); int listLength = length(head); printf("List Length: %d\n", listLength); return 0; } </code></pre> <p>I've already changed the while loops I originally used (e.g.):</p> <pre><code>void traverseList(node *head){ if(head != 0){ while(head-&gt;next !=0){ cout &lt;&lt; head-&gt;data &lt;&lt; endl; head = head-&gt;next; } //one extra for the node at the end cout &lt;&lt; head-&gt;data &lt;&lt; endl; } } </code></pre> <p>to the for loops above. Is there anything else I should keep in mind? I'm following the Stanford CS linked list basics and problem set.</p>
[]
[ { "body": "<p>This is C++, not C. Therefore, your linked list class should contain the methods for operating on the list, and it shouldn't expose implementation details like nodes. For traversing the list, provide iterators. You should also make it a template so that it can be used with any type</p>\n\n<p>That's the general picture. More specifically:</p>\n\n<ul>\n<li>If you insist on traversing with a dedicated function for it, make it take a function (or functor!) so that anything can be done with the nodes.</li>\n<li>You've not created any mechanism for deleting the nodes. Your class should do that in its destructor.</li>\n<li>You're not doing a lot of error checking that you should be. That's not as relevant when you turn it into a class, but making sure <code>head</code> isn't null is very important. You're doing that in <code>traverse</code> now, but <code>length</code> also needs it.</li>\n</ul>\n\n<p>To summarise, if the user of your class sees a single pointer, you can be sure you're doing it wrong.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:43:34.563", "Id": "9196", "ParentId": "9193", "Score": "5" } } ]
{ "AcceptedAnswerId": "9196", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T17:40:25.480", "Id": "9193", "Score": "3", "Tags": [ "c++" ], "Title": "Linked List review" }
9193
<p>I started playing with Python last week. This is a section of code from an application which reads a configuration file and launches <code>ssh</code> sessions and continuously displays data back to the local user.</p> <p>The whole project is <a href="https://github.com/maxmackie/vssh" rel="nofollow">on Github</a>.</p> <pre><code>def open_connections(sessions): """ open_connections(sessions) Opens ssh connections and forks them to the background. Passwords are sent from the user via STDIN to each process. If correctly identified, the process is successfully created and added to the Session object. """ for server in sessions: usr = raw_input("Enter username for " + server.address + ": ") pwd = getpass.unix_getpass("Enter passphrase for " + server.address + ": ") con = paramiko.SSHClient() con.set_missing_host_key_policy(paramiko.AutoAddPolicy()) con.connect(server.address, username=usr, password=pwd) print "[OK]" server.connection = con def run(sessions): """ run(sessions) Takes the file descriptors from the open sessions and runs the commands at the specified intervals. Display the STDOUT to the current tty. """ while True: time.sleep(TIMEOUT) os.system("clear") for session in sessions: print session.command + " @ " + session.address print "------------------------------------------------------------" stdin, stdout, stderr = session.connection.exec_command(session.command) print format_stdout(stdout.readlines()) </code></pre> <p>A couple of my concerns:</p> <ul> <li>Am I doing any big Python no-nos?</li> <li>Am I following proper comment/code conventions?</li> <li>Is this the best way to display continuous information to user (screen refreshes)?</li> </ul> <p>This is my first contact with Python so I'm definitely doing something I shouldn't be. The rest of the code for this project is really only 1 file, and what I posted above is the bulk of it. If anyone went to the Github page and wanted to comment on something else, I'd be happy to respond.</p>
[]
[ { "body": "<pre><code> usr = raw_input(\"Enter username for \" + server.address + \": \")\n pwd = getpass.unix_getpass(\"Enter passphrase for \" + server.address + \": \")\n con = paramiko.SSHClient()\n</code></pre>\n\n<p>I'd avoid using abbreviations. Call them <code>username</code> and <code>password</code> and <code>connection</code>. You don't gain anything using abbreviations and it reduces readability.</p>\n\n<pre><code> for session in sessions:\n\nfor server in sessions:\n</code></pre>\n\n<p>Are they servers or sessions? </p>\n\n<p>I'd also move the contents of the loop into methods on your session objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T13:55:56.433", "Id": "14441", "Score": "1", "body": "I'll make the comments more descriptive to avoid any ambiguity. Also, you're right. I didn't even notice I'm calling them sessions and servers. You mean instead of looping the logic, loop calling a logic method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:03:57.587", "Id": "14442", "Score": "0", "body": "@MaxMackie, comments? I didn't mention any coments. Yes, loop calling a logic method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:21:00.583", "Id": "14447", "Score": "0", "body": "My bad, typo. It's early :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T03:59:09.033", "Id": "9212", "ParentId": "9195", "Score": "5" } }, { "body": "<h2>Docstrings</h2>\n\n<p>This:</p>\n\n<pre><code>def open_connections(sessions):\n \"\"\" open_connections(sessions)\n Opens ssh connections and forks them to the background. Passwords are sent\n from the user via STDIN to each process. If correctly identified, the\n process is successfully created and added to the Session object.\n \"\"\"\n\n for server in sessions:\n # ...\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>def open_connections(sessions):\n \"\"\"Opens ssh connections and forks them to the background.\n\n Passwords are sent from the user via STDIN to each process. If correctly\n identified, the process is successfully created and added to the Session\n object.\n\n \"\"\"\n for server in sessions:\n # ...\n</code></pre>\n\n<p>To know more, take a look at <a href=\"http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings\" rel=\"nofollow noreferrer\">PEP257</a> about multi line docstrings.</p>\n\n<p>There's also no need to repeat the function declaration inside your docstring. If you tomorrow decide to use <a href=\"http://sphinx.pocoo.org/\" rel=\"nofollow noreferrer\">Sphinx</a> for generating your code documentation, that part will be taken care of on its own. You can find other possible conventions on docstrings <a href=\"http://packages.python.org/an_example_pypi_project/sphinx.html#function-definitions\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<h2>while 1 and while True</h2>\n\n<p>Replace this:</p>\n\n<pre><code>while True:\n # ...\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>while 1:\n # ...\n</code></pre>\n\n<p>This will do a tiny difference in Python 2 (in Python 3 they will be exactly the same). This topic was well discussed on SO <a href=\"https://stackoverflow.com/q/3815359/1132524\">here</a>.</p>\n\n<h2>print formatting</h2>\n\n<p>This line:</p>\n\n<pre><code>print \"------------------------------------------------------------\"\n</code></pre>\n\n<p>Will be more readable this way:</p>\n\n<pre><code>print \"-\" * 60\n</code></pre>\n\n<p>Check out the <a href=\"http://docs.python.org/library/string.html#format-specification-mini-language\" rel=\"nofollow noreferrer\">Format Specification Mini-Language</a> if you want to do something fancy.</p>\n\n<h2>Don't shadow the built-in</h2>\n\n<p>I tracked down in your repository, this function:</p>\n\n<pre><code>def format_stdout(stdout):\n \"\"\" format_stdout(stdout)\n Takes the list from the stdout of a command and format it properly with\n new lines and tabs.\n \"\"\"\n\n nice_stdout = \"\"\n for tuple in stdout:\n nice_stdout += tuple\n return nice_stdout\n</code></pre>\n\n<p>Do not use <code>tuple</code> as variable because it will shadow the built in <a href=\"http://docs.python.org/library/functions.html#tuple\" rel=\"nofollow noreferrer\"><code>tuple()</code></a>. But more important I think that <strong>you don't need this function at all</strong>.</p>\n\n<p>Take a look at <a href=\"http://docs.python.org/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join()</code></a>, it will be faster and better (since strings in Python are immutables).</p>\n\n<p>So you should replace this line:</p>\n\n<pre><code>print format_stdout(stdout.readlines())\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>print ''.join(stdout.readlines())\n</code></pre>\n\n<h2>Write only one time what you could write several</h2>\n\n<p>Change this:</p>\n\n<pre><code>usr = raw_input(\"Enter username for \" + server.address + \": \")\npwd = getpass.unix_getpass(\"Enter passphrase for \" + server.address + \": \")\n</code></pre>\n\n<p>To something like:</p>\n\n<pre><code>template_msg = \"Enter {} for \" + server.address + \": \"\nusr = raw_input(template_msg.format(\"username\"))\npwd = getpass.unix_getpass(template_msg.format(\"passphrase\"))\n</code></pre>\n\n<p>This way you'll be also also calling server.address one time, and one line less to maintain :)</p>\n\n<h2>Clear console</h2>\n\n<p>It will be better to avoid calling <a href=\"http://docs.python.org/library/os.html#os.system\" rel=\"nofollow noreferrer\"><code>os.system</code></a> directly, the <a href=\"http://docs.python.org/library/subprocess.html#module-subprocess\" rel=\"nofollow noreferrer\"><code>subprocess</code></a> module is there exactly for that.</p>\n\n<p>Anyway calling clear is not your only option: check out this <a href=\"https://stackoverflow.com/q/2084508/1132524\">SO question</a>.</p>\n\n<h2>Don't check the lenght of a list</h2>\n\n<h3>(unless you really need to know how long it is)</h3>\n\n<p>Again peeking from your git repo, I've found this:</p>\n\n<pre><code>if ( len(sessions) == 0 ):\n</code></pre>\n\n<ol>\n<li><p>Lose the brackets:</p>\n\n<pre><code>if len(sessions) == 0:\n</code></pre>\n\n<p>This will work too, Python is not C/C++ so don't put brackets everywhere :)</p></li>\n<li><p>More important check the list directly:</p>\n\n<pre><code>if session:\n # sessions is not empty\nelse:\n # sessions is empty\n</code></pre></li>\n</ol>\n\n<p>The implicit boolean conversion is a very smart Python feature :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T14:38:41.593", "Id": "15289", "Score": "1", "body": "Wow, thanks for an amazing breakdown of some key features I'm still missing in Python. +1 and accepted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T14:18:40.620", "Id": "9671", "ParentId": "9195", "Score": "5" } } ]
{ "AcceptedAnswerId": "9671", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:14:44.380", "Id": "9195", "Score": "4", "Tags": [ "python", "optimization", "beginner", "session" ], "Title": "Display data based on read configuration file from ssh sessions" }
9195
<p>I have a function that compares sequential elements from a python list and returns 1 and -1:</p> <pre><code>&gt;&gt;&gt; up_down([0, 2, 1, 3]) [1, -1, 1] </code></pre> <p>I need a function to return all possible lists from a '-1, 1' list using the function up_down.</p> <pre><code>&gt;&gt;&gt; possible_lists([1, -1]) [[0, 2, 1], [1, 0, 2]] </code></pre> <p>I'd like to know if I can write these functions in a better way. My code is below:</p> <pre><code>import itertools def comparison(a, b): if b &gt; a: return 1 if b &lt; a: return -1 else: return 0 def up_down(data, n=1): return [comparison(data[pos], data[pos + n]) for pos, value in enumerate(data[:-n])] def possible_lists(data, n=1): size = len(data) + n all_lists = itertools.permutations(range(size), size) return [list(el) for el in all_lists if up_down(el, n) == data] </code></pre>
[]
[ { "body": "<p>Your <code>comparison</code> function is the same as the builtin <code>cmp</code> function.</p>\n\n<p>Your filtering technique to find the matching lists may be not the most efficient. Permutations will generate a lot of lists which fail the test. On the other hand, itertools is written in C, which means it'll probably be faster for small data sets.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T21:05:25.050", "Id": "14414", "Score": "0", "body": "Thanks, @Winston. What alternative do I have if I need to use data sets between 10 and 20 elements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T04:01:05.210", "Id": "14422", "Score": "0", "body": "@MarcosdaSilvaSampaio, start with a recursive algorithm that calculate what permutations does. Then abandon any list as soon as its not a valid prefix of your desired list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T19:15:04.483", "Id": "9198", "ParentId": "9197", "Score": "1" } }, { "body": "<p>For up_down, the algorithm is good, but can be implemented more simply:\nUse cmp built-in, thx to @Winston\nUse itertools built-ins to eliminate redundant index math,\nindexed access(\"[]\") , and list copying (\"[:]\").</p>\n\n<pre><code># compare each element with its nth successor.\ndef up_down(data, n=1):\n # iterate in parallel over data and its n-shifted slice\n return imap(cmp, data, itertools.islice(data, n, None))]\n</code></pre>\n\n<p>For possible_lists, you could do much better than generating the entire\npermutation set. Instead, consider an approach that generates an initial\nlist that provably matches the up_down data and then applies a series\nof mutations to that list, generating other lists that preserve its up_down \nprofile until all such lists have been provably generated.</p>\n\n<p>In an optimal solution, </p>\n\n<ul>\n<li><p>the initial list would be cheap to generate</p></li>\n<li><p>the initial list would be \"minimal\" according to some metric.</p></li>\n<li><p>the mutator function would generate the next minimal list \n(i.e. \"next most minimal?\" \"next least?\").</p></li>\n</ul>\n\n<p>In a less-than-optimal solution,</p>\n\n<ul>\n<li><p>the initial list would at least be cheaper to generate than it would\nbe to discover by the OP's \"permute and test\" method</p></li>\n<li><p>the \"minimality\" idea could be abandoned</p></li>\n<li><p>the mutator function could generate a set of successor lists, test\nthem against the set of lists already seen, and mutate any one of \nthem that isn't in a set of those already mutated.</p></li>\n</ul>\n\n<p>I believe that an optimal solution is worth pursuing, especially since \nit might allow possible_lists to export a \"generator\" interface that\nproduced each matching list sequentially with a minimal memory footprint.</p>\n\n<p>I also believe that a good solution for n > 1 is likely to be found by\nsomehow post-processing all combinations of the n independent solutions for the\nlists of every nth element of the original.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T01:29:20.140", "Id": "9210", "ParentId": "9197", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T18:55:53.977", "Id": "9197", "Score": "2", "Tags": [ "python" ], "Title": "All possible lists from ups and downs between elements in python list" }
9197
<p>I could not find a Boost Python converter which converts <code>std::tuple</code>, so I wrote one.</p> <p>This was tested with a g++ 4.7 snapshot on Debian squeeze. It uses C++ 11 features, specifically variadic templates, so requires a recent compiler. This is based on <a href="https://stackoverflow.com/a/7858971/350713">the answer to ""unpacking" a tuple to call a matching function pointer"</a>.</p> <p>It is rather long, and could probably be improved/simplified. In particular, the two *_wrapper structures look redundant. How do I replace the <code>cpptuple2pytuple_wrapper</code> and <code>pytuple2cpptuple_wrapper</code> with one struct, and perhaps template on the differences using something like type traits, if that is possible? Any other simplifications would also be interesting.</p> <h1>cpptup_conv_pif.cpp</h1> <pre><code>#include &lt;tuple&gt; #include &lt;string&gt; #include &lt;iostream&gt; using std::cout; using std::endl; using std::string; #include &lt;boost/python/tuple.hpp&gt; #include &lt;boost/python/extract.hpp&gt; #include &lt;boost/python/object.hpp&gt; #include &lt;boost/python/module.hpp&gt; #include &lt;boost/python/class.hpp&gt; #include &lt;boost/python/def.hpp&gt; using boost::python::extract; template&lt;int ...&gt; struct seq{}; template&lt;int N, int ...S&gt; struct gens : gens&lt;N-1, N-1, S...&gt;{}; template&lt;int ...S&gt; struct gens&lt;0, S...&gt; {typedef seq&lt;S...&gt; type;}; template &lt;typename ...Args&gt; struct cpptuple2pytuple_wrapper { std::tuple&lt;Args...&gt; params; cpptuple2pytuple_wrapper(const std::tuple&lt;Args...&gt;&amp; _params):params(_params){} boost::python::tuple delayed_dispatch() { return callFunc(typename gens&lt;sizeof...(Args)&gt;::type()); } template&lt;int ...S&gt; boost::python::tuple callFunc(seq&lt;S...&gt;) { return boost::python::make_tuple(std::get&lt;S&gt;(params) ...); } }; template &lt;typename ...Args&gt; struct pytuple2cpptuple_wrapper { boost::python::tuple params; pytuple2cpptuple_wrapper(const boost::python::tuple&amp; _params):params(_params){} std::tuple&lt;Args...&gt; delayed_dispatch() { return callFunc(typename gens&lt;sizeof...(Args)&gt;::type()); } template&lt;int ...S&gt; std::tuple&lt;Args...&gt; callFunc(seq&lt;S...&gt;) { return std::make_tuple((static_cast&lt;Args&gt;(extract&lt;Args&gt;(params[S])))...); } }; // Convert (C++) tuple to (Python) tuple as PyObject*. template&lt;typename ... Args&gt; PyObject* cpptuple2pytuple(const std::tuple&lt;Args...&gt;&amp; t) { cpptuple2pytuple_wrapper&lt;Args...&gt; wrapper(t); boost::python::tuple bpt = wrapper.delayed_dispatch(); return boost::python::incref(boost::python::object(bpt).ptr()); } // Convert (Python) tuple to (C++) tuple. template&lt;typename ... Args&gt; std::tuple&lt;Args...&gt; pytuple2cpptuple(PyObject* obj) { boost::python::tuple tup(boost::python::borrowed(obj)); pytuple2cpptuple_wrapper&lt;Args...&gt; wrapper(tup); std::tuple&lt;Args...&gt; bpt = wrapper.delayed_dispatch(); return bpt; } template&lt;typename ... Args&gt; struct cpptuple_to_python_tuple { static PyObject* convert(const std::tuple&lt;Args...&gt;&amp; t) { return cpptuple2pytuple&lt;Args...&gt;(t); } }; template&lt;typename ... Args&gt; struct cpptuple_from_python_tuple { cpptuple_from_python_tuple() { boost::python::converter::registry::push_back( &amp;convertible, &amp;construct, boost::python::type_id&lt;std::tuple&lt;Args...&gt; &gt;()); } static void* convertible(PyObject* obj_ptr) { if (!PyTuple_CheckExact(obj_ptr)) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data) { void* storage = ( (boost::python::converter::rvalue_from_python_storage&lt;std::tuple&lt;Args...&gt; &gt;*) data)-&gt;storage.bytes; new (storage) std::tuple&lt;Args...&gt;(pytuple2cpptuple&lt;Args...&gt;(obj_ptr)); data-&gt;convertible = storage; } }; template&lt;typename ...Args&gt; void create_tuple_converter() { boost::python::to_python_converter&lt;std::tuple&lt;Args...&gt;, cpptuple_to_python_tuple&lt;Args...&gt; &gt;(); cpptuple_from_python_tuple&lt;Args...&gt;(); } void export_cpptuple_conv() { create_tuple_converter&lt;int, float&gt;(); create_tuple_converter&lt;int, double, string&gt;(); } std::tuple&lt;int, float&gt; tupid1(std::tuple&lt;int, float&gt; t){return t;} std::tuple&lt;int, double, string&gt; tupid2(std::tuple&lt;int, double, string&gt; t){return t;} BOOST_PYTHON_MODULE(bptuple) { export_cpptuple_conv(); boost::python::def("tupid1", tupid1); boost::python::def("tupid2", tupid2); } </code></pre> <p>This can be compiled with the following SConstruct file.</p> <h1>SConstruct</h1> <pre><code>#!/usr/bin/python import commands, glob, os def pyversion(): pystr = commands.getoutput('python -V') version = pystr.split(' ')[1] major, minor = version.split('.')[:2] return major + '.' + minor boost_python_env = Environment( #CXX="g++", CXX="g++-4.7", CPPPATH=["/usr/include/python"+pyversion()], CXXFLAGS="-ftemplate-depth-100 -fno-strict-aliasing -ansi -Wextra -Wall -Werror -Wno-unused-function -g -O3 -std=c++11", CPPDEFINES=['BOOST_PYTHON_DYNAMIC_LIB'], LIBPATH=["/usr/lib/python"+pyversion()+"/config"], LIBS=["python"+pyversion(), "m", "boost_python"], SHLIBPREFIX="", #gets rid of lib prefix ) boost_python_env.SharedLibrary(target="bptuple", source=["cpptup_conv_pif.cpp"]) </code></pre> <p>The compilation looks like this on my machine:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>g++-4.7 -o cpptup_conv_pif.os -c -ftemplate-depth-100 -fno-strict-aliasing -ansi -Wextra -Wall -Werror -Wno-unused-function -g -O3 -std=c++11 -fPIC -DBOOST_PYTHON_DYNAMIC_LIB -I/usr/include/python2.6 cpptup_conv_pif.cpp g++-4.7 -o bptuple.so -shared cpptup_conv_pif.os -L/usr/lib/python2.6/config -lblitz -lRmath -lpython2.6 -lm -lboost_python </code></pre> </blockquote> <p>Usage:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>In [1]: import bptuple In [2]: bptuple.tupid1((1,1.2)) Out[2]: (1, 1.2000000476837158) In [3]: bptuple.tupid2((1,1.2, "foo")) Out[3]: (1, 1.2, 'foo') </code></pre> </blockquote>
[]
[ { "body": "<p>One thing that's not immediately clear to me is if the <code>tuple2tuple_wrapper</code>'s are supposed to be internal helpers, or actually part of the interface. They seem to be instantiated only once each in the code shown, both immediately followed by a call to their <code>delayed_dispatch</code>.</p>\n\n<p>If these are only internal helpers, you could trim them down a lot. You'll still need a templated struct with a templated member function, since you have two template parameter packs. But you're not actually using <code>delayed_dispatch</code> as it's name suggests, so that can go. And then the <code>params</code> member and ctor can go as well, with <code>params</code> becoming an extra parameter to <code>callFunc</code>. Taking <code>cpptuple2pytuple_wrapper</code> as an example:</p>\n\n<pre><code>template&lt;typename... Args&gt;\nstruct cpp_to_py_wrapper { // I suck at typing typle\n template&lt;int... S&gt;\n boost::python::tuple callFunc(std::tuple&lt;Args...&gt; params, seq&lt;S...&gt;) {\n return boost::python::make_tuple(std::get&lt;S&gt;(params)...);\n }\n};\n</code></pre>\n\n<p><code>cpptuple2pytuple</code> then becomes:</p>\n\n<pre><code>template&lt;typename ... Args&gt; PyObject* cpptuple2pytuple(const std::tuple&lt;Args...&gt;&amp; t)\n{\n boost::python::tuple bpt = cpp_to_py_wrapper&lt;Args...&gt;().callFunc(t, typename gens&lt;sizeof...(Args)&gt;::type());\n return boost::python::incref(boost::python::object(bpt).ptr());\n}\n</code></pre>\n\n<p>Now you're just left with two instances of <code>callFunc</code>, both of which show a similar composition. If we just abstract for a bit:</p>\n\n<pre><code>template&lt;int ...S&gt;\nreturn_type callFunc(params_type params, seq&lt;S...&gt;)\n{\n return construct_tuple&lt;return_type&gt;(extract_tuple_value&lt;S, Args&gt;(params) ...);\n}\n</code></pre>\n\n<p>Now, this is definitely something that can be implemented generically. However, if you're only using this here, I'd actually advise against it. Since you're only defining two conversions, hardcoding both overloads of <code>callFunc</code> will likely be <em>less</em> work than providing suitable implementations of <code>construct_tuple</code> and <code>extract_tuple_value</code>. A generic implementation will likely not pay off until you want to convert between more than three types. That's the point were the number of pair-wise combinations of N elements starts to grow faster than N itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T16:29:50.980", "Id": "136556", "Score": "0", "body": "Thanks for the answer, Daan. Unfortunately, I don't remember this question that well - it has been a while. Working code would be helpful. I'm not sure what you mean by `typle2tuple` - there is no such name in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T16:35:11.050", "Id": "136559", "Score": "0", "body": "That should have been t*u*ple. I was referring to `cpptuple2pytuple_wrapper` and it's counterpart. As for the working code: like I said, I don't have a compatible build environment. So unless you can provide a self-contained drop of your code, I can't even test what I've written so far ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T16:54:36.453", "Id": "136568", "Score": "0", "body": "Define self-contained drop. I think if you cut and paste the code it will probably work. And I'm not sure what you mean by \"compatible build environment\". Can you elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T17:29:45.053", "Id": "136586", "Score": "0", "body": "Yes, all that is rather central to testing the example. :-) What is your OS/distribution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T18:33:49.283", "Id": "136611", "Score": "0", "body": "I use Debian wheezy. It's trivial to get all that stuff on Ubuntu. Try libboost-python-dev, scons, python-all-dev, g++. That would pull in most of it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T15:40:59.747", "Id": "75135", "ParentId": "9202", "Score": "3" } }, { "body": "<p>There is a way to simplify this by using only a single wrapper template. First, here's the single template:</p>\n\n<pre><code>template &lt;typename P, typename R, typename ...Args&gt;\nstruct tupleconvert_wrapper\n{\n P params;\n tupleconvert_wrapper(const P&amp; _params):params(_params){}\n\n R delayed_dispatch()\n {\n return callFunc(typename gens&lt;sizeof...(Args)&gt;::type());\n }\n\n template&lt;int ...S, typename = typename std::enable_if&lt;(sizeof(S),std::is_same&lt;boost::python::tuple, R&gt;::value), R&gt;::type&gt;\n boost::python::tuple callFunc(seq&lt;S...&gt;)\n {\n return boost::python::make_tuple(std::get&lt;S&gt;(params) ...);\n }\n\n template&lt;int ...S, typename = typename std::enable_if&lt;(sizeof(S),std::is_same&lt;boost::python::tuple, P&gt;::value), R&gt;::type&gt;\n std::tuple&lt;Args...&gt; callFunc(seq&lt;S...&gt;)\n {\n return std::make_tuple((static_cast&lt;Args&gt;(extract&lt;Args&gt;(params[S])))...);\n }\n};\n</code></pre>\n\n<p>Here are the uses of it, as converted from your original code.</p>\n\n<pre><code>// Convert (C++) tuple to (Python) tuple as PyObject*.\ntemplate&lt;typename ... Args&gt; PyObject* cpptuple2pytuple(const std::tuple&lt;Args...&gt;&amp; t)\n{\n tupleconvert_wrapper&lt;std::tuple&lt;Args...&gt;, boost::python::tuple, Args...&gt; wrapper(t);\n boost::python::tuple bpt = wrapper.delayed_dispatch();\n return boost::python::incref(boost::python::object(bpt).ptr());\n}\n\n// Convert (Python) tuple to (C++) tuple.\ntemplate&lt;typename ... Args&gt; std::tuple&lt;Args...&gt; pytuple2cpptuple(PyObject* obj)\n{\n boost::python::tuple tup(boost::python::borrowed(obj));\n tupleconvert_wrapper&lt;boost::python::tuple, std::tuple&lt;Args...&gt;, Args...&gt; wrapper(tup);\n std::tuple&lt;Args...&gt; bpt = wrapper.delayed_dispatch();\n return bpt;\n}\n</code></pre>\n\n<p>You may be wondering why the <code>sizeof(S)</code> is part of the <code>std::enable_if</code> clause. It's needed to force the <code>enable_if</code> to be dependent on the template parameter. Otherwise your compiler will issue an error as in <a href=\"https://stackoverflow.com/questions/13964447/why-compile-error-with-enable-if?rq=1\">this question</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T21:19:29.040", "Id": "75383", "ParentId": "9202", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T12:58:31.497", "Id": "9202", "Score": "14", "Tags": [ "c++", "c++11", "converting", "boost" ], "Title": "Boost Python converter for std::tuple" }
9202
<p>I have an old mp3 player with a broken screen. Consequently, it's a real pain to turn shuffle mode on and off; however, there are a few albums that I wanted to mix together and have shuffled for when I'm working out.</p> <p>That led me to whip up something in Python -- the first successful result was only about a dozen lines and could strip the track numbers from the beginning of files' names and replace them with random numbers.</p> <p>I wanted to learn argparse for another <a href="http://github.com/ryran/pyrite" rel="nofollow">more complicated project</a>, so I took the opportunity to spruce up my randrename script today.</p> <p>I started playing with Python in mid-December, but have been doing so in a vacuum with no peer-review, so.... I would happily receive any and all kinds of feedback you can offer. I'm quite confident in my general logic skills, so I'm most interested in any tips for making things more Pythonic. Thanks for reading this far!</p> <p>Here's the code:</p> <pre><code>#!/usr/bin/env python2 # # Last file mod: 2012/02/21 # Latest version at &lt;http://github.com/ryran&gt; # Copyright 2012 Ryan Sawhill &lt;ryan@b19.org&gt; # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License &lt;gnu.org/licenses/gpl.html&gt; for more details. #------------------------------------------------------------------------------ import random import os import argparse from textwrap import dedent from sys import stderr progname='randrename' parser = argparse.ArgumentParser( prog=progname, description=dedent(""" Insert random numbers into filenames or replace filenames with random numbers, optionally stripping characters from the beginning or end of said filenames. """), formatter_class=argparse.RawDescriptionHelpFormatter, epilog=dedent(""" ins-pos may be specified as (examples): 0 rand num will be inserted at beginning of filename 2 rand num will be inserted after the 2nd character of filename -1 rand num will be inserted after the last char of filename -3 rand num will be inserted after the 3rd from last char of filename NOTES: All operations (e.g. ins-pos, crop-right, and kill-name) are performed on the name of FILE sans its file extension. Use ignore-ext to change this behavior. If kill-name is specified, ins-pos, left-strip, &amp; crop-right will all be ignored (if they're specified). Lastly, if any cropping is requested, it will be performed before the random number (+ any specified separator chars) are inserted into the filename. EXAMPLES: [EXAMPLE CMD] [POSSIBLE OUTPUT] {prog} toaster.mp3 ==&gt; '71toaster.mp3' {prog} -s '. ' toaster.mp3 ==&gt; '20. toaster.mp3' {prog} -i1 toaster.mp3 ==&gt; 't66oaster.mp3' {prog} -i-1 -S_ toaster.mp3 ==&gt; 'toaster_24.mp3' {prog} -d3 -s. toaster.mp3 ==&gt; '395.toaster.mp3' {prog} -d4 -k 01.bak ==&gt; '8353.bak' {prog} -d4 -kx 01.bak ==&gt; '7279' {prog} -l2 -r1 01-AB.mp3 02-ZX.mp3.zip ==&gt; '50-A.mp3' '38-ZX.mp.zip' """.format(prog=progname))) parser.add_argument('filenames', metavar='FILE', nargs='+', help="file(s) to operate on") parser.add_argument('-i', '--ins-pos', metavar='N', type=int, default=0, help="position in filename to insert rand num (default: 0)") parser.add_argument('-d', '--num-digits', metavar='N', type=int, default=2, help="num of digits to use for rand num range (default: 2)") parser.add_argument('-S', '--lsep', metavar='C', default='', help="separator char(s) to prefix the random number with") parser.add_argument('-s', '--rsep', metavar='C', default='', help="separator char(s) to append to the random number") parser.add_argument('-l', '--lstrip', metavar='N', type=int, default=None, help="number of chars to strip from beginning of filename") parser.add_argument('-r', '--rstrip', metavar='N', type=int, default=None, help="number of chars to strip from end of filename") parser.add_argument('-w', '--wstrip', action='store_true', default=False, help="strip whitespace from beginning/end of filename") parser.add_argument('-k', '--kill-name', action='store_true', default=False, help="remove filename completely (excluding extension)") parser.add_argument('-x', '--ignore-ext', action='store_true', default=False, help="disable special treatment of file extensions (e.g. if used with --kill-name, extension is removed as well)") args = parser.parse_args() def get_path_components(fin, ignore_extension=False): """Break filename into component parts, i.e. path, filename, extension.""" # Split the path from the actual filename head, tail = os.path.split(fin) # Split filename and extension, unless ignoring extension if ignore_extension: filename = tail ext = '' else: filename, ext = os.path.splitext(tail) return head, filename, ext def generate_randint(num_digits, end): """Generate num_digits-long zero-filled random integer between 0 &amp; end.""" return str(random.randint(0, end)).zfill(num_digits) def update_filename(args, filename, ext, random_num): """Munge filename (&amp; potentially extension), dependent on options in args namespace.""" if args.wstrip: # Strip leading/trailing whitespace if requested filename = filename.strip() ext = ext.strip() # Strip num of chars from left &amp; right filename = filename[args.lstrip:args.rstrip] # If negative index, need to modify it if args.ins_pos &lt; 0: index = len(filename) + args.ins_pos + 1 else: index = args.ins_pos # Insert random_num into filename at proper index filename = filename[:index] + random_num + filename[index:] return filename, ext # If negative num-digits supplied, flip the sign if args.num_digits &lt; 0: args.num_digits *= -1 # Calculate high end of random number generation range rand_max = 10 ** args.num_digits - 1 # If right-strip was supplied, convert it to negative if args.rstrip &gt; 0: args.rstrip *= -1 # Process each file for fin in args.filenames: # Split fin into component parts head, filename, ext = get_path_components(fin, args.ignore_ext) # Prefix/append separator char(s) to random number num = args.lsep + generate_randint(args.num_digits, rand_max) + args.rsep # Replace filename with random num or insert rand num into filename if args.kill_name: filename = num else: filename, ext = update_filename(args, filename, ext, num) # Join file path, name, &amp; extension fout = os.path.join(head, filename + ext) # Rename! try: os.rename(fin, fout) except OSError as error: stderr.write("Error renaming FILE {!r}: {}\n".format(fin, error[1])) else: print("Renamed: {!r} ==&gt; {!r}".format(fin, fout)) </code></pre> <p>(Or at github, <a href="https://github.com/ryran/b19scripts/blob/master/randrename" rel="nofollow">https://github.com/ryran/b19scripts/blob/master/randrename</a>)</p>
[]
[ { "body": "<pre><code># Figure out high range for random number generation, based on num-digits arg\nrand_max = 0\nfor n in xrange(args.num_digits):\n if rand_max == 0: rand_max = '9'\n else: rand_max += '9'\nrand_max = int(rand_max)\n</code></pre>\n\n<p>This whole loop can be written as <code>rand_max = int('9' * args.num_digits)</code> or <code>rand_max = 10**args.num_digits - 1</code></p>\n\n<pre><code># Need to tweak this a little to make it optional\nif args.rstrip == 0:\n args.rstrip = None\nelif args.rstrip &gt; 0:\n args.rstrip = args.rstrip.__neg__() \n</code></pre>\n\n<p>You should almost never called <strong>functions</strong>. Instead use <code>-args.rstrip</code> </p>\n\n<pre><code># Process each file\nfor fin in args.filenames:\n</code></pre>\n\n<p>I recommend using <code>filename</code> rather then <code>fin</code></p>\n\n<pre><code> # Skip to the next file if no write permission on file\n if not os.path.isfile(fin):\n print(\"FILE {!r} not found\".format(fin))\n continue\n elif not os.access(fin, os.W_OK):\n print(\"No write permission for FILE {!r}\".format(fin))\n continue\n</code></pre>\n\n<p><code>continue</code> is rarely helpful. You should almost always use <code>else</code>. I also recommend catching exceptions rather then trying to check failure conditions.</p>\n\n<pre><code> # Split the path from the actual filename\n head, tail = os.path.split(fin)\n\n # Split filename and extension, unless ignore-ext opt provided\n if args.ignore_ext:\n filename = tail\n ext = ''\n else:\n filename, ext = os.path.splitext(tail)\n\n # Generate random number, zero-filled and prefix/append separator char(s)\n num = args.lsep + str(random.randint(0,rand_max)).zfill(args.num_digits) + args.rsep\n\n # Replace filename with random num or insert rand num into filename\n if args.kill_name:\n filename = num\n else:\n if args.wstrip:\n # Strip leading/trailing whitespace if requested\n filename = filename.strip()\n ext = ext.strip()\n # Strip num of chars from left &amp; right\n filename = filename[args.lstrip:]\n filename = filename[:args.rstrip:]\n</code></pre>\n\n<p>You should be able to combine these two lines</p>\n\n<pre><code> # Insert random number at proper position\n if args.ins_pos &lt; 0:\n # If negative index, need to modify it\n args.ins_pos = len(filename) + args.ins_pos + 1\n</code></pre>\n\n<p>It makes more sense to do this outside of your loop.</p>\n\n<pre><code> filename = filename[:args.ins_pos] + num + filename[args.ins_pos:]\n\n # Join file path, name, &amp; extension\n fout = os.path.join(head, filename + ext)\n\n # Rename!\n print(\"Renaming: {!r} ==&gt; {!r}\".format(fin, fout))\n os.rename(fin, fout)\n</code></pre>\n\n<p>Overall, it would be helped by using more functions. I'd aim for a body something like:</p>\n\n<pre><code>head, filename, ext = path_components(args, fin)\nrandom_number = generate_random_number(args)\nfilename = update_filename(args, random_number, filename)\nfout = os.path.join(head, filename + ext)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T09:20:40.327", "Id": "14434", "Score": "0", "body": "**1)** I love `rand_max = int('9' * args.num_digits)` and `rand_max = 10**args.num_digits - 1` -- I knew there was a way to make that block better. I feel kinda silly now. :) Can't decide which one to use either. **2)** I'd like to hear more on what you said about continue. I'm not convinced. My solution is succinct and simple and avoids having to indent the rest of the file. Why is this so bad? **3)** I don't see what you're talking about when you say \"You should be able to combine these two lines\". **4)** I also don't see how to do what you're saying (at the end) outside the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T09:22:53.507", "Id": "14435", "Score": "0", "body": "Because, as the code stands now, I need to mess with the value of filename, which is inside the loop.\n\nFinally: I took a KISS philosophy with this project -- it just didn't seem worth it to split the logic up into functions. But I'll play with that. THANKS for your feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T11:18:49.283", "Id": "14440", "Score": "0", "body": "A reason occurred to me for why you might have not liked my error-checking + continue statement at the beginning of the for loop. While that kind of setup would be more efficient if there were tons of bad filenames, it comes at the cost of being less efficient on good filenames. So I get it. I changed it to a try/except block around the rename at the end. Thanks again for making me think. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:15:35.277", "Id": "14444", "Score": "0", "body": "@ryan, `continue` is a bit of a personal preference thing. If you look at the equivalent `else` and `continue` versions, I think the else version is easier to follow. If you put `continue` it makes if act like an if/else, so I figure you should use an if/else. I guess I don't see saving a level of indent as worthwhile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:17:40.860", "Id": "14445", "Score": "0", "body": "Unless I'm missing something you should be able to use `filename = filename[args.lstrip:args.rstrip]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:19:11.700", "Id": "14446", "Score": "0", "body": "Regarding 4, you are right, I missed that. But it seems to me that your code is wrong. You modify args at that point given the length of the current filename. But what happens with the next filename? It'll use the value you calculate here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:22:29.327", "Id": "14448", "Score": "0", "body": "I find that almost any amount of logic is worth splitting into functions. Again, that's a personal style issue. I think its much easier to grasp the overall logic of your new version without getting bogged down in the details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:27:38.430", "Id": "14449", "Score": "0", "body": "Regarding checking vs try/except. You are correct that this is going to generally be more efficient. Your original loop has to make three system calls which are really expensive. The new loop has to make a single system call. The best that could happen for the first loop is to bail out after the first call, leaving it at best only slightly more efficient then the try/except loop. Additionally, the status of a file could change while your program is running. If that happens, your checks will pass and then you'll get an exception trying to actually rename the file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:33:16.363", "Id": "14451", "Score": "0", "body": "Admittedly thats kinda far fetched. But using try/except: that case will be handled correctly. Also, what if you missed a failing case? You can be pretty sure that no matter what goes wrong with renaming it, the exception code caught it. Can you say the same for the if-checking code? Stylistically, I also think it produces easier to follow code. Overall, catching exceptions rather then detecting failing conditions generally works better. Lastly, your `except: raise` bit doesn't do anything (except waste cpu cycles)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T18:23:54.427", "Id": "14467", "Score": "0", "body": "**(A)** You _are_ missing something with condensing args.lstrip & args.rstrip into one line. **(B)** WOW! You're absolutely right about #4. Thanks for catching that. I'm shocked I made that mistake. **(C)** Re logic/flow/functions: After pondering it a bit, I kinda landed on that same side of the fence as you just described -- that even if it makes the script longer, it allows one to take a quick glance and grasp the main flow without focusing on all the details. **(D)** Good point on file-status changing during operation. In the end I definitely came to appreciate the whole try/except logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T18:54:46.840", "Id": "14470", "Score": "0", "body": "Ahhh. I get what you mean about the `except: raise`. I've been doing it wrong. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T19:03:59.063", "Id": "14472", "Score": "0", "body": "PS: You weren't missing anything about how I could condense two lines down to `filename = filename[args.lstrip:args.rstrip]`. I was dumb. Thanks again." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T02:36:11.457", "Id": "9211", "ParentId": "9205", "Score": "2" } } ]
{ "AcceptedAnswerId": "9211", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-20T23:06:26.777", "Id": "9205", "Score": "1", "Tags": [ "python", "random" ], "Title": "randrename -- insert random nums in filenames" }
9205
<p>I have a directory of .xls workbooks with the following naming convention:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>001.WIP Monthly Report 002.WIP Joes Custom Report ... 129.PUR Supplier Spend </code></pre> </blockquote> <p>The number of worksheets in each workbook varies but each worksheet is formatted the same way.</p> <p>Row 5 holds column headers and rows 6 and beyond hold data:</p> <blockquote> <pre class="lang-none prettyprint-override"><code> A B C D 4| | | | ... 5| Org | Project | Task | ... 6| 023 | XYZ | 01304 | ... 7| 010 | ABC | 26453 | ... 8| ... | ... | ... | ... </code></pre> </blockquote> <p>My goal was to write a script that loops through every workbook in the directory, then loops through their respective worksheets and documents the column headers that they contain.</p> <p>A sample output of this script would be something like:</p> <blockquote> <pre class="lang-none prettyprint-override"><code> A B C D E F 1| | | Org | Project | Task | ... 2| 001 | Sheet1 | X | | X | ... 3| 001 | Sheet2 | X | X | | ... 4| 002 | Sheet1 | | | X | ... 5| ... | ... | ... | ... | ... | ... 6| 129 | Sheet8 | X | X | X | .. </code></pre> </blockquote> <p>where column A is the first 3 digits of the workbook name, B is the worksheet name, and C and beyond contain the column headers and an X documenting whether or not that worksheet contains that column header. Also, if a worksheet started with "SQL" or "---" I wanted it to be ignored.</p> <p>Here is the script:</p> <pre class="lang-powershell prettyprint-override"><code>#a function I found online for practicing good hygiene function Release-Ref ($ref) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } # ----------------------------------------------------- #open up a new instance of excel $xl = new-object -comobject excel.application $xl.Visible = $True $xl.DisplayAlerts = $False #open up a blank workbook that already exists on the desktop #I refer to this as the $master workbook $master = $xl.Workbooks.Open("c:\Users\me\desktop\master.xlsx") $mws = $master.Worksheets.Item(1) #initialize the row and column counters for the $master workbook $c = 2 $r = 1 #specify the directory of workbooks to be analyzed $files = dir("c:\Users\me\desktop\exports\*.xls") #loop through the workbooks in the directory foreach ($f In $files) { $wb = $xl.Workbooks.Open($f.FullName) #loop through the worksheets in the current workbook for ($i = 1; $i -le $wb.Sheets.count; $i++) { #if the first three characters of the worksheet are "SQL" or "---" then continue #else record the first three digits of the workbook name and the worksheet name $ws = $wb.Worksheets.Item($i) $wsns = $ws.Name.Substring(0,3) if ( $wsns -eq "SQL" ) { continue } elseif ( $wsns -eq "---" ) { continue } else { $r++ $mws.Cells.Item($r,1) = $wb.Name.Substring(0,3) $mws.Cells.Item($r,2) = $ws.Name } #for each column in the worksheet, get the cell value in row 5. #if the cell value is blank, then go to the next cell. #if 4 cells in a row are blank then break and go to the next worksheet. #we need to let 4 blank cells go by due to the formatting of some of the workbooks to be analyzed #I picked 200 iterations because none of the workbooks being analyzed should have more columns than that. $blnk = 0 for ($z = 1; $z -le 200; $z++) { $v = $ws.Cells.Item(5,$z).Value() if ( $v -eq $Null ) { $blnk++ if ($blnk -eq 4) { break } continue } #compare the current value of $v to all the previous values of $v that have already been stored in row 1 of the $master workbook #I picked 5000 iterations arbitrarily. There should definitely not be this many columns by the end of the script execution. for ($x = 3; $x -le 5000; $x++) { $mwsv = $mws.Cells.Item(1,$x).Value() #if the value of $v matches the value of a cell in row 1 of the $master workbook then put an x in that column instead of creating a new column if ( $mwsv -eq $v ) { $mws.Cells.Item($r,$x) = "x" break } #elseif $mwsv is blank then we have hit the end of list without finding a matching column #we should create a new column and mark an "x" in the row for the current sheet. elseif ( $mwsv -eq $Null ) { $c++ $mws.Cells.Item(1,$c) = $v $mws.Cells.Item($r,$c) = "x" } } } } #close the current workbook $wb.Close($False) Release-Ref $wb } #save the $master workbook and quit excel $master.Save() Release-Ref $mws Release-Ref $master $xl.Quit() Release-Ref $xl </code></pre> <p>The script did exactly what I wanted it to but it took forever. It found 1518 unique column headers for 330 worksheets in 129 workbooks but it took a day and a half to do so. Is there any optimization I can make to this script? Are there alternatives to Powershell that would be much faster?</p> <p>I ran this script on a Dell Latitude with Windows 7 Pro, Intel Core i5-2540M 2.6GHz, 4GB RAM. CPU usage while the script was running was about 40%-70%.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T20:02:39.020", "Id": "17478", "Score": "1", "body": "Perhaps this would be easier with a db? Even in MSAccess - just link all the tables (a lot of work with so many, but once it's done, it's done)." } ]
[ { "body": "<p>I find it easier to use the Interop vs. COM approach to Office automation. If nothing else it makes finding values to the enumerated types easier, everything else is basically the same.</p>\n\n<pre><code>Add-Type -ASSEMBLY \"Microsoft.Office.Interop.Excel\"\n</code></pre>\n\n<p>You should also look at $WorkSheet.UsedRange This will give you a range (Row and Columns) that excel identifies as having data.</p>\n\n<pre><code>$WorkSheet.UsedRange.Rows.Count\n$WorkSheet.UsedRange.Columns.Count\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-30T14:06:33.890", "Id": "25650", "ParentId": "9209", "Score": "5" } }, { "body": "<p>I know this question is a bit old, but I ran into it while looking for other Excel/PowerShell help and had recently found one potential fix. A two line change may actually speed up the entire process significantly. </p>\n\n<p>Change from:</p>\n\n<pre><code>#loop through the worksheets in the current workbook\nfor ($i = 1; $i -le $wb.Sheets.count; $i++)\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>#loop through the worksheets in the current workbook\n$sheetCount = $wb.Sheets.Count\nfor ($i = 1; $i -le $sheetCount; $i++)\n</code></pre>\n\n<p>The reason lies in how the COM object works internally, which I can't fully explain myself. <a href=\"https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects/158839#158839\">This StackOverflow question</a> briefly reviews why not to use 2 dots when referencing COM objects. Second, <a href=\"http://sushihangover.blogspot.com/2012/03/powershell-excel-olecom-automation.html\" rel=\"nofollow noreferrer\">this blog post</a> identifies this specific change as improving performance from 14 minutes to 10s. I haven't validated myself, but I would expect some improvement. Hope that helps... even if it is over a year late.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-21T03:39:15.417", "Id": "32989", "ParentId": "9209", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T01:28:35.767", "Id": "9209", "Score": "9", "Tags": [ "performance", "beginner", "vba", "excel", "powershell" ], "Title": "Powershell script for manipulating Excel files" }
9209
<p>I wrote a simple client for handlersocket server, but I'm not a professional Java programmer and would like to know the opinion of Java developers on my code.</p> <p>Well I have not yet decided how to implement a class <code>HSResult</code>.</p> <p>My project is <a href="https://github.com/komelgman/Java-HandlerSocket-Connection" rel="nofollow">here</a></p> <p><code>HSResult</code> store initial query and answer as <code>List</code> of <code>ChannelBuffer</code>s, where each <code>ChannelBuffer</code> it chunk of response according to the <a href="https://github.com/DeNADev/HandlerSocket-Plugin-for-MySQL/blob/master/docs-en/protocol.en.txt" rel="nofollow">protocol</a>.</p> <pre><code>package kom.handlersocket.result; import org.jboss.netty.buffer.ChannelBuffer; import kom.handlersocket.query.HSQuery; import kom.handlersocket.core.SafeByteStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class HSResult { private final HashMap&lt;HSQuery, List&lt;ChannelBuffer&gt;&gt; resultSet = new LinkedHashMap&lt;HSQuery, List&lt;ChannelBuffer&gt;&gt;(); private final Charset charset; public HSResult(Charset charset) { this.charset = charset; } public void add(HSQuery query, List&lt;ChannelBuffer&gt; result) { resultSet.put(query, result); } public void debug() { SafeByteStream output = new SafeByteStream(1024, 65536, charset); for (Map.Entry&lt;HSQuery, List&lt;ChannelBuffer&gt;&gt; entry: resultSet.entrySet()) { entry.getKey().encode(output); System.out.print(new String(output.toByteArray(), charset)); output.reset(); for (ChannelBuffer buffer : entry.getValue()) { System.out.print(buffer.toString(charset)); System.out.print("-"); } System.out.println(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T19:44:26.037", "Id": "14474", "Score": "0", "body": "Please include code in the question. (Check the FAQ.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T07:03:23.457", "Id": "14514", "Score": "0", "body": "it too much. I would like to know how well I use a collection and how well I use Netty.\n\nSeparately, I wanted to board the best way to make interpreting the results in class HSResult" } ]
[ { "body": "<ol>\n<li><p>The type of the <code>resultSet</code> reference could be simply <code>Map&lt;...&gt;</code>:</p>\n\n<pre><code>private final Map&lt;HSQuery, List&lt;ChannelBuffer&gt;&gt; resultSet\n</code></pre>\n\n<p>Reference: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p>Instead of the <code>Map&lt;HSQuery, List&lt;ChannelBuffer&gt;&gt;</code> I'd use <a href=\"http://docs.guava-libraries.googlecode.com/git-history/v12.0/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow\">Guava's Multimap</a>. It was \n<a href=\"http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap\" rel=\"nofollow\">designed for this case</a>.</p></li>\n<li><p>Constructors and methods should validate their input parameters.</p>\n\n<pre><code>public HSResult(Charset charset) {\n this.charset = charset;\n}\n</code></pre>\n\n<p>Does it make sense to have a <code>charset</code> with <code>null</code>? If not, check it and throw an <code>NullPointerException</code>. (<em>Effective Java, Second Edition</em>, <em>Item 38: Check parameters for validity</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-19T19:31:07.907", "Id": "11911", "ParentId": "9215", "Score": "2" } } ]
{ "AcceptedAnswerId": "11911", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T09:59:26.440", "Id": "9215", "Score": "1", "Tags": [ "java", "mysql" ], "Title": "Client for handlersocket server" }
9215
<p>I just invented <strong>PSEUDO Query</strong>!</p> <pre><code>var objects = $.pquery([ '##pquery##', // Initialize as PSEUDO Query Object [document.body, 'css', [{'background-color':'#f00'}], 'append', ['##pquery##', // Helps distinguish array needing parsing from array of arguments '&lt;div /&gt;', 'text', 'LOL!'] ], ['textarea', 'css', ['background-color', '#0f0']] ]); </code></pre> <p>...Is equivalent to:</p> <pre><code>var objects = [ $(document.body).css({background-color: '#f00'}).append($('&lt;div /&gt;').text('LOL!')), $('textarea').css('background-color', '#0f0') ]; </code></pre> <p>Example image:</p> <p><img src="https://i.stack.imgur.com/IoSgi.png" alt="enter image description here"></p> <p><strong>The point?</strong></p> <p>The point of this is in no way for added readability, but rather to provide a means to execute jQuery via PHP outputted JSON through Ajax. I believe this is going to make possible a nicely structured, and well defined output class for PHP, with very little code.</p> <p>Ultimately, my goal is to have all clients long polling the server, to accept new Javascript and commands at any given moment. I plan to use jQuery for exactly what it is, as a framework, and extend any common commands/routines directly to it as extensions. Eventually I'll revise the structure to support <code>$.method()</code> calls, without having to have a selector. I might need some ideas for the best way to go about that, without causing problems. </p> <p><strong>What are some concerns with this?</strong></p> <p>I wanted to avoid it, but I think I'm going to have to eval the Ajax array, for setting callback functions. Or I'll just pass it to a new <code>&lt;script /&gt;</code> element, and delete it after parse. Another option is to add some method to detect function structures, and pass the quoted code through <code>new Function</code>. The last option I can think of, is to only allow predefined functions, which I've already extended to jQuery. I've heard it is bad to pass Javascript through through JSON, however I feel it is necessary if I'm going to be constructing new objects with bound events. I also feel that maybe this whole thing may be a little redundant if I'm going to just eval the code, but there's still the factor of easy output with PHP, which makes me want to continue with this extension. <em>This is the area that I could really use the most advice and opinions about.</em></p> <p>Any structural/general ideas or concerns about this? Or possibly some suggestions to just scrap the whole thing, and start with a different approach to the madness?</p>
[]
[ { "body": "<p>I'm not sure if there is a real use for this. Web apps normally don't need to execute arbitrary JavaScript, but instead just have a static library which gets data via AJAX on what they want to do. Can you give a more concrete use case? </p>\n\n<p>Also I don't really understand what you are saying in the \"concerns\" section. Are you asking how to execute the \"generated\" JavaScript? In that case I'd use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"nofollow\"><code>apply</code></a> and/or <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call\" rel=\"nofollow\"><code>call</code></a>.</p>\n\n<p>Finally I'm not really fond of the marker string (<code>'##pquery##'</code>). I'm sure it's possible to use a different data structure that doesn't require it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:03:02.640", "Id": "14477", "Score": "0", "body": "I've added the code, and revised some of my explanations a little bit. For my concerns section, I'm basically trying to decide if I should allow raw Javascript to be passed or not. If you have some ideas for an easily identifiable structure, that would not require the header (`##pquery##`), please share. I'm mainly trying to get feedback about the structure of the \"protocol\". Feel free to revise your answer, I'm constantly rereading for things I may have missed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:08:33.173", "Id": "14478", "Score": "0", "body": "Basically, I need a structure that is capable of behaving exactly like jQuery, with full functionality." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:51:20.757", "Id": "9229", "ParentId": "9218", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:36:15.793", "Id": "9218", "Score": "-1", "Tags": [ "javascript", "jquery", "array", "ajax" ], "Title": "PSEUDO Query (jQuery extension)" }
9218
<p>I wrote the binary search algorithm with Ruby, the code is below. The question is if there's any way to make it look cleaner?</p> <pre><code>def binary_search(sample_array, x, l, r) mid = (l + r)/2 return -1 if r &lt; l return binary_search(sample_array, x, l, mid-1) if (sample_array[mid] &gt; x) return binary_search(sample_array, x, mid+1, r) if (sample_array[mid] &lt; x) return mid if (sample_array[mid] == x) end result = binary_search(sample_array, x, l, r) puts "#{result}" </code></pre> <p>It seems to me that returns can be minimised or even some more Ruby idioms added. Tried to use lambda, but smth went wrong.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:44:10.677", "Id": "14438", "Score": "0", "body": "If nothing else, you can make it tail-recursive by conditionally assigning a new value to `l` or `r` (or returning) according to the comparisons between `sample_array[mid]` and `x`." } ]
[ { "body": "<ul>\n<li>Rather than defining it at the top level, why don't you make it a new method on <code>Array</code>?</li>\n<li>Taking <code>l</code> and <code>r</code> makes recursive calls possible, but would be annoying for the end user who always has to pass <code>0</code> and <code>array.length-1</code>. You should either make those arguments optional, or don't use recursion, or use a private helper method for the recursion.</li>\n<li>Someone suggested you could make it tail-recursive, but I don't think any Ruby implementation I know of can optimize tail recursion, so I'm not sure what the point of that would be. Method calls are expensive in Ruby, so if you are after performance, I think a <code>while</code> loop would be more appropriate.</li>\n<li>You could consider calling <code>&lt;=&gt;</code> once and switching on the return value using <code>case</code>. I'm not sure if you would like the way this reads better or not. If performance is important, definitely try it and benchmark both ways.</li>\n<li>If you do want to use <code>if</code> statements, the 3rd <code>if</code> is redundant.</li>\n<li>You are using the type of binary search which has 3 different branches (depending on whether the value at the probed index is <code>&gt;</code>, <code>&lt;</code>, or <code>==</code> to the value you are searching for). There is another to write a binary search which only uses a single if-else, which is more concise, generally faster, and which is guaranteed to return the <em>first</em> matching element in the array (if there are duplicates).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T23:32:15.053", "Id": "14964", "Score": "0", "body": "Thanks for great pieces of advice! A lot of things to think on." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T14:55:19.793", "Id": "9270", "ParentId": "9220", "Score": "1" } } ]
{ "AcceptedAnswerId": "9270", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T07:13:47.243", "Id": "9220", "Score": "2", "Tags": [ "ruby", "algorithm", "search" ], "Title": "Refactoring binary search algorithm in Ruby" }
9220
<p>This program forms the reducer of a Hadoop MapReduce job. It reads data in from stdin that is tab delimited.</p> <pre><code>foo 1 foo 1 bar 1 </code></pre> <p>and outputs</p> <pre><code>foo 2 bar 1 </code></pre> <p>Any suggestions for improvements?</p> <pre><code>(use '[clojure.string :only [split]]) (def reducer (atom {})) (defn update-map [map key] (merge-with + map {key 1})) (doseq [line (line-seq (java.io.BufferedReader. *in*))] (let [k (first (split line #"\t"))] (swap! reducer update-map k))) (doseq [kv @reducer] (println (format "%s\t%s" (first kv) (second kv)))) </code></pre>
[]
[ { "body": "<p>Why don't you use <code>reduce</code> instead of the first <code>doseq</code>? Something along the lines (untested, entered directly here):</p>\n\n<pre><code>(def response\n (reduce (fn [map line]\n (let [k (fist (split line #\"\\t\"))]\n (update-map map k)))\n {} (line-seq (java.io.BufferedReader. *in*)))\n\n(doseq [kv response]\n (println (format \"%s\\t%s\" (first kv) (second kv))))\n</code></pre>\n\n<p>Then you won't need the <code>atom</code> either.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T07:28:51.450", "Id": "11196", "ParentId": "9221", "Score": "2" } }, { "body": "<p>probably a bit too late to help OP, but in case anyone else stumbles upon this question, here's a nice succinct way of doing it, using the <code>frequencies</code> function:</p>\n\n<pre><code>(doseq [[word freq] (frequencies\n (map\n #(re-find #\"^[^\\t]+\" %) ;; just get the first non-tab characters\n (line-seq (java.io.BufferedReader. *in*))))]\n (println (str word \"\\t\" freq)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T17:11:57.070", "Id": "14821", "ParentId": "9221", "Score": "4" } }, { "body": "<p>Can ouput contain numbers other than 1? Like:</p>\n\n<pre><code>foo 1\nfoo 3\nbar 10\n</code></pre>\n\n<p>If so, then:</p>\n\n<pre><code>(use '[clojure.string :only [split]])\n\n(def parsed-input\n (for [line (line-seq (java.io.BufferedReader. *in*))\n :let [[k v] (split line #\"\\t\")]]\n {k (Double/parseDouble v)}))\n\n(def table (apply (partial merge-with + {}) parsed-input))\n\n(doseq [[k v] table]\n (println (str k \"\\t\" v)))\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>bar 10.0\nfoo 4.0\n</code></pre>\n\n<p>If it's just 1's <code>frequencies</code> will do as suggested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-10T12:09:28.747", "Id": "27228", "ParentId": "9221", "Score": "0" } } ]
{ "AcceptedAnswerId": "14821", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T10:55:42.150", "Id": "9221", "Score": "4", "Tags": [ "clojure" ], "Title": "Clojure MapReduce Reducer" }
9221
<p>This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic. </p> <pre><code>from math import sqrt def mean(lst): """calculates mean""" sum = 0 for i in range(len(lst)): sum += lst[i] return (sum / len(lst)) def stddev(lst): """calculates standard deviation""" sum = 0 mn = mean(lst) for i in range(len(lst)): sum += pow((lst[i]-mn),2) return sqrt(sum/len(lst)-1) numbers = [120,112,131,211,312,90] print stddev(numbers) </code></pre>
[]
[ { "body": "<p>The easiest way to make <code>mean()</code> more pythonic is to use the <code>sum()</code> built-in function.</p>\n\n<pre><code>def mean(lst):\n return sum(lst) / len(lst)\n</code></pre>\n\n<p>Concerning your loops on lists, you don't need to use <code>range()</code>. This is enough:</p>\n\n<pre><code>for e in lst:\n sum += e\n</code></pre>\n\n<p>Other comments:</p>\n\n<ul>\n<li>You don't need parentheses around the return value (check out <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> when you have a doubt about this).</li>\n<li>Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative (\"returns the mean of lst\"). </li>\n<li>Why do you use \"-1\" in the return for stddev? Is that a bug?</li>\n<li>You are computing the standard deviation using the variance: call that \"variance\", not sum!</li>\n<li>You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)</li>\n<li>You shouldn't use pow() anyway, ** is enough.</li>\n</ul>\n\n<p>This would give:</p>\n\n<pre><code>def stddev(lst):\n \"\"\"returns the standard deviation of lst\"\"\"\n variance = 0\n mn = mean(lst)\n for e in lst:\n variance += (e-mn)**2\n variance /= len(lst)\n\n return sqrt(variance)\n</code></pre>\n\n<p>It's still way too verbose! Since we're handling lists, why not using list comprehensions?</p>\n\n<pre><code>def stddev(lst):\n \"\"\"returns the standard deviation of lst\"\"\"\n mn = mean(lst)\n variance = sum([(e-mn)**2 for e in lst]) / len(lst)\n return sqrt(variance)\n</code></pre>\n\n<p>This is not perfect. You could add tests using <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow noreferrer\">doctest</a>. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T08:23:14.387", "Id": "14515", "Score": "0", "body": "Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-30T20:09:27.300", "Id": "214384", "Score": "0", "body": "@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T16:41:52.520", "Id": "267801", "Score": "0", "body": "Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T19:19:50.133", "Id": "267841", "Score": "0", "body": "@CodyA.Ray Your Rev 2 corrected the result, but it was not the [right](https://en.wikipedia.org/wiki/Variance#Discrete_random_variable) fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T22:09:11.203", "Id": "267867", "Score": "0", "body": "@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the \"return\" line. But the equation seems correct for non-sampled std dev: http://libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/page_19.htm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T22:13:54.703", "Id": "267868", "Score": "0", "body": "@CodyA.Ray See Rev 3. By [definition](https://en.wikipedia.org/wiki/Variance), \"variance\" is the expected squared deviation from the mean. It is therefore important to put the division in the right place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T14:53:10.330", "Id": "425972", "Score": "0", "body": "@Quentin Pradet the -1 is a compensation factor to deal with outliers. To see the difference between stdev on sample space vs population: https://statistics.laerd.com/statistical-guides/measures-of-spread-standard-deviation.php" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T13:01:11.207", "Id": "9224", "ParentId": "9222", "Score": "14" } }, { "body": "<p>You have some serious calculation errors…</p>\n\n<hr>\n\n<p>Assuming that this is Python 2, you also have bugs in the use of division: if both operands of <code>/</code> are integers, then Python 2 performs integer division. Possible remedies are:</p>\n\n<ul>\n<li><a href=\"http://legacy.python.org/dev/peps/pep-0238/\" rel=\"noreferrer\"><code>from __future__ import division</code></a></li>\n<li>Cast one of the operands to a <code>float</code>: <code>return (float(sum)) / len(lst)</code>, for example.</li>\n</ul>\n\n<p>(Assuming that this is Python 3, you can just use <a href=\"https://docs.python.org/3/library/statistics.html#statistics.stdev\" rel=\"noreferrer\"><code>statistics.stdev()</code></a>.</p>\n\n<hr>\n\n<p>The formula for the sample standard deviation is</p>\n\n<p>$$ s = \\sqrt{\\frac{\\sum_{i=1}^{n}\\ (x_i - \\bar{x})^2}{n - 1}}$$</p>\n\n<p>In <code>return sqrt(sum/len(lst)-1)</code>, you have an error with the precedence of operations. It should be</p>\n\n<pre><code>return sqrt(float(sum) / (len(lst) - 1))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-26T23:40:48.793", "Id": "153210", "Score": "0", "body": "Source for formula?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-26T23:42:44.903", "Id": "153211", "Score": "0", "body": "@Agostino It's basically [common knowledge](http://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation) in statistics." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T16:56:52.243", "Id": "60931", "ParentId": "9222", "Score": "6" } } ]
{ "AcceptedAnswerId": "9224", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T11:03:27.313", "Id": "9222", "Score": "10", "Tags": [ "python", "statistics" ], "Title": "Calculating population standard deviation" }
9222
<p>I previously wrote the question about version 1 of my code, since then I have released a version 1.6.3. I would just like everyone's opinion on it. Here is the old question: <a href="https://codereview.stackexchange.com/questions/8331/filemaker-php-api-interface">FileMaker PHP API Interface</a></p> <p>The code interacts with the FileMaker API for PHP which is the Official version of the FileMaker PHP API (not the fx.php by iViking).</p> <p>This code helps users interact from the web to their FileMaker database. It does this by interacting with the FileMaker PHP API which retrieves XML from various requests to/from the server.</p> <p>It uses the HTTP protocol to retrieve this data if I recall correctly.</p> <p>The idea of this came from my Cybershade CMS project which can be found at <a href="http://github.com/cybershade/cmsv1" rel="nofollow noreferrer">http://github.com/cybershade/cmsv1</a> which is still under-development but it uses a simular syntax as this. </p> <p>The main reason I made this class was to create an easier method for users to interact with the database. </p> <p>Here is a link to the <a href="https://github.com/DarkMantisCS/FileMaker-PHP-API-Interface" rel="nofollow noreferrer">github</a></p> <p>And here is the code directly:</p> <pre><code>&lt;?php require_once ( 'fm_api/FileMaker.php' ); require_once ( 'config/config.php' ); /** * Interface between the FileMaker API and PHP - Written By RichardC * * @author RichardC * @version 1.6.3 * * @license GPLv3 */ class FMDB { /* * Filemaker LessThan/Equal to and GreaterThan/Equal to characters * Does not work in all IDE's * * Update: * Reason why I have defined these as a constant is because they will * never change. I have left them as a variable for those whom have already * started using it as a variable */ const LTET = '≤'; const GTET = '≥'; /** * Setting up the classwide variables */ protected $fm, $layout = '', $debugCheck = true, $fieldList = array(); public $revertedData = array(), $lastObj = null, $ltet = self::LTET, $gtet = self::GTET; /** Constructor of the class */ public function __construct() { //Performs all the relative checks that are required by the FM PHP API $this-&gt;doChecks(); $this-&gt;fm = new FileMaker( FMDB_NAME, FMDB_IP, FMDB_USERNAME, FMDB_PASSWORD ); } /** * Perform all checks before doing any thing * * @todo Will extend this function to perfrom more extensive tests * * @author RichardC * @version 1.0 * * @since 1.6 * * @return true */ protected function doChecks(){ if( !function_exists( 'curl_init' ) ){ die( 'Please enable cURL to use the FileMaker PHP API' ); } return true; } /** * Checks whether there is an error in the resource given. * * @author RichardC * @since 1.0 * * @version 1.6 * * @param obj $request_object * * @return int */ public static function isError( $request_object ) { if( is_array( $request_object ) &amp;&amp; preg_grep( '/^([^*)]*)error([^*)]*)$/', array_keys( $request_object ) ) ){ foreach( $request_object as $key =&gt; $val ){ return (int)$val; } } return ( FileMaker::isError( $request_object ) ? (int)$request_object-&gt;getCode() : 0 ); } /** * Just a quick debug function that I threw together for testing * * @author RichardC * @since 1.4 * * @version 1.4 * * @param string $func * @param array $arrReturn * @param string $type 'file' || 'console' * * @return mixed */ protected function debug( $func, $arrReturn, $type='file' ){ $debugStr = ''; if( $func == '' || empty( $func ) ){ return null; } $debugStr = ''; switch( $type ){ default: case 'file': $fo = fopen( DEBUG_LOCATION, 'a+' ); foreach( $arrReturn as $k =&gt; $v ){ $v = ( is_array( $v ) ? $v : array( $k =&gt; $v ) ); foreach( $v as $n =&gt; $m ){ $debugStr .= sprintf( '[Debug %s] %s - [ %s ] -&gt; %s %s', date( 'd-m-Y H:i:s' ), $func, $n, $m, "\n" ); } } fwrite( $fo, $debugStr ); fclose( $fo ); return true; break; case 'console': foreach( $arrReturn as $k =&gt; $v ){ $v = ( is_array( $v ) ? $v : array( $k =&gt; $v ) ); foreach( $v as $n =&gt; $m ){ $debugStr .= sprintf( '&lt;script type="text/javascript" console.log("[Debug] %s - %s -&gt; %s "); &lt;/script&gt;', $func, $n, $m ); } } return $debugStr; break; } } /** * Simular to select but just returns the fields which you wanted * * @todo Figure out a way to reduce the amount of loops or make the loops faster * * @warning This function is discouraged for a large amount of data due to the amount of loops * * @author RichardC * @since 1.6 * * @version 1.0 * * @param string $layout * @param array $arrSearchCriteria * @param array $arrFields * * @return array */ public function getFields( $layout, $arrSearchCriteria, $arrFields ){ $arrOut = array(); if( !ctype_alnum( (string)$layout ) || !is_array( $arrSearchCriteria ) ){ return $arrOut; } // If no fields are specified then perform a normal select if( empty( $arrFields ) || !is_array( $arrFields ) ){ return $this-&gt;select( $layout, $arrSearchCriteria ); } // Perform the select $select = $this-&gt;select( $layout, $arrSearchCriteria ); if( !$this-&gt;isError( $select ) ){ // Loop through the returned fields foreach( $select as $field =&gt; $contents ){ // Loop through the desired fields foreach( $arrFields as $f ){ if( $field == $f ){ $arrOut[$f] = $contents; } } } } return $arrOut; } /** * Selects data from a FileMaker Layout from the given criteria * * @author RichardC * @since 1.0 * * @version 1.4 * * @param string $layout * @param array $arrSearchCriteria * * @return array */ public function select( $layout, $arrSearchCriteria ) { $arrOut = array(); if ( ( !is_array( $arrSearchCriteria ) ) ) { return false; } $findReq = $this-&gt;fm-&gt;newFindCommand( $layout ); foreach ( $arrSearchCriteria as $field =&gt; $value ) { $findReq-&gt;addFindCriterion( $this-&gt;fm_escape_string( $field ), $this-&gt;fm_escape_string( $value ) ); } $results = $findReq-&gt;execute(); if ( $this-&gt;isError( $results ) === 0 ) { $fields = $results-&gt;getFields(); $records = $results-&gt;getRecords(); //Set the last used layout and object $this-&gt;layout = $layout; $this-&gt;lastObj = $records; //Loops through the records retrieved $i = 0; foreach ( $records as $record ) { $i++; foreach ( $fields as $field ) { $arrOut[$i]['rec_id'] = $record-&gt;getRecordId(); $arrOut[$i][$field] = $record-&gt;getField( $field ); } } } else { $arrOut['errorCode'] = $this-&gt;isError( $results ); } if( $this-&gt;debugCheck ){ foreach( $arrOut as $k =&gt; $v ){ $this-&gt;debug( 'SELECT', array( $k =&gt; $v )); } } return $arrOut; } /** * Sets Fields within a given Layout with the given criteria * * @author RichardC * @since 1.0 * * @version 1.2 * * @param array $arrFields * * @example $objFMDB-&gt;setFields( array( 'fieldName' =&gt; 'ValueToUpdate' ) ); * * @return bool */ public function setFields( $arrFields ) { $blOut = false; if ( ( !is_array( $arrFields ) ) ) { return false; } $layout = ( empty( $layout ) ? ( $this-&gt;layout ) : ( $layout ) ); $records = $this-&gt;lastObj; if ( isset( $records ) &amp;&amp; !empty( $records ) ) { foreach ( $records as $record ) { foreach ( $arrFields as $fieldName =&gt; $value ) { $record-&gt;setField( $this-&gt;fm_escape_string( $fieldName ), $this-&gt;fm_escape_string( $value ) ); } } $commit = $record-&gt;commit(); if ( $this-&gt;isError( $commit ) === 0 ) { $blOut = true; } else { return $this-&gt;isError( $commit ); } } // Housekeeping unset( $record, $commit, $fieldName, $value ); return $blOut; } /** * Updates a record by the given ID of the record on a specified layout * * @author RichardC * @since 1.0 * * @version 1.2 * * @param string $layout * @param array $arrFields * @param int $iRecordID * * @return bool */ public function updateRecordByID( $layout, $arrFields, $iRecordID ) { if ( ( $layout == '' ) || ( !is_array( $arrFields ) ) || ( !is_numeric( $iRecordID ) ) ) { return false; } $findReq = $this-&gt;fm-&gt;getRecordById( $layout, $iRecordID ); if ( $this-&gt;isError( $findReq ) === 0 ) { foreach ( $findReq as $record ) { foreach ( $arrFields as $f =&gt; $v ) { $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) ); } $commit = $record-&gt;commit(); } if ( $this-&gt;isError( $commit ) === 0 ) { return true; } else { return $this-&gt;isError( $commit ); } } else { return $this-&gt;isError( $findReq ); } unset( $result, $commit, $record, $findReq ); return false; } /** * Inserts a record into the layout * * @author RichardC * @since 1.0 * * @version 1.0 * * @param string $layout * @param array $arrFields * * @return bool */ public function insert( $layout, $arrFields ) { $blOut = false; if ( ( $layout == '' ) || ( !is_array( $arrFields ) ) ) { return false; } // Auto-Sanitize the input data foreach ( $arrFields as $field =&gt; $value ) { $fields[$this-&gt;fm_escape_string( $field )] = $this-&gt;fm_escape_string( $value ); } $addCmd = $this-&gt;fm-&gt;newAddCommand( $this-&gt;fm_escape_string( $layout ), $fields ); $result = $addCmd-&gt;execute(); if ( $this-&gt;isError( $result ) === 0 ) { $blOut = true; } else { return $this-&gt;isError( $result ); } unset( $addCmd, $result ); return $blOut; } /** * Gets the layout names within a Database * * @author RichardC * @since 1.0 * * @version 1.0 * * @return array */ public function get_layout_names() { return $this-&gt;fm-&gt;listLayouts(); } /** * Updates a set of fields on a layout where the clauses match * * @author RichardC * @since 1.4 * * @version 1.0 * * @param string $layout * @param array $arrFields * @param array $arrSearchCriteria * * @return bool */ public function update( $layout, $arrFields, $arrSearchCriteria ){ //Loop through the parameters and check they are set and not empty foreach( func_get_args() as $arg ){ if( ( $arg == '' ) || ( empty( $arg ) ) ){ return false; } } $findReq = $this-&gt;fm-&gt;newFindCommand( $layout ); foreach ( $arrSearchCriteria as $field =&gt; $value ) { $findReq-&gt;addFindCriterion( $this-&gt;fm_escape_string( $field ), $this-&gt;fm_escape_string( $value ) ); } //Perform the find $result = $findReq-&gt;execute(); if ( $this-&gt;isError( $result ) !== 0 ) { return $this-&gt;isError( $result ); } $records = $result-&gt;getRecords(); //Loop through the found records foreach ( $records as $record ) { //Loop through the fields given in the argument and set the fields with the values foreach ( $arrFields as $f =&gt; $v ) { $record-&gt;setField( $this-&gt;fm_escape_string( $f ), $this-&gt;fm_escape_string( $v ) ); } //Commit the setFields $commit = $record-&gt;commit(); if ( $this-&gt;isError( $commit ) !== 0 ) { return $this-&gt;isError( $commit ); } } //Housekeeping unset( $result, $commit, $record, $findReq ); return true; } /** * Alias of 'select' * * @author RichardC * @since 1.0 * * @version 1.0 * * @param string $layout * @param array $arrSearchCriteria * * @return array */ public function find( $layout, $arrSearchCriteria ) { return $this-&gt;select( $layout, $arrSearchCriteria ); } /** * Runs a script on the layout * * @author RichardC * @since 1.0 * * @version 1.0.2 * * @param string $layout * @param string $scriptName * @param array $params (optional) * * @return bool */ public function runScript( $layout, $scriptName, $params = array() ) { if ( ( empty( $layout ) ) || ( empty( $scriptName ) ) ) { return false; } return ( $this-&gt;fm-&gt;newPerformScriptCommand( $layout, $scriptName, $params ) ? true : false ); } /** * Get the ID of the last updated/inserted field * * @author RichardC * @since 1.2 * * @version 1.0 * * @return int */ public function getLastID() { } /** * Deletes a record from the table/layout with the given record ID * * @author RichardC * @since 1.2.0 * * @version 1.0.2 * * @return bool */ public function deleteRecordByID( $layout, $iRecordID ) { $delete = $this-&gt;fm-&gt;newDeleteCommand( $layout, $iRecordID ); $delResult = $delete-&gt;execute(); if( $this-&gt;isError( $delResult ) ){ return $this-&gt;isError( $delResult ); } unset( $delete, $delResult, $layout, $iRecordID ); return true; } /** * Deletes a record where the search criteria matches * * @author RichardC * @since 1.4.0 * * @version 1.0.0 * * @param string $layout * @param array $arrSearchCriteria * * @return int The amount of records deleted || errorCode */ public function delete( $layout, $arrSearchCriteria ){ if( empty( $layout ) || empty( $arrSearchCriteria ) ){ return 0; } //Performs the search $search = $this-&gt;select( $layout, $arrSearchCriteria ); if( empty( $search ) ){ return 0; } //Checks for an error if( $this-&gt;isError( $search ) !== 0 ){ return $this-&gt;isError( $search ); } $i = 0; foreach( $search as $records ){ $delete = $this-&gt;deleteRecordByID( $layout, $records['rec_id'] ); // Errors return as strings so thats why the check is to make sure its an integer if( !is_int( $delete ) ){ return $delete; //replace $delete with 0; after testing } $i++; } return $i; } /** * Gets the ID of the record in the last Select * * @author RichardC * @since 1.0 * * @version 1.0 * * @return int */ public function getRecordId() { return $this-&gt;lastObj-&gt;getRecordId(); } /** * Escapes a string manually * * @author RichardC * @since 1.0 * * @version 1.0 * * @param string $input * * @return string */ public function fm_escape_string( $input ) { if ( is_array( $input ) ) { return array_map( __method__, $input ); } if ( !empty( $input ) &amp;&amp; is_string( $input ) ) { return str_replace( array( '\\', '/', "\0", "\n", "\r", "'", '"', "\x1a", '&lt;', '&gt;', '%00' ), array( '\\\\', '\/', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z', '\&lt;\\/', '\\/&gt;', '' ), $input ); } } } ?&gt; </code></pre> <p>The format is nicer in the IDE, it got a bit messed up after being pasted, but please let me know what you think.</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:46:27.300", "Id": "15220", "Score": "0", "body": "Feel free to read about [What makes a god question](http://meta.codereview.stackexchange.com/questions/75/what-makes-a-good-question) on meta. A link to the previous question and an explanation of what the code does would help a lot. By the way, saying \"I won't bother correcting my indentation\" makes me want to say \"I won't bother reviewing you code\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T13:49:37.463", "Id": "15228", "Score": "0", "body": "Thanks for your comment. Fixed the issues you were talking about. Also linked to the new question." } ]
[ { "body": "<p>Did you consider making this a REST API? Read more about <a href=\"http://broadcast.oreilly.com/2011/06/the-good-the-bad-the-ugly-of-rest-apis.html\" rel=\"nofollow\">The Good, the Bad, and the Ugly of REST APIs</a> and <a href=\"http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven\" rel=\"nofollow\">REST APIs must be hypertext-driven</a> from the creator of REST (this is one is a bit special, no need to follow it).</p>\n\n<p>Aslo try explaning how your API is better. Perhaps that's obvious, but it would still be good to explain it a few points for someone just stopping by and wondering if he should use it or not.</p>\n\n<p>Anyway, here are my observations. Feel free to discard them whenever you don't agree. I'd be glad to discuss in the comments:</p>\n\n<ol>\n<li>Your indentation is a bit funky, but at list seems consistent, so that's a good point.</li>\n<li>The ordering of the methods is important, especially when the reader has no IDE (and I think most PHP developers don't use IDEs), and especially for APIs that are intended to be used by third-party developers. Whenever your users will have errors, they will look at your code, so don't confuse them about internals such as <code>doChecks</code> or <code>debug</code>. (I don't even know what <code>debug</code> does right now.)\n<ol>\n<li>Put protected functions last.</li>\n<li>Group public functions by \"task\".</li>\n<li>Try to put functions with no dependencies before, they will help understand the rest. (If the documentation for function X says \"similar to Y\", then Y should probably be placed before X. Same remark when X calls Y).</li>\n</ol></li>\n<li><code>isError</code> should return a boolean</li>\n<li><p>The following code has unneeded parentheses. This is defensive programming, and I don't think it's good practice. If $arrSearchCriteria is not an array, you should fail hard, and not let this go unnoticed, since it will probably happen only during development.</p>\n\n<pre><code>if ( ( !is_array( $arrSearchCriteria ) ) ) {\n return false;\n}\n</code></pre></li>\n<li><p>I prefer handling error cases first, even more so when they are really short. It helps knowing that the <code>else</code> is the normal case. When putting the error condition last, you can not see it and have to remember \"maybe there's something else\", which is cumbersome. For example:</p>\n\n<pre><code>if ( $this-&gt;isError( $results ) === FALSE ) {\n $arrOut['errorCode'] = $this-&gt;isError( $results );\n} else {\n // normal stuff.\n}\n</code></pre>\n\n<p>(And keep in mind the \"Flattening Arrow Code\" comment from palacsint on your earlier question. :)</p></li>\n<li><code>if ( isset( $records ) &amp;&amp; !empty( $records ) ) {</code> same comment than 4. You have other occurrences of this issue, I won't list them all.</li>\n<li><code>// Housekeeping</code> : strive for meaningful comments. :)</li>\n<li>What is <code>$blOut</code>?</li>\n<li><p>Is this useful or confusing? Try adopting a convention for your names, to allow users to easily guess them. Changing names arbitrarily is not nice. If you want to code_like_this, at least use <code>list_layouts</code>.</p>\n\n<pre><code>public function get_layout_names() {\n return $this-&gt;fm-&gt;listLayouts();\n}\n</code></pre></li>\n<li><code>public function getLastID() { }</code> Oops?</li>\n<li><code>@return int The amount of records deleted || errorCode</code> Use exceptions!</li>\n<li>What makes your string escaping function special? Why not used a PHP function? Does your function has bugs or flaws?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:20:50.303", "Id": "15256", "Score": "0", "body": "Fantastic answer, thanks. #4/6 - I agree, I obviously didn't proof read my code enough to notice that. #7 - I will change this; #8 - Strange you should mention that, it was a coding standard that I got from my previous company and it is the boolean return variable but I know a lot of other developers hate it; #10 - Still not finished yet, it is still a work in progress as you can see. #12 - The only reason I use that is because its not using MySQL so I cannot use mysql_real_escape_string() but could use addslashes, htmlentities etc (Point taken)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:22:59.470", "Id": "15257", "Score": "0", "body": "I do not like the \"Flattening Arrow Code\", in my opinion it makes it more difficult to read, but that is just a personal opinion.\n\nAs for making this a RESTful API, I don't know too much about REST to start but I will look into it as I do love the idea of REST as I say I just don't know where to begin. Thanks again for all of your suggestions, it's much appreciated!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T17:23:36.760", "Id": "15258", "Score": "0", "body": "I will give you my bounty btw, but I have to wait 18 hours to do so :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T16:39:32.360", "Id": "9648", "ParentId": "9223", "Score": "2" } } ]
{ "AcceptedAnswerId": "9648", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T11:26:44.593", "Id": "9223", "Score": "1", "Tags": [ "php", "object-oriented", "api" ], "Title": "FileMaker PHP API Interface v1.6.3" }
9223
<p><img src="https://i.stack.imgur.com/4nE02.png" alt="VBA Image"></p> <p>Visual Basic for Applications (VBA) is an event-driven programming language first introduced by Microsoft in 1993 designed to give Excel 5.0 a more robust object-oriented language for writing macros and automating the use of Excel. The language and its runtime quickly matured and began being used in products beyond Microsoft Office applications. </p> <p>The last full version, VBA 6, was shipped in 1998 and includes a myriad of licensed hosts, among them: Office 2000 - 2010, AutoCAD, PI Processbook, and the stand-alone Visual Basic 6.0. VBA 6 code will run equally well on any host, though the underlying objects native to each host will vary. Though still built into Microsoft Office applications, VBA ceased to be an integral of part of Microsoft's development platform when Visual Basic .NET shipped with the first version of the .NET framework in 2002.</p> <p>VBA has only been slightly updated since, only including new features to allow it to remain compatible with x64 versions of Windows and Office. VBA 7 was released in 2010 to address the new 64-bit version of Microsoft Office which shipped in 2010. There are several important changes made to VBA 7 that make it different from VBA 6, namely compatibility with both 32 and 64-bit versions of Office. Applications using VBA 7 must address both backwards compabitility and 64-bit-safe issues.</p> <p>It was removed from Office for Mac 2008, however Microsoft returned VBA to Office 2011. Microsoft has continually been questioned about whether or not VBA will be removed altogether from Office and has repeatedly replied "no".</p> <p>VBA inherits much of its syntax from the BASIC programming language, where language features tend to be explicitly expressed in words (e.g. <code>If ... Then ... End If</code>, <code>Function ... End Function</code>). It also has many object-oriented features, such as classes and interfaces, and even has some dynamic features, such as <code>Variant</code>. Below is a simple subroutine which generates a message box and prints a message to the <em>Immediate</em> window:</p> <pre><code>Public Sub HelloWorld() Dim message As String message = "Hello World" MsgBox message Debug.Print "I just made a message box that says """ &amp; message &amp; """!" End Sub </code></pre> <p><strong>Frequently Asked Questions</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/993300/difference-between-visual-basic-and-vba">Difference between Visual Basic and VBA</a></li> <li><a href="https://stackoverflow.com/questions/1139321/how-do-i-force-vba-access-to-require-variables-to-be-defined">How do I force VBA/Access to require variables to be defined</a></li> <li><a href="https://stackoverflow.com/questions/158633/how-can-i-send-an-http-post-request-to-a-server-from-excel-using-vba">How can I send an HTTP Post request to a server from Excel using VBA?</a></li> <li><a href="https://stackoverflow.com/questions/1802120/building-sql-strings-in-access-vba">Build SQL strings in Access/VBA</a></li> <li><a href="https://stackoverflow.com/questions/3072356/what-are-the-differences-between-vba-6-0-and-vba-7-0">Differences between VBA 6 and VBA 7</a></li> </ul> <p><strong>Beginner Resources</strong></p> <ul> <li><a href="http://www.ehow.com/how_5659528_started-excel-vba.html" rel="nofollow noreferrer">How to Get Started With Excel VBA</a> at <a href="http://www.ehow.com/how_5659528_started-excel-vba.html" rel="nofollow noreferrer">eHow</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ee814735.aspx" rel="nofollow noreferrer">Getting Started with VBA in Office 2010</a></li> </ul> <p><strong>Additional Reading</strong></p> <ul> <li><a href="https://rads.stackoverflow.com/amzn/click/0782129781" rel="nofollow noreferrer"><em>VBA Developer's Handbook, 2nd Edition</em></a>, by Getz &amp; Gilbert</li> <li><a href="https://rads.stackoverflow.com/amzn/click/0321508793" rel="nofollow noreferrer"><em>Professional Excel Development, 2nd Edition</em></a></li> </ul> <p><strong>General VBA Information and History</strong></p> <ul> <li><a href="https://en.wikipedia.org/wiki/Visual_Basic_for_Applications" rel="nofollow noreferrer">Visual Basic for Applications</a> on <a href="https://www.wikipedia.org" rel="nofollow noreferrer">Wikipedia</a></li> <li><a href="http://www.joelonsoftware.com/items/2007/04/25.html" rel="nofollow noreferrer">VBA for Macintosh goes away</a> at <a href="http://www.joelonsoftware.com" rel="nofollow noreferrer">Joel on Software</a></li> <li><a href="http://www.joelonsoftware.com/items/2006/06/16.html" rel="nofollow noreferrer">My First BilLG Review</a> at <a href="http://www.joelonsoftware.com" rel="nofollow noreferrer">Joel on Software</a></li> </ul> <hr> <h2>"not responding" isn't <em>broken code</em></h2> <p>If you're reviewing a VBA question, please don't downvote and/or vote to close VBA questions on the basis of "broken code" or "not working as intended" when the OP mentions the host application going unresponsive. Most VBA hosts run VBA code on the main/UI thread, so it's perfectly normal that a long-running VBA macro makes the host application's main window caption say "(not responding)". In that state, the VBA code is running, and the host application is no longer handling Windows messages; clicking on the main window causes the screen to "white-out", which an inexperienced VBA coder may easily misinterpret as "Excel freezing", when in reality Excel is just busy running the OP's code. Responsiveness resumes when the code completes.</p> <p>If you're asking a VBA question, please avoid wording this unresponsive state in such a way that could be interpreted as a bug in your code: avoid terms like "freezes" or "crashes" in your post (crashing code is off-topic) - if Excel is just not reaponding and your code eventually completes, your question is perfectly on-topic and probably just needs performance tuning... And you're on the right site for this.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-02-21T13:28:41.437", "Id": "9225", "Score": "0", "Tags": null, "Title": null }
9225
Visual Basic for Applications (VBA) is an event-driven programming language first introduced by Microsoft in 1993 to give Excel 5.0 a more robust object-oriented language for writing macros and automating the use of Excel. It is now used for the entire Office suite and over 200 non-Office hosts.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-02-21T13:28:41.437", "Id": "9226", "Score": "0", "Tags": null, "Title": null }
9226
<p>I am having a <a href="http://pastie.org/3426970" rel="nofollow">challenge problem</a>. I have solved the problem but my solution is slow.</p> <p>The problem is basically the distribution of scores among players. <em>e.g</em> for a 2 player game the possible scorecards combination is 2 because either player can win \$\{0,1\}\$ or \$\{1,0\}\$ while for a 3 player game the possible scorecards combination is 7: \$\{1,1,1\}\$, \$\{0,1,2\}\$, \$\{0,2,1\}\$, \$\{1,0,2\}\$, \$\{1,2,0\}\$, \$\{2,0,1\}\$, \$\{2,1,0\}\$ as a single player can win maximum by 2 other players and minimum by no one.</p> <p>As I can guess the reason my code is slow is because I am trying to find all valid scorecards and displaying the number.</p> <ol> <li><p>In my first attempt I tried to find all possible combination of scorecards and storing them in a vector, then removing the invalid combinations. This approach was slow.</p></li> <li><p>In my second attempt I applied some checks such as that in a series no 2 players can have a score of \$0\$ <em>i.e</em> \$\{0,0,...\}\$ etc cause it is logically not possible. Because if a player doesn't win from any other player then all other player must have won from that particular player so every other player will have at least 1 win. It reduced my calculations by almost 50-60% but it is still slow.</p></li> </ol> <p>I think my code/logic can be improved: instead of finding all valid combinations, I may find the number of valid combinations with some kind of formula.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;numeric&gt; using namespace std; bool hasElement(vector&lt;int&gt;&amp; arr, const int&amp; element) { vector&lt;int&gt;::iterator found = find(arr.begin(), arr.end(), element); if (found != arr.end()) return true; return false; } int sumElements(const vector&lt;int&gt;&amp; arr) { int s = accumulate(arr.begin(), arr.end(), 0); return s; } bool isPossible(vector&lt;int&gt;&amp; arr, const int&amp; sum, const int&amp; nMax) { if (hasElement(arr, -1) || *max_element(arr.begin(), arr.end()) &gt; nMax) return false; int s = sumElements(arr); if (s == sum) return true; return false; } int rangeSum (int start, int end) { int sum = 0; for (int i = start; i &lt; end; i++) sum += i; return sum; } int size = 0; int maxSum; int n; int maxZero; int maxMax; int maxAllowed; int range; vector&lt;int&gt; tempVec; vector&lt;vector&lt;int&gt;&gt; mainVec; void printTempVec() { for(int i = 0; i &lt; tempVec.size(); i++) { if (tempVec[i] &gt;= 0) cout &lt;&lt; tempVec[i] &lt;&lt; " "; else cout &lt;&lt; -1 &lt;&lt; " "; } cout &lt;&lt; endl; } int summation(const int&amp; places, const int&amp; max) { int s = 0; for (int i = 0; i &lt; places; i++) { } return s; } bool isValid(vector&lt;int&gt;&amp; arr, const int&amp; nMax) { int sz = 0; int sm = 0; for (int i = 0; i &lt; arr.size(); i++) { if (arr[i] == nMax) sm++; if (sm &gt; 1) return false; } return true; } void findNum(int i, int max, int rSum, int mZero, int mMax) { max = max &gt; maxAllowed ? maxAllowed : max; if (max == 0) mZero++; if (mZero &gt; 1) return; if (max == -1) return; tempVec[i] = max; int tempSum = rSum - max; max--; if(i != n) { findNum(i + 1, tempSum, tempSum, mZero, mMax); findNum(i, max, rSum, mZero, mMax); } else if(i == n) { if (isPossible(tempVec, range, maxAllowed) &amp;&amp; isValid(tempVec, maxAllowed)) mainVec.push_back(tempVec); else printTempVec(); maxSum++; } } int missing(const vector&lt;int&gt;&amp; temp) { int s = 0; for (int i = 0; i &lt; temp.size(); i++) { if (temp[i] == -1) s++; } return s; } int remainingSum(const vector&lt;int&gt;&amp; temp) { int s = rangeSum(0, temp.size()); for (int i = 0; i &lt; temp.size(); i++) { if (temp[i] != -1) s -= temp[i]; } return s; } int main() { vector&lt;vector&lt;int&gt;&gt; mainArray; vector&lt;int&gt;temp; for (int i = 0; i &lt; 3; i++) temp.push_back(-1); mainArray.push_back(temp); for (int i = 0; i &lt; mainArray.size(); i++) { size = mainArray[i].size(); tempVec.clear(); tempVec.resize(size); maxZero = 0; maxSum = 0; maxMax = 0; int rSum = remainingSum(mainArray[i]); int tSum = rangeSum(0, mainArray[i].size()); range = tSum; n = missing(mainArray[i]) - 1; maxAllowed = mainArray[i].size() - 1; if (isPossible(mainArray[i], tSum, maxAllowed)) maxSum = 1; else findNum(0, rSum, rSum, 0, maxMax); cout &lt;&lt; maxSum &lt;&lt; endl; cout &lt;&lt; mainVec.size() &lt;&lt; endl; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:04:42.243", "Id": "14443", "Score": "1", "body": "a few notes on your code: 1. There's no reason to pass an integer as a const-ref. Just pass it by value. 2. Instead of `if(x==y) return true; return false;` you simply can do `return x==y`. 3. Instead of `int s = accumulate(…); return s;` simply do `return accumulate(…)`. 4. Try not to use global variables; 5. In `summation()` is an loop without a body. Therefore that function doesn't have an effect. 6. `vector<vector<int>>` is only possible in C++0x. Are you allowed to use it? 7. A vector is not an array. Why do you call your vectors `arr`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T14:30:43.997", "Id": "14450", "Score": "0", "body": "@Polybos Thanks for your comment. I improved the code as you suggested. I used global variables cause of the recursive function `findSum(...)` because it requires same values for all calls. Others don't have any effect on the speed though. Will really appreciate if you can provide more insight on improving the logic for speeding it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T21:37:07.940", "Id": "14476", "Score": "0", "body": "Can you describe why it is to slow and how fast it is supposed to be? And maybe explain the problem a little so that everybody understands what this is all about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T14:42:54.850", "Id": "14536", "Score": "0", "body": "@bamboon Thanks for your comment. I have updated the question." } ]
[ { "body": "<p>Some more comments. </p>\n\n<ol>\n<li><p>The function <code>rangeSum()</code> can be optimized to:</p>\n\n<pre><code>int rangeSum(int start, int end)\n{\n return start*(start-1)/2 + end*(end-1)/2 - 2;\n}\n</code></pre>\n\n<p>which is much better since it's <code>O(1)</code> and not <code>O(n)</code>. </p></li>\n<li><p>The function <code>hasElement()</code> can be reimplemented to:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline bool hasElement(const vector&lt;T&gt;&amp; vec, T elem)\n{\n return std::find(vec.begin(), vec.end(), elem) != vec.end();\n}\n</code></pre></li>\n<li><p>Assuming you can use C++0x, <code>missing()</code> can be reimplemented to:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline std::size_t missing(const std::vector&lt;T&gt;&amp; tmp)\n{\n return std::count_if(tmp.begin(), tmp.end(), [](T elem) {\n return elem == -1;\n });\n}\n</code></pre></li>\n<li><p>The variables <code>maxMax</code> and <code>size</code> aren't used globally. Just declare them locally. </p></li>\n<li><p>You might think of using a functor <code>FindNum</code> – something like:</p>\n\n<pre><code>struct FindNum\n{\n void operator()(int i, int max, int rSum, int mZero, int mMax)\n {\n /* … */\n }\n\n int maxSum, n, maxAllowed, range;\n std::vector&lt;int&gt; tempVec;\n std::vector&lt;std::vector&lt;int&gt;&gt; mainVec;\n};\n</code></pre>\n\n<p>You really shouldn't use global variables. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T19:16:14.593", "Id": "14473", "Score": "0", "body": "Really appreciate your help. These changes have been made but there is no change in the performance. Major work is being done in FindNum. I want to improve FindNum so that it can run efficiently." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T16:24:34.330", "Id": "9234", "ParentId": "9227", "Score": "6" } }, { "body": "<ul>\n<li><p>The names <code>isPossible()</code> and <code>missing()</code> are not very good at all. What could be possible? What could be missing? Use accurate names; don't leave the reader guessing.</p></li>\n<li><p><code>summation()</code> doesn't appear to be doing anything. It initializes <code>s</code> to <code>0</code>, has a loop that does nothing with <code>s</code>, then returns it. Essentially, it will always return <code>0</code>. You could just get rid of this function if you aren't needing to fill in the loop body anymore.</p></li>\n<li><p>Why's all this hanging around in global (and in between other functions)?</p>\n\n<blockquote>\n<pre><code>int size = 0;\n\nint maxSum;\nint n;\nint maxZero;\nint maxMax;\nint maxAllowed;\nint range;\n\nvector&lt;int&gt; tempVec;\nvector&lt;vector&lt;int&gt;&gt; mainVec;\n</code></pre>\n</blockquote>\n\n<p>It appears that you're using all of this in <code>main()</code>, so it should just be declared or initialized there. Avoid global variables as they could introduce unexpected bugs anywhere in the code.</p></li>\n<li><p>This can be reduced quite a bit:</p>\n\n<blockquote>\n<pre><code>vector&lt;vector&lt;int&gt;&gt; mainVec;\n\n vector&lt;int&gt;temp;\n for (int i = 0; i &lt; 3; i++)\n temp.push_back(-1);\n mainVec.push_back(temp);\n</code></pre>\n</blockquote>\n\n<p>You can initialize <code>temp</code> and eliminate the loop:</p>\n\n<pre><code>std::vector&lt;int&gt; temp(3, -1); // elems: -1, -1, -1\nvector&lt;vector&lt;int&gt;&gt; mainVec(temp);\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-04T23:07:01.290", "Id": "59062", "ParentId": "9227", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T13:43:14.087", "Id": "9227", "Score": "5", "Tags": [ "c++", "optimization", "algorithm", "c++11", "programming-challenge" ], "Title": "Count Scorecards challenge problem related to partition number theory" }
9227
<p>For a specific test-scenario I wanted:</p> <ol> <li>avoid accessing the file system through pythons builtin <code>open</code>-function</li> <li>don't want to use 3rd party libraries like <a href="http://www.voidspace.org.uk/python/mock/" rel="nofollow">Michael Foord's Mock</a> library</li> </ol> <p>I would like to hear your opinion, if this seems like a valuable solution, or if there are</p> <ul> <li>similar solutions with less lines of code</li> <li>grave errors or caveats in the provided solution</li> </ul> <p></p> <pre><code>from io import StringIO class MockFile(StringIO): """Wraps StringIO, because of python 2.6: clumsy name-property reset""" name = None #overwrite TextIOWrapper-property - part 1/2 _vfs = {} #virtual File-System enables to "re-read" already written MockFiles def __init__(self, name, mode = 'r', buffer_ = None): self.name = name #overwrite TextIOWrapper-property - part 2/2 if self._vfs.has_key(name): buffer_ = self._vfs[name] super(MockFile, self).__init__(unicode(buffer_)) __enter__ = lambda self: self __exit__ = lambda self, exc_type, exc_value, traceback: None read = lambda self, size = None: super(Mockfile, self).read(size) def write(self, data): super(MockFile, self).write(data) self._vfs[self.name] = self.getvalue() def replace_builtin(builtinname, replacementobj): import __builtin__ builtin_func = getattr(__builtin__, builtinname) setattr(__builtin__, builtinname, replacementobj) def decorator_factory(func): def decorator(*args, **kwarg): return func(*args, **kwarg) #attach the original name and function to the decorator: decorator.replaced_builtin = (builtinname, builtin_func) return decorator return decorator_factory </code></pre>
[]
[ { "body": "<pre><code>from io import StringIO\n\nclass MockFile(StringIO):\n \"\"\"Wraps StringIO, because of python 2.6: clumsy name-property reset\"\"\"\n\n name = None #overwrite TextIOWrapper-property - part 1/2\n _vfs = {} #virtual File-System enables to \"re-read\" already written MockFiles\n</code></pre>\n\n<p>Storing files here causes them to be persistent between unit tests.</p>\n\n<pre><code> def __init__(self, name, mode = 'r', buffer_ = None):\n self.name = name #overwrite TextIOWrapper-property - part 2/2\n if self._vfs.has_key(name):\n buffer_ = self._vfs[name]\n</code></pre>\n\n<p>I'd use <code>buffer_ = self._vfs.get(name, buffer_)</code></p>\n\n<pre><code> super(MockFile, self).__init__(unicode(buffer_))\n</code></pre>\n\n<p>What <code>_buffer</code> is <code>None</code> at this point? Won't that have strange effects?</p>\n\n<pre><code> __enter__ = lambda self: self\n __exit__ = lambda self, exc_type, exc_value, traceback: None\n read = lambda self, size = None: super(Mockfile, self).read(size)\n</code></pre>\n\n<p>None of these lines of code do anything. They assign to local variables which are thrown away at the end of the function.</p>\n\n<pre><code> def write(self, data):\n super(MockFile, self).write(data)\n self._vfs[self.name] = self.getvalue()\n</code></pre>\n\n<p>I wouldn't update self._vfs for every write. I'd put that in a close function. That way your tests fail if you forget to invoke close. </p>\n\n<pre><code>def replace_builtin(builtinname, replacementobj):\n import __builtin__\n builtin_func = getattr(__builtin__, builtinname)\n setattr(__builtin__, builtinname, replacementobj)\n\n def decorator_factory(func):\n def decorator(*args, **kwarg):\n return func(*args, **kwarg)\n\n #attach the original name and function to the decorator:\n decorator.replaced_builtin = (builtinname, builtin_func)\n return decorator\n return decorator_factory\n</code></pre>\n\n<p>I'm having real trouble figuring out how you would use this function. </p>\n\n<p>UPDATE:</p>\n\n<pre><code>from io import StringIO\n\nclass MockFile(StringIO):\n \"\"\"Wraps StringIO\"\"\"\n _vfs = {} #virtual File-System\n name = None #overwrite TextIOWrapper-property - part 1/2\n def __init__(self, name, mode = 'r', buffer_ = ''):\n self.name = name #overwrite TextIOWrapper-property - part 2/2\n if self._vfs.has_key(name):\n buffer_ = self._vfs.get(name, buffer_)\n</code></pre>\n\n<p>No need for the if. The second parameter to <code>get</code> is a default. Using get replaces checking for the key.</p>\n\n<pre><code> super(MockFile, self).__init__(unicode(buffer_))\n\n def read(self, size = None):\n return super(MockFile, self).read(size)\n\n def write(self, data):\n super(MockFile, self).write(data)\n</code></pre>\n\n<p>These functions just call the superclass which happens anyways. So why include them?</p>\n\n<pre><code> def close(self):\n self._vfs[self.name] = self.getvalue()\n super(MockFile, self).close()\n\ndef replace_builtin(builtinname, replacementobj):\n \"\"\"makes it possible to mock the built-in functions like open.\n &gt;&gt;&gt; @replace_builtin('open', MockFile)\n &gt;&gt;&gt; def test_whatever(self, *args, **kwargs)\n with open(filename, 'r') as file:\n self.content = file_.read()\n \"\"\"\n import __builtin__\n builtin_func = getattr(__builtin__, builtinname)\n\n def decorator_factory(func):\n def decorator(*args, **kwarg):\n setattr(__builtin__, builtinname, replacementobj)\n result = func(*args, **kwarg)\n</code></pre>\n\n<p>Bad things will happen if an exception is thrown by the function. I'd use a try/finally block here.</p>\n\n<pre><code> setattr(__builtin__, builtinname, builtin_func)\n return result\n #attach the original name and function to the decorator:\n decorator.replaced_builtin = (builtinname, builtin_func)\n return decorator\n return decorator_factory\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:57:26.350", "Id": "521402", "Score": "0", "body": "Have there been updates to this in the past 9+ years? I am trying to do a similar thing today. do I just copy the blocks after the \"Update\" above and put them together?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T15:38:57.273", "Id": "9231", "ParentId": "9228", "Score": "4" } } ]
{ "AcceptedAnswerId": "9231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T13:50:39.647", "Id": "9228", "Score": "4", "Tags": [ "python", "unit-testing", "reinventing-the-wheel" ], "Title": "Monkeypatching builtin open and File Mock-Up for unit testing" }
9228