body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
---|---|---|---|---|
<p>As an exercise, I have implemented a circular bounded queue using arrays as the base data structure. I'd appreciate it if someone can review it for me.</p>
<pre><code> class BoundedQueue<T> {
T[] que;
int head; // remove from head
int tail; // insert at tail
public BoundedQueue(int quesize)
{
head = tail = -1;
que = new T[quesize];
}
public void enqueue(T elem) // if next index to tail == head => Q is FULL
{
int newIndex = nextIndex(tail);
if ( newIndex == head)
throw new BoundedQueueException(Full);
tail = newIndex;
que[newIndex] = elem;
if (head == -1)
head = 0;
}
public T dequeue() // After removing from head, if that was the only element in Q
// Mark Q to be empty by setting head and tail to -1
{
if (head == -1)
throw new BoundedQueueException(Empty);
T elem = que[head];
que[head] = default(T);
if (head == tail)
{
head = tail = -1;
}
else
{
head = nextIndex(head);
}
return elem;
}
private int nextIndex(int index)
{
return (index + 1) % que.Length;
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Exception handling should be added\nto the constructor, handling a negative\n<code>quesize</code>. Or take a look at Code\nContracts.</li>\n<li>Instead of initializing <code>head</code> and\n<code>tail</code> to <code>-1</code>, you could use\n<a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\">nullable ints</a>, and adjust your\nlogic so it doesn't rely on the\nmagic number <code>-1</code>.</li>\n<li>Implement some missing features.\n(might have been left out\nintentionally): implement <code>ICollection</code> and <code>IEnumerable</code>, <code>isFull()</code>.</li>\n<li>A minor point would be naming conventions. In C# method names normally start with a capital letter.</li>\n<li>Be aware that this is not a thread safe class.</li>\n<li>Add some comments, this code isn't that self-documenting. Or, where possible, make it self-documenting, e.g. <code>if ( head == tail )</code> could be <code>if ( Count == 0 )</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T01:09:37.837",
"Id": "2142",
"Score": "0",
"body": "I will work on your suggestions. This problem was more about me getting circular queues implemented. But, I'll definitely try to integrate the recommendations."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T01:10:00.193",
"Id": "2143",
"Score": "0",
"body": "Why is it not thread-safe ? How can I make it thread safe ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T01:15:38.957",
"Id": "2144",
"Score": "0",
"body": "@brainydexter: That's [a whole different subject](http://msdn.microsoft.com/en-us/library/573ths2x%28v=vs.71%29.aspx). I'm not saying you should make it thread safe. I'm only saying you should be aware it's not. E.g. comment it in the summary of the class. The caller can also do thread safe calls to the queue in a multithreaded environment. If you don't need it, [don't worry about it for now](http://stackoverflow.com/q/164088/590790)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T00:44:02.933",
"Id": "1217",
"ParentId": "1216",
"Score": "15"
}
},
{
"body": "<p>A few minor comments.</p>\n\n<ol>\n<li>C# typically uses CamelCase for method names.</li>\n<li>A Peek() method or a Count property could be useful.</li>\n<li>I would prefer to use an if statement in the NextIndex method instead of the modulus operator.</li>\n</ol>\n\n<pre>\n index++\n if (index >= que.Length)\n index = 0;\n return index;\n</pre>\n\n<p>I am not sure which would perform faster, I suspect the if, but I think that the if more clearly communicates what you are trying to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T00:50:46.217",
"Id": "2138",
"Score": "0",
"body": "I was doubting to mention the modulo. The function already describes what it does, and somehow, when you use it often, it is readable. Never thought about performance however. :O Would be interesting to do some benchmarks for that. Not that performance would be an issue :) just out of curiosity."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T05:05:53.320",
"Id": "2154",
"Score": "2",
"body": "Modulo is fine.. It's more natural in these cases, everyone uses it to deal with overflowing/circularity, so it's pretty natural for any programmer who reads it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T00:44:44.877",
"Id": "1218",
"ParentId": "1216",
"Score": "3"
}
},
{
"body": "<ol>\n<li>Use XML-doc instead of comments when describing public method or properties. Especially for a class that is intended to be used by many people with different purposes (generic collections fall into that category)</li>\n<li>Naming. Methods really should be CamelCase and you usually want to use verbs, like <code>GetNextIndex</code></li>\n<li>I would add a <code>Count</code> method or property for external and internal use (it's useful for the caller and it allows to rewrite some parts of the code more semantic way)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T05:14:08.197",
"Id": "1226",
"ParentId": "1216",
"Score": "4"
}
},
{
"body": "<p>It's not that clear why do you want to implement such data structure as <code>circular queue</code>. Externally the only it's difference from regular <code>queue</code> is that it has maximum capacity. But if the only point to implement it was to have a max capacity then I would use <code>LinkedList</code> or even regular <code>Queue</code> internally. Code will be more readable if you will get rid of these index games. Sample with <code>LinkedList</code>:</p>\n<pre><code>class BoundedQueue<T> {\n\n private readonly LinkedList<T> _internalList = new LinkedList<T>();\n private readonly int _maxQueueSize;\n\n public BoundedQueue(int queueSize)\n {\n if (queueSize < 0) throw new ArgumentException("queueSize");\n _maxQueueSize = queueSize;\n }\n\n public void Enqueue(T elem)\n {\n if (_internalList.Count == _maxQueueSize)\n throw new BoundedQueueException(Full);\n _internalList.AddLast(elem);\n }\n\n public T dequeue()\n {\n if (_internalList.Count == 0)\n throw new BoundedQueueException(Empty);\n\n T elem = _internalList.First.Value;\n _internalList.RemoveFirst();\n return elem;\n }\n}\n</code></pre>\n<p>P.S.: Also consider declaring fields with <code>readonly</code> keyword.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T12:41:41.587",
"Id": "2163",
"Score": "0",
"body": "Very true. I'm guessing it was just an exercise. :) Perhaps one advantage is, when adjusting his code, it could work on any existing array without having to copy all elements to the LinkedList. :) There might also be a small performance gain."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T15:56:02.473",
"Id": "2168",
"Score": "0",
"body": "@Steven Jeuris: What was that bit about copying all the elements, if I were to use a linked list ? (Even if Linked list is used, I don't think elements would be copied. Please correct me, if am wrong)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T16:00:02.423",
"Id": "2169",
"Score": "0",
"body": "@Snowbear: One of the requirements was to have a maximum capacity and array felt like a natural choice to me, since array is usually a fixed size data structure. Also, I could not use any external class, so if I were to use either Linkedlist or a Queue, I'd have to write my own implementation. I'd still be interested to learn why would you use linkedlists over arrays ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T16:02:34.980",
"Id": "2171",
"Score": "0",
"body": "@brianydexter: I mean that your class can easily be adjusted to work on an existing array. (if you ever want to do that anyway ...) This class can too, but then you will have to add all items from the array into the linked list, and the original array won't change along. Just mentioning it, probably not important. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T16:03:26.663",
"Id": "2172",
"Score": "1",
"body": "Also, shouldn't queSize condition be: `quesize <= 0 ` :: throw exception ?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-10T12:08:35.233",
"Id": "1234",
"ParentId": "1216",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1217",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-09T23:21:17.183",
"Id": "1216",
"Score": "14",
"Tags": [
"c#",
"queue",
"circular-list"
],
"Title": "Circular Bounded Queue using C#"
} | 1216 |
<p>This Common Lisp program is an exercise to print an integer and its digits reversed to the screen:</p>
<pre><code>(defun read-number () (format t "Enter a number: ~%") (read))
(defun reverse-string (the-string)
(if (eq (length the-string) 0)
""
(concatenate 'string (reverse-string (subseq the-string 1)) (subseq the-string 0 1))))
(defun reverse-digits (the-number) (reverse-string (write-to-string the-number)))
(let ((the-number (read-number)))
(format t "N->: ~a~%<-N: ~a~%" the-number (reverse-digits the-number)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T02:24:08.913",
"Id": "2149",
"Score": "0",
"body": "Wow, lots of Lisp exercises. Is this for school, or did you just pick it up for the hell of it? :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T06:27:26.617",
"Id": "2155",
"Score": "0",
"body": "Just picked it up for the heck of it :) I've always heard Lisp is a good language to learn."
}
] | [
{
"body": "<p>You're talking about digits and integer, but to me, as an non-lisper, it looks as if you operate on Strings. </p>\n\n<ul>\n<li>I would take the number, modulo 10, print that digit. </li>\n<li>If the rest is > 0 recursively call the function with the (number - digit) / 10. </li>\n</ul>\n\n<p>In most languages with integer-arithmetic you can omit the subtraction, since 37/10 => 3 :==: (37-7)/10 => 3 </p>\n\n<p>In scala it would look like this: </p>\n\n<pre><code>def redigit (n: Int, sofar: Int = 0) : Int = { \n if (n == 0) sofar else \n redigit (n / 10, sofar * 10 + n % 10)}\n\nredigit (123)\n321 \n</code></pre>\n\n<p>It uses default arguments. First tests with DrScheme didn't succeed. Here is what I came up with:</p>\n\n<pre><code>;; redigit : number number -> number\n(define (redigit in sofar)\n (cond [(< in 1) sofar]\n [else (redigit (/ in 10) (+ (* 10 sofar) (modulo in 10)))]) \n)\n\n(redigit 134 0) \n</code></pre>\n\n<p>But the division is precise and doesn't cut off the digits behind the floting point. I get this error: </p>\n\n<blockquote>\n <p>modulo: expects type as 1st\n argument, given: 67/5; other arguments\n were: 10</p>\n</blockquote>\n\n<p>I looked for a function toInt, asInt, floor, round and so on for the term (/ in 10) but I didn't find something useful. Maybe you know it yourself?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T04:08:09.590",
"Id": "2151",
"Score": "0",
"body": "You need to use `quotient` and `remainder`. See my answer. :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T02:42:15.673",
"Id": "1220",
"ParentId": "1219",
"Score": "1"
}
},
{
"body": "<p>This problem is more about numbers than strings, so I felt the need to post a non-string-based solution. I've got my original Scheme version, and a Common Lisp adaptation of same.</p>\n\n<p>Scheme version:</p>\n\n<pre><code>(define (reverse-digits n)\n (let loop ((n n) (r 0))\n (if (zero? n) r\n (loop (quotient n 10) (+ (* r 10) (remainder n 10))))))\n</code></pre>\n\n<p>Common Lisp translation of the Scheme version:</p>\n\n<pre><code>(defun reverse-digits (n)\n (labels ((next (n v)\n (if (zerop n) v\n (multiple-value-bind (q r)\n (truncate n 10)\n (next q (+ (* v 10) r))))))\n (next n 0)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T04:16:22.193",
"Id": "2152",
"Score": "0",
"body": "I meanwhile wrote my own version of `quotient`, `idiv`. `remainder` and `module` seem to be synonyms."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T04:24:27.753",
"Id": "2153",
"Score": "0",
"body": "@user unknown: `remainder` and `modulo` have different behaviour if the dividend is negative. `(remainder -5 3)` => -2, whereas `(modulo -5 3)` => 1."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T07:12:29.713",
"Id": "2156",
"Score": "0",
"body": "Yeah, I didn't test negative values. For such, I would use a wrapper method. `(if (< 0 x) (* -1 (redigit (* -1 x) 0)))`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T15:18:18.550",
"Id": "2166",
"Score": "0",
"body": "+1 - Just keep in mind that TCO isn't guaranteed in CL the way it is in Scheme."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T15:19:30.890",
"Id": "2167",
"Score": "1",
"body": "@Inaimathi: Of course. But how many digits is your number going to have? ;-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T03:58:04.950",
"Id": "1221",
"ParentId": "1219",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1221",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T02:10:39.440",
"Id": "1219",
"Score": "4",
"Tags": [
"strings",
"lisp",
"common-lisp"
],
"Title": "Print an integer and its digits reversed"
} | 1219 |
<p>I need to place a Google map in Colorbox overlay and am wondering if there's a better way to do this. I've just started out with Google's tutorial so there's nothing fancy going on.</p>
<p>Right now I'm hiding the div that Google loads the map into:</p>
<pre><code><div style="width:0; height: 0; overflow: hidden;">
<div id="map_canvas" style="width:600px; height:400px; "></div>
</div>
</code></pre>
<p>Here's the call to Colorbox:</p>
<pre><code>var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$(document).ready(function(){
$("#farm_on_google_maps").colorbox({
inline: true,
width:700,
height:450,
href : '#map_canvas'
});
});
</code></pre>
<p>Even though it works, I wonder if the map could be loaded directly into Colorbox.</p>
| [] | [
{
"body": "<p>If you want to dynamically insert the Google Map, instead of simply linking to an href, you can do as follows:</p>\n\n<p>In your HTML, have the basic outline for the colorbox ready:</p>\n\n<pre><code><div id=\"box\">\n <div class=\"google-map\"></div>\n</div>\n</code></pre>\n\n<p>Then, when you invoke your colorbox, invoke it with an <code>html</code> option:</p>\n\n<pre><code>$(\"#farm_on_google_maps\").colorbox({\n inline: true,\n width:700,\n height:450,\n html : $(\"#box\").html()\n });\n</code></pre>\n\n<p>This will setup your colorbox with the basic HTML structure. We then want to insert the google map dynamically into the colorbox as follows:</p>\n\n<pre><code>var googleMap = $(\"#cboxLoadedContent\").find(\"div.google-map\")[0];\nvar latlng = new google.maps.LatLng(-34.397, 150.644);\nvar myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };\nvar map = new google.maps.Map(googleMap, myOptions);\n</code></pre>\n\n<p>The <code>cboxLoadedContent</code> div is created by the colorbox when it's invoked, so it's simply a matter of grabbing that, and using it to setup the Google Map.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T23:37:32.360",
"Id": "1290",
"ParentId": "1223",
"Score": "4"
}
},
{
"body": "<p>Nothing easier than this:</p>\n\n<pre><code><a href=\"URLTOMAP\" class=\"colorbox\">Map</a>\n\n$(document).ready(function(){\n$(\".colorbox\").colorbox({ rel:'colorbox' });\n});\n</code></pre>\n\n<p>Does exactly what it says on the tin.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-18T00:57:13.277",
"Id": "19715",
"ParentId": "1223",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1290",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T04:22:50.250",
"Id": "1223",
"Score": "6",
"Tags": [
"google-apps-script",
"google-maps"
],
"Title": "Placing a Google map in Colorbox"
} | 1223 |
<p>I have two helper methods that return li for view with the li for current view having id as selected. </p>
<pre><code>def get_li(a)
li = "<li"
li += ' id=selected' if (a[:controller] == params[:controller] && a[:action] == params[:action])
li += ">" + link_to(a[:text], { :controller => a[:controller], :action => a[:action]}) + "</li>"
end
def get_tab_options
if (params[:controller] == 'sessions' || params[:controller] == 'users')
[{:text => "Login", :controller => 'sessions', :action => 'new'},
{:text => "Sign Up", :controller => 'users', :action => 'new'}]
elsif (params[:controller] == 'meetings')
[{:text => "Meetings List", :controller => 'meetings', :action => 'index'},
{:text => "Create Meeting", :controller => 'meetings', :action => 'new'},
{:text => "Running Meetings", :controller => 'meetings', :action => 'monitor'}]
end
end
</code></pre>
<p>And the view file has</p>
<pre><code> %ul
-get_tab_options.each do |a|
= get_li(a)
</code></pre>
<p>How can I write this better?</p>
| [] | [
{
"body": "<p>First of all let's talk about method names:</p>\n\n<p>The <code>get_</code> prefix is usually not used in ruby - you'd just leave it off.</p>\n\n<p>Further the name <code>get_li</code> (or just <code>li</code>) is not very descriptive of what the method does. It tells me that it will produce an <code><li></code>, sure, but it doesn't tell me that the <code><li></code> will contain a link. From the method name I would just assume that this is a general helper method I can use whenever I want a list item. It should probably be called something like <code>list_item_with_link</code> or possibly <code>navigation_entry</code>, assuming that the <code><li><a></code>s produced by this method are meant as entries in a navigation bar/menu.</p>\n\n<p>The name of the argument is also not very descriptive. I assume you called it <code>a</code> because of the <code><a></code> tag, but <code>a</code> does not really contain an <code>a</code> tag, just the information you use to build one. I'd call it something like <code>link</code> instead.</p>\n\n<hr>\n\n<p>Your methods should also be commented. Sure in the case of short methods like this, it's easy enough to tell what it does from looking at the code, but there should still be comments explaining what the method does, when and how it's intended to be used and what the arguments should look like.</p>\n\n<hr>\n\n<p>Now to the actual code: Instead of building the <code>li</code> tag using string concatenation, you should use the <code>content_tag</code> helper instead, which builds HTML-tags containing content, like <code><li></code>.</p>\n\n<p>I also feel that the code would become nicer if the the logic to determine whether a link points to the current page was factored into its own method. I'm sure it could be useful in other places as well.</p>\n\n<hr>\n\n<p>On a general design note, it seems wrong that you're restricting the links to only contain <code>:controller</code> and <code>:action</code>. Maybe you would later like to add a link to an action with a specific parameter. Your current design would not allow that.</p>\n\n<p>For this you could just use your current system and just remove the <code>:text</code> key out of the hash after retrieving it and then passing the rest to <code>link_to</code>. However this would break if you ever have an action to which you want to supply a parameter named <code>text</code>.</p>\n\n<p>So what I would do is the separate the link text from the link location. For example an array where the first element is the link text and the second is the location might work. This way <code>[\"Meetings List\", {:controller => 'meetings', :action => 'index'}]</code>, <code>[\"Meetings List\", {:controller => 'meetings'}]</code> and <code>[\"Meetings List\", {:controller => 'meetings', :action => 'index', :show_only_active => true}]</code> would all be valid links.</p>\n\n<p>Instead of an array, it could be even nicer to use a struct/class. This way you could also put the logic of determining whether the link points to the current page and how to turn the link to HTML into that class.</p>\n\n<hr>\n\n<p>With all those points, my code would probably look like this:</p>\n\n<pre><code># Class to represent links.\n# First argument to new will be the text to be displayed for the link and the second\n# argument will be the location that the link points to as a hash.\nLink = Struct.new(:text, :location) do\n include ActionView::Helpers\n\n # Turns this link into an HTML link\n def to_html\n link_to(text, location)\n end\n\n # Returns true if this link points to the same controller and action as the given\n # location hash.\n def points_to?(other_location)\n # If no action is specified, the :index action is used\n # This way the locations {:controller => :foo} and {:controller => :foo, :action => :index}\n # will be treated as equal\n action = location[:action] || :index\n other_action = other_location[:action] || :index\n location[:controller] == other_location[:controller] && action == other_action\n end\nend\n\n# Returns an li tag containing a link to the location represented by the given Link object.\n# The tag's id will be \"selected\" if the link points to the current action and controller.\ndef navigation_item(link)\n selected = link.points_to?(params) ? \"selected\" : nil\n content_tag(:li, link.to_html, :id => selected)\nend\n</code></pre>\n\n<p>You'd then use <code>Link.new(\"title\", :controller => \"foo\", :action => bar)</code> inside <code>get_tab_options</code> to create a link.</p>\n\n<hr>\n\n<p>As a last note, it also seems a bit icky to me to hardcode which links will be available in which controller into a helper method. It seems that this should rather be handled in the controllers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T05:33:44.833",
"Id": "2230",
"Score": "0",
"body": "When i tried this i got undefined method `link_to' for ActionView::Helpers:Module error. Am I missing any thing here?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T13:57:37.390",
"Id": "2243",
"Score": "0",
"body": "@ssri: Sorry about that. Fixed now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T11:43:45.190",
"Id": "1232",
"ParentId": "1224",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "1232",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T04:54:24.250",
"Id": "1224",
"Score": "7",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Refactor Helper methods"
} | 1224 |
<p>I needed a function that would take a list of folders and removed all sub folders, so that only the top level folders stayed in the list. </p>
<p>For example, given the list:</p>
<pre><code>c:\stuf\morestuff
c:\stuf\morestuff\sub1
c:\otherstuf
c:\otherstuf\sub1
c:\otherstuf\sub2
</code></pre>
<p>I wanted the list to be reduced to:</p>
<pre><code>c:\stuf\morestuff
c:\otherstuf
</code></pre>
<p>So I came up with this solution:</p>
<pre><code>// remove empty strings and sub folders
private static void CleanUpFolders(List<string> uniqueFolders)
{
uniqueFolders.RemoveAll(
delegate(string curFolder)
{
// remove empty
if (string.IsNullOrEmpty(curFolder))
return true;
// remove sub paths
if (uniqueFolders.Exists(
delegate(string s)
{
if (!string.IsNullOrEmpty(s) &&
curFolder.StartsWith(s) &&
string.Compare(s, curFolder) != 0)
return true;
return false;
} ))
return true;
return false;
}
);
}
</code></pre>
<p>This seems to work (not very well tested though) but I was left wondering about some things:</p>
<ul>
<li>is there an issue with using variables inside anonymous methods that were declared outside?</li>
<li>any potential issues with nested anonymous methods?</li>
<li>any other issues or best practices worth mentioning?</li>
</ul>
| [] | [
{
"body": "<pre><code>is there an issue with using variables inside anonymous methods that were declared outside?\n</code></pre>\n\n<p>no, if an anonymous method accesses a local variable then C# will create a separate class to host the method and variable allowing it all to \"just work\". (*)</p>\n\n<pre><code>any potential issues with nested anonymous methods?\n</code></pre>\n\n<p>The only issue I see with the nested anonymous methods is that it makes the code ugly and hard to read, but then I find linq in general has this effect :).</p>\n\n<pre><code>any other issues or best practices worth mentioning?\n</code></pre>\n\n<p>Since your paths are windows paths, you may want to consider using case insensitive comparisons.</p>\n\n<p>This is how I would have done it, it works off the basis that if you sort the list then all strings that start with the string at position X will be in a single block that appears immediately after it.</p>\n\n<pre><code>private static void CleanUpFolders(List<string> uniqueFolders)\n{\n uniqueFolders.RemoveAll(string.IsNullOrEmpty);\n uniqueFolders.Sort(StringComparer.OrdinalIgnoreCase);\n\n int write = 0;\n string last = null;\n\n for (int read = 0; read < uniqueFolders.Count; read++)\n {\n string value = uniqueFolders[read];\n\n if (last = null || value.StartsWith(last, StringComparison.OrdinalIgnoreCase))\n {\n uniqueFolders[write] = value;\n last = value;\n write++;\n }\n }\n\n if (write < uniqueFolders.Count)\n {\n uniqueFolders.RemoveRange(write, uniqueFolders.Count - write);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>(*) if you change the referenced variable after creating the delegate, it will affect what the delegate sees which can be non-obvious, particularly if you create a delegate in a loop that accesses the index or current item.</p>\n\n<p>At the end of the loop in this example, all delegates will return 10;</p>\n\n<pre><code>Func<int>[] bob = new Func<int>[10];\n\nfor(int i = 0; i < bob.Length; i++)\n{\n bob[i] = () => i;\n}\n</code></pre>\n\n<p>But at the end of this loop each will return it's own index.</p>\n\n<pre><code>for(int i = 0; i < bob.Length; i++)\n{\n int j = i;\n bob[i] = () => j;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T09:18:21.423",
"Id": "1230",
"ParentId": "1225",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>is there an issue with using variables inside anonymous methods that were declared outside?</p>\n</blockquote>\n\n<p>No, this is what anonymous methods are designed for! It is a very useful trick to keep up your sleeve. Read up on <a href=\"http://en.wikipedia.org/wiki/Closure_%28computer_programming%29\">Closures</a>. There are all sorts of things you can do with them. </p>\n\n<p>Obviously there are issues with doing anything when you don't understand it fully, but the way you are using them in your code is what these things are all about!</p>\n\n<blockquote>\n <p>any potential issues with nested anonymous methods?</p>\n</blockquote>\n\n<p>Same thing.</p>\n\n<blockquote>\n <p>any other issues or best practices worth mentioning?</p>\n</blockquote>\n\n<p>Unless you are still using c# 2, the syntax has been simplified to use what is known as a lambda. Instead of using</p>\n\n<pre><code>delegate(string curFolder) { ..code.. }\n</code></pre>\n\n<p>you can just go :</p>\n\n<pre><code>curFolder => ..code..\n</code></pre>\n\n<p>As RemoveAll takes a Predicate, you can also lose the return key word. As long as the statement evaluates to True or False, it will take that as the return.</p>\n\n<p>You have some code that is basically going :</p>\n\n<pre><code>if x == true\n return true\nreturn false\n</code></pre>\n\n<p>This can be simplified to :</p>\n\n<pre><code>return x\n</code></pre>\n\n<p>With those two things, your code could be simplified to :</p>\n\n<pre><code> uniqueFolders.RemoveAll(\n curFolder => \n\n string.IsNullOrEmpty(curFolder) ||\n uniqueFolders.Exists( s=> \n !string.IsNullOrEmpty(s) &&\n curFolder.StartsWith(s) &&\n string.Compare(s, curFolder) != 0)\n\n );\n</code></pre>\n\n<p>Its a bit of a mouthfull. You may want to factor out a new method.</p>\n\n<pre><code>uniqueFolders.RemoveAll( curFolder => IsNotRootFolder(uniqueFolders, curFolder ) );\n\nbool IsNotRootFolder ( uniqueFolders, curFolder )\n{\n return string.IsNullOrEmpty(curFolder) ||\n uniqueFolders.Exists( s=> \n !string.IsNullOrEmpty(s) &&\n curFolder.StartsWith(s) &&\n string.Compare(s, curFolder) != 0)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T19:47:12.607",
"Id": "2178",
"Score": "2",
"body": "To be clear, there is a potential issue with using variable in anonymous methods which are declared outside the anonymous method; you don't have that issue here, but you should make sure you understand the concept of \"Access to Modified Closure\" - http://stackoverflow.com/questions/235455/access-to-modified-closure"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T10:52:57.137",
"Id": "1231",
"ParentId": "1225",
"Score": "12"
}
},
{
"body": "<p>The other answers are already pretty much complete, but I'm wondering about the usage of your code.</p>\n\n<p>Are these real folders, present on the system running the code? Do you have to receive the folders as a list of strings?</p>\n\n<p>Brian Reichle already mentioned that string representation of folders are system dependant. Perhaps you are better of writing a solution based around the <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx\" rel=\"nofollow\"><code>DirectoryInfo</code></a> class.</p>\n\n<p>This is a simple recursive solution using an extension method:</p>\n\n<pre><code>public static List<DirectoryInfo> GetTopFolders( this DirectoryInfo dir )\n{\n List<DirectoryInfo> result = new List<DirectoryInfo>();\n\n DirectoryInfo[] subDirs = dir.GetDirectories();\n if ( subDirs.Length > 0 )\n {\n result.Add( dir );\n subDirs.ForEach( d => result.AddRange( GetTopFolders( d ) ) );\n }\n\n return result;\n} \n</code></pre>\n\n<p>It uses the following IEnumerable extension method:</p>\n\n<pre><code>public static void ForEach<T>( this IEnumerable<T> source, Action<T> action )\n{\n foreach ( var item in source )\n {\n action( item );\n }\n}\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>Or even better using Linq and the <code>EnumerateDirectories</code> function. Note that the passed <code>dir</code> argument isn't included in this result.</p>\n\n<pre><code>public static IEnumerable<DirectoryInfo> GetTopFolders( this DirectoryInfo dir )\n{\n return from d in dir.EnumerateDirectories(\"*\", SearchOption.AllDirectories)\n where d.EnumerateDirectories().Any()\n select d;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T14:11:14.790",
"Id": "1237",
"ParentId": "1225",
"Score": "2"
}
},
{
"body": "<p>One consideration is performance. Your current code is scanning the list as part of RemoveAll (that's O(n)) and for each item it is calling Exists on the list (that's also O(n) because it has to loop the entire list). The Exists call has the potential to get cheaper as you get closer to done if items are removed but in the worst case it looks like an O(N^2) implementation. Instead, use a HashSet - this makes lookups O(1) and results in an O(n) implementation. </p>\n\n<p>Also, use the framework Path class to get the parent folders instead of StartsWith - your current code treats c:\\john as a parent of c:\\johnny\\appleseed and removes c:\\johnny\\appleseed from the list.</p>\n\n<pre><code>private static void CleanUpFolders(List<string> uniqueFolders)\n{\n var folderLookup = new HashSet<string>(uniqueFolders);\n uniqueFolders.RemoveAll(x => String.IsNullOrEmpty(x) ||\n x.Generate(Path.GetDirectoryName)\n .Skip(1) // the original\n .TakeWhile(p => p != Path.GetPathRoot(p))\n .Any(folderLookup.Contains));\n}\n</code></pre>\n\n<p>assuming generically reusable <a href=\"http://www.eggheadcafe.com/tutorials/aspnet/159e4793-6b17-4e89-bd94-3bde8a5f2d50/iterators-iterator-block.aspx\" rel=\"nofollow\">Generate extension method</a></p>\n\n<pre><code>public static class TExtensions\n{\n public static IEnumerable<T> Generate<T>(this T initial, Func<T, T> next) \n {\n var current = initial;\n while (true)\n {\n yield return current;\n current = next(current);\n }\n }\n}\n</code></pre>\n\n<p>test:</p>\n\n<pre><code>public void Should_only_keep_parent_directories()\n{\n var directories = new List<string>\n {\n null,\n \"\",\n @\"c:\\bob\",\n @\"c:\\john\",\n @\"c:\\johnny\\appleseed\",\n @\"c:\\bob\\mike\\nick\",\n @\"C:\\a\\c\",\n @\"c:\\stuf\\morestuff\",\n @\"c:\\stuf\\morestuff\\sub1\",\n @\"c:\\otherstuf\",\n @\"c:\\otherstuf\\sub1\",\n @\"c:\\otherstuf\\sub1a\",\n @\"c:\\otherstuf\\sub2\"\n };\n\n CleanUpFolders(directories);\n directories.Count.ShouldBeEqualTo(6);\n directories.ShouldContainAll(new[]\n {\n @\"c:\\bob\",\n @\"c:\\stuf\\morestuff\",\n @\"c:\\otherstuf\",\n @\"C:\\a\\c\",\n @\"c:\\john\",\n @\"c:\\johnny\\appleseed\"\n });\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T02:17:06.437",
"Id": "2188",
"Score": "1",
"body": "if you added `c:\\a\\b` to the directories list then `c:\\a` would be added to parents and `c:\\a\\b` would be removed. but there is no `c:\\a` in the list to cover it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T15:47:11.873",
"Id": "2192",
"Score": "0",
"body": "Good point @Brian. I revised the implementation to cover this case."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T23:30:24.637",
"Id": "2196",
"Score": "0",
"body": "Now if you add `c:\\bob` and `c:\\bob\\mike\\nick` then the latter will not be removed because `c:\\bob\\mike` is not also in the list."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T18:13:12.520",
"Id": "2226",
"Score": "0",
"body": "Yep, right again @Brian. Fixed."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T18:40:50.120",
"Id": "1243",
"ParentId": "1225",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1231",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T05:04:50.357",
"Id": "1225",
"Score": "11",
"Tags": [
"c#",
"strings",
"collections"
],
"Title": "Filtering a recursive directory listing, discarding subfolders"
} | 1225 |
<p>This code is intended to find all possible solutions to a cryptoarithmetic problem. The description of the problem I was trying to solve is here:</p>
<blockquote>
<p>In cryptoarithmetic problems, we are given a problem wherein the
digits are replaced with characters representing digits. A solution to
such a problem is a set of digits that, when substituted in the
problem, gives a true numerical interpretation.</p>
<p>Example:</p>
<pre><code>IS
IT
___
OK
</code></pre>
<p>has a solution</p>
<pre><code>{ I = 1; K = 1; O = 3; S = 5; T = 6}
</code></pre>
<p>For each of the below cryptoarithmetic problems, write a program that finds all
the solutions in the shortest possible time.</p>
<pre><code>IS I
IT AM
__ __
OK OK
</code></pre>
</blockquote>
<p>I was only able to solve it using brute force, though I believe there are more efficient methods. I am also hoping to receive feedback on my formatting, naming, and really anything you think could use improvement.</p>
<pre><code>(defun place-value-to-integer (the-list &OPTIONAL place-value)
(let ((place-value (if place-value place-value 1)))
(if (= (length the-list) 1) (* place-value (first the-list))
(+ (* place-value (first (last the-list))) (place-value-to-integer (butlast the-list) (* 10 place-value))))))
(defun fill-from-formula (formula guess)
(loop for digit in formula collect (gethash digit guess)))
(defun check-answer (augend-formula addend-formula sum-formula guess)
(let ((augend (fill-from-formula augend-formula guess))
(addend (fill-from-formula addend-formula guess))
(sum (fill-from-formula sum-formula guess)))
(= (place-value-to-integer sum) (+ (place-value-to-integer augend) (place-value-to-integer addend)))))
(defun brute-force-guess(augend-formula addend-formula sum-formula unique-values &OPTIONAL callback guess)
(let ((guess (if (null guess) (make-hash-table) guess)))
(loop for digit in '(0 1 2 3 4 5 6 7 8 9) do
(setf (gethash (car unique-values) guess) digit)
(if (= (length unique-values) 1)
(if (check-answer augend-formula addend-formula sum-formula guess) (print-result augend-formula addend-formula sum-formula guess) nil)
(brute-force-guess augend-formula addend-formula sum-formula (cdr unique-values) callback guess)))))
(defun print-result (augend-formula addend-formula sum-formula guess)
(format t "One answer is ~a + ~a = ~a ~%"
(fill-from-formula augend-formula guess)
(fill-from-formula addend-formula guess)
(fill-from-formula sum-formula guess)))
(defun find-unique-values (the-list)
(let ((unique-items ()))
(loop for sublist in the-list do
(loop for item in sublist do
(unless (member item unique-items) (setf unique-items (append (list item) unique-items))))) unique-items))
(let ((problemA (list (list 'I 'S) (list 'I 'T) (list 'O 'K)))
(problemB (list (list 'I) (list 'A 'M) (list 'O 'K))))
(brute-force-guess (first problemA) (second problemA) (third problemA) (find-unique-values problemA) #'print-result)
(brute-force-guess (first problemB) (second problemB) (third problemB) (find-unique-values problemB) #'print-result))
</code></pre>
| [] | [
{
"body": "<p>Some preliminary notes for now (I'll add later):</p>\n\n<p>Whenever you need to write <code>(if n n 2)</code> or <code>(if (not n) 2 n)</code>, you can instead write <code>(or n 2)</code>. <code>or</code> will take any number of arguments and return either <code>nil</code> or the first argument that evaluates to non-<code>nil</code>.</p>\n\n<hr>\n\n<p>When working with optional arguments, you can set defaults for them. </p>\n\n<pre><code>(defun place-value-to-integer (the-list &OPTIONAL place-value) \n (let ((place-value (if place-value place-value 1)))\n ...\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>(defun place-value-to-integer (the-list &OPTIONAL (place-value 1)) \n ...\n</code></pre>\n\n<hr>\n\n<p>I don't have time to get into the rest right now, but you're using <code>loop</code> to <code>setf</code> a series of <code>hash</code> values, which tells me you could probably simplify it by using a more functional approach (it might be one of the exceptions, but it doesn't feel like one at first glance).</p>\n\n<p>EDIT:</p>\n\n<p><code>(if a b nil)</code> is equivalent to <code>(when a b)</code> (and it's good style to use the second over the first).</p>\n\n<p>EDIT2: Ok, wow, hey. That's two hours of my life I won't get back. I wrote up and edited down a pretty ridiculously long piece on my process (if you care, it's <a href=\"http://langnostic.blogspot.com/2011/03/puzzling-with-lisp.html\" rel=\"nofollow\">here</a>). Here's how I would tackle a brute-force approach to this problem.</p>\n\n<p>EDIT3: Simplified slightly.</p>\n\n<pre><code>(defpackage :cry-fun (:use :cl :cl-ppcre))\n(in-package :cry-fun)\n\n(defun digits->number! (&rest digits)\n (apply #'+ (loop for d in (nreverse digits) for i from 0\n collect (* d (expt 10 i)))))\n\n(defun number->digits (num &optional (pad-to 5))\n (let ((temp num)\n (digits nil))\n (loop do (multiple-value-call \n (lambda (rest d) (setf temp rest digits (cons d digits)))\n (floor temp 10))\n until (= pad-to (length digits)))\n digits))\n\n(defun string->terms (problem-string)\n (reverse\n (mapcar (lambda (s) (mapcar (lambda (i) (intern (format nil \"~a\" i))) \n (coerce s 'list)))\n (split \" \" (string-downcase problem-string)))))\n\n(defmacro solve-for (problem-string)\n (let* ((arg-count (length (remove-duplicates (regex-replace-all \" \" problem-string \"\"))))\n (nines (apply #'digits->number! (make-list arg-count :initial-element 9))))\n `(loop for i from 0 to ,nines\n when (apply (solution-fn ,problem-string) (number->digits i ,arg-count))\n collect it)))\n\n(defmacro solution-fn (problem-string)\n (let* ((terms (string->terms problem-string))\n (args (remove-duplicates (apply #'append terms))))\n `(lambda ,args\n (when (= (+ ,@(loop for term in (cdr terms) collect `(digits->number! ,@term)))\n (digits->number! ,@(car terms)))\n (list ,@(mapcan (lambda (i) (list (symbol-name i) i)) args))))))\n</code></pre>\n\n<p>EDIT (by jaresty): adding comments to show example intermediate values for \"solution-fn\" </p>\n\n<pre><code>(defmacro solution-fn (problem-string)\n (let* ((terms (string->terms problem-string)) \n ;example: (terms ((o k) (i t) (i s)))\n (args (remove-duplicates (apply #'append terms)))) \n ;example: (args (o k t i s))\n `(lambda ,args\n (when (= (+ ,@(loop for term in (cdr terms) collect `(digits->number! ,@term))) \n (digits->number! ,@(car terms)))\n ;example: (when (= (+ (i t) (i s)) (o k)\n (list ,@(mapcan (lambda (i) (list (symbol-name i) i)) args))))))\n ;example: (list \"o\" o \"k\" k \"t\" t \"i\" i \"s\" s)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T08:42:09.787",
"Id": "2200",
"Score": "0",
"body": "Wow, this is a pretty intense solution! I'm going to need to study it for a while to try and understand how it works. Thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T10:37:06.887",
"Id": "2203",
"Score": "0",
"body": "Can you explain what multiple-value-call does in number->digits? I'm having some trouble understanding how it works."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T13:00:54.553",
"Id": "2204",
"Score": "1",
"body": "@jaresty: `floor` returns two values: the floored value and the remainder. However when calling it normally, only the first return value will be used. By using `multiple-value-call` both values returned by floor are given to the lambda."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T13:55:42.837",
"Id": "2206",
"Score": "1",
"body": "I linked to a blog post in which I go step-by-step on how I came up with this (it's actually a lot simpler than it looks; most of the complexity in it is introduced because the naive solution I started with performed quite poorly, and the question specifies \"as fast as possible\"). sepp2k got it on the `multiple-value-call`, and yeah `->` is just part of a name. It's a convention from Scheme where `foo->bar` lets you know that the function takes a `foo` and returns a `bar`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T01:38:57.247",
"Id": "2228",
"Score": "0",
"body": "Why do you need to use defmacro rather than defun for solve-for and solution-fn?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T04:02:12.597",
"Id": "2229",
"Score": "0",
"body": "How would you use \"solve-for\" to print out a list of possible solutions? I'm having some difficulty figuring out how to work with the returning values. I tried using multiple-value-call, but I only see one answer, \"((s 0 i 0 t 0 0 o 0 k 0))\", to \"is it ok\", which doesn't seem right at first glance."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T12:50:24.033",
"Id": "2237",
"Score": "0",
"body": "@jaresty - I used `defmacro` for `solve-for` because it needs to take a variable number of differently named (but specific to the problem) arguments. You could probably define it as a function, but the amount of list slicing I assumed I'd need to do seemed like it would be more complicated (or forced onto the user). I made `solve-for` a macro because I need to pass `solution-fn` a raw string, and I don't know what its value will be at the time I define `solve-for`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T13:26:40.367",
"Id": "2240",
"Score": "0",
"body": "@jaresty - `solve-fn` currently returns a list of `([letter] [value] ...)` for each possible solution. If you absolutely must print it, way I'd try it here is either by prepending `(format t \"~{~a:~a~^, ~}~%\"` to `(list ,@(mapcan (lambda (i) (list (symbol-name i) i)) args))))))`. I have to point out though; printing the result rather than returning it severely limits the reusability of the function, and (in this case) doesn't add much to the readability either."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T13:43:53.520",
"Id": "2241",
"Score": "0",
"body": "Ok - I think I need to apologize. It works great. The problem seems to have been a makeshift solution I tried to use to replace the strings when I couldn't download cl-ppcre easily (proxy at work - didn't have time to work around it). Anyway, it seems to work great! Now I just need some time to try and understand it better. Thanks again, and I hope it's ok to ask if I still have questions..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T14:29:50.810",
"Id": "2245",
"Score": "0",
"body": "@jaresty - S'ok; I'm happy to keep answering to help clarify. Macros tend to be...difficult the first time. If your work disallows `quicklisp`, `cl-ppcre` should also be installable through `asdf`. In SBCL, evaluate `(require 'asdf) (require 'asdf-install) (asdf-install:install 'cl-ppcre)` (really it should work in any implementation, but I've heard people have some problems with a couple of them). As a last resort, you can get the raw tarball from the [doc-page](http://weitz.de/cl-ppcre/). PS. pardon the poor editing on the previous comment."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T03:18:09.873",
"Id": "2254",
"Score": "0",
"body": "Is there a better way to debug a function, i.e. peek inside its variables and whatnot, than printing the variables' contents out with format?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T04:32:32.680",
"Id": "2255",
"Score": "0",
"body": "I added comments with my understanding of the intermediate values of solution-fn in an addendum to your post above. Is my interpretation correct?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T13:07:41.497",
"Id": "2269",
"Score": "0",
"body": "@jaresty - I typically test functions piece by piece in the REPL (while I'm constructing them). The main debugging facilities Lisp has are the `trace` and `step` functions. I can't see your addendum; if you edited the post above, I won't be able to see it until a mod approves your edits (you may want to just post a separate answer)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T17:03:38.500",
"Id": "2270",
"Score": "0",
"body": "@jaresty - Yup, you got it. (Only one technical point; because of the way I generate the symbols, they'll actually be `|o| |k| |t| |i| |s|`, but that doesn't change the mechanics of the macroexpansion. `|foo|` just denotes a symbol name with escaped elements)."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T17:47:43.433",
"Id": "1251",
"ParentId": "1227",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1251",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T06:26:11.830",
"Id": "1227",
"Score": "4",
"Tags": [
"lisp",
"cryptography",
"common-lisp"
],
"Title": "Finding a cryptoarithmetic solution"
} | 1227 |
<p>I saw a sassy CSS for a rails app like this:</p>
<pre><code>$std-margin: 30px;
@mixin solid-bg($color: #EEEEEE) {
background: none repeat scroll 0 0 $color;
}
@mixin solid-border($direction, $width: 1px, $color: black) {
@if $direction == "" {
border: {
color: $color ;
width: $width;
style: solid;
}
} @else {
border-#{$direction}: {
color: $color ;
width: $width;
style: solid;
}
}
}
html {
font: 90%/1.3 arial,sans-serif;
body {
margin: $std-margin;
.top-nav {
text-align: center;
width: 100%;
.login {
float: right;
padding-right: 63px;
clear: both;
}
a {
text-decoration: none;
}
}
.content {
@include solid-border("");
clear: both;
padding: 15px;
}
h2 {
margin: $std-margin;
margin-left: 0px;
}
h3, .detail {
margin: $std-margin;
}
#header {
ul {
list-style: none outside none;
padding: 0;
li {
float: left;
a {
@include solid-bg();
color: #0000CC;
display: block;
padding: 0.24em 1em;
text-decoration: none;
}
}
}
#selected a {
@include solid-bg(white);
color: black;
font-weight: bold;
position: relative;
top: 1px;
@include solid-border("");
@include solid-border('bottom', 0px);
}
}
label {
float: left;
margin-right: 1em;
text-align: right;
width: 10em;
}
input {
@include solid-bg(#FAFAFA);
-moz-border-radius: 0.4em 0.4em 0.4em 0.4em;
@include solid-border("", 1px, #DDDDDD);
font: bold 0.95em arial,sans-serif;
padding: 0.15em;
width: 10em;
}
.field {
padding: 5px;
clear: both;
input {
width:12em;
@include solid-border("", 1px, #006);
@include solid-bg(#ffc);
&:hover {
@include solid-border("");
@include solid-bg(#ff6);
}
}
.fieldWithErrors {
float: left;
padding: 3px;
input {
@extend .field.input;
@include solid-border("", 2px, red);
}
}
.create {
width:5em;
}
.submit {
@include solid-bg(#D0DAFD);
border: 0 none;
cursor: pointer !important;
display: block;
height: 26px;
margin: 1em;
overflow: hidden;
width: 69px;
}
}
table {
border-collapse: collapse;
margin: 20px;
text-align: left;
width: 480px;
font {
family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
size: 12px;
}
th {
@include solid-bg(#B9C9FE);
@include solid-border('bottom', 1px, #FFFFFF);
@include solid-border('top', 4px, #AABCFE);
color: #003399;
font-size: 13px;
font-weight: normal;
padding: 8px;
}
tr {
@include solid-bg(#E8EDFF);
&:hover td {
@include solid-bg(#D0DAFD);
color: #333399;
}
td.title {
color: #333399;
}
}
td {
@include solid-border('bottom', 1px, #FFFFFF);
@include solid-border('top', 1px, transparent);
color: #666699;
padding: 8px;
}
}
.activities {
padding: 10px;
a{
margin: 10px;
}
}
.flash {
font-family:'Trebuchet MS';
color:#FF0000;
font-size:14px;
}
.calendar_date_select table {
width: 78px;
td {
padding: 5px;
}
}
.main-content {
clear: both;
float: left;
width: 100%;
}
.clear {
clear: both;
}
#errorExplanation {
@include solid-bg();
margin: 10px;
padding: 5px 0 5px 20px;
}
}
}
</code></pre>
<p>Using best practice how this can be optimized?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T11:39:18.790",
"Id": "2160",
"Score": "1",
"body": "Optimization usually depends on the HTML. Can you provide it with use cases for all the rules? Also could you point out the advantages you see in your mixins over just using `background-color` and `border` directly?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T06:09:40.903",
"Id": "2231",
"Score": "0",
"body": "@RoToRa: I am learning about sassy css and I saw this for some rails application. I don't know why those hav been used. As far as i understand mixins are used to replace a set of common style, and they might have used mixin for background as all the background differs only in color and have same value for the properties position, repeat and scroll. I am not sure why they have used. Its purely my guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T19:49:18.697",
"Id": "68614",
"Score": "4",
"body": "This question appears to be off-topic because it is [not code written by you](http://meta.codereview.stackexchange.com/questions/1294/why-is-only-my-own-written-code-on-topic)"
}
] | [
{
"body": "<p>One optimization you should do in any case is not to have all rules inside <code>html { ... }</code> and <code>body { ... }</code>, because the resulting CSS rules all require the renderer to unnecessarily check every single element if it is actually a decedent of <code>html</code> and <code>body</code> - which they undoubtedly are.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T11:47:12.343",
"Id": "1233",
"ParentId": "1229",
"Score": "8"
}
},
{
"body": "<p>Sadly, that code would best be optimized by <em>removing</em> the mixins. They're not saving you any typing <em>and</em> generating highly inefficient CSS. Using proper CSS shorthand would help too.</p>\n\n<p>From the solid background mixin:</p>\n\n<pre><code>background: none repeat scroll 0 0 $color;\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>background: $color;\n</code></pre>\n\n<p>Shorter to write, shorter when compiled.</p>\n\n<hr>\n\n<p>From the border mixin:</p>\n\n<pre><code>border: {\n color: $color ;\n width: $width;\n style: solid;\n}\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>border: $width solid $color;\n// or just `$width solid` if the border will be the same color as your text\n</code></pre>\n\n<hr>\n\n<p>There's an instance of <code>cursor: pointer</code> without <code>cursor: hand</code> to go with it (some browsers use one, others use the other)</p>\n\n<hr>\n\n<pre><code> font {\n family: \"Lucida Sans Unicode\",\"Lucida Grande\",Sans-Serif;\n size: 12px;\n }\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>font: 12px \"Lucida Sans Unicode\",\"Lucida Grande\",Sans-Serif;\n</code></pre>\n\n<hr>\n\n<p>There's a lonely border-radius property with <em>only</em> the -moz- prefix, not even the non-prefixed version to go with it.</p>\n\n<hr>\n\n<p>The table styles are all nested unnecessarily</p>\n\n<ul>\n<li><code>table tr</code></li>\n<li><code>table tr td.title</code></li>\n<li><code>table td</code></li>\n</ul>\n\n<p>The tr and td elements cannot appear outside of tables, so saying it must be a descendant of a table is superfluous. Similarly, td must be a descendant of tr, so again redundancy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T20:01:48.423",
"Id": "27921",
"ParentId": "1229",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T08:40:48.553",
"Id": "1229",
"Score": "5",
"Tags": [
"css",
"sass"
],
"Title": "Good practice using SCSS"
} | 1229 |
<p>I have this code in a class sharing a private static array of data. Internally it's encoded, but I need the iterator for a <code>foreach</code> loop to show the decoded values.</p>
<p>Is there a native array function that can remap the keys and values via a callback function?</p>
<pre><code>public function getIterator( )
{
$arr = array();
foreach ( self::$data as $encName => $encValue )
{
$name = $this->decode( $encName );
$value = $this->decode( $encValue );
$arr[$name] = $value;
}
return new ArrayIterator( $arr );
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T23:51:12.673",
"Id": "2187",
"Score": "0",
"body": "I just had a thought to possibly implement `Iterator` instead of `IteratorAggregate` which would reduce the need for duplicating the array before iterating, and instead, decode during the iteration."
}
] | [
{
"body": "<p>Implementing <code>Iterator</code> is the way to go in my opinion. As for your question, <a href=\"http://php.net/manual/en/function.array-map.php\" rel=\"nofollow\"><code>array_map</code></a> would allow you to decode the values but not the keys. But you can combine that with other array operations to get the desired result.</p>\n\n<pre><code>public function decodeArray($array) {\n $decode = array($this, 'decode');\n return array_combine(\n array_map(array_keys($array), $decode),\n array_map(array_values($array), $decode)\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-11T02:48:38.827",
"Id": "1246",
"ParentId": "1238",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T17:48:35.670",
"Id": "1238",
"Score": "3",
"Tags": [
"php",
"php5"
],
"Title": "Decoding name/value pairs"
} | 1238 |
<p>I have a function that takes in a controller instance, a method, and parameters (this is for a little MVC experiment I'm working on). The purpose of the function is to execute the controller method with the given parameters.</p>
<p>However, there are a few caveats. First, if the controller has a "router" method, it will call that instead of the method that was passed in. Second, if any of the controller "annotations" return a response, that will also override the method. Then, if those cases fail, we return the response of the actual controller method passed in.</p>
<p>It looks like this:</p>
<pre><code> switch (true)
{
// Router methods get first priority!
case ($controller->using_router):
$response = call_user_func_array(array($controller, 'router'));
break;
// Annotation responses take precedence over method responses because they are often used for authentication.
case ( ! is_null($response = Annotation\Runner::run(Annotation\Extractor::extract($controller, $method)))):
break;
// No router or annotation responses... we're ready to run the method!
default:
$response = call_user_func_array(array($controller, $method), $parameters);
}
</code></pre>
<p>For some reason, this just feels dirty. I don't like the <code>break</code> after checking for an annotation response. But, I'm not sure of any other way to implement a response "priority".</p>
<p>Is there a better way?</p>
| [] | [
{
"body": "<p>That's certainly a bastardization of the <code>switch</code> statement.</p>\n\n<p>What you should use is an <code>if...else if...</code> group:</p>\n\n<pre><code>$response = null; //initialize\nif ( $controller->using_router)\n{\n $response = $controller->router();\n}\nelse\n{\n $response = Annotation\\Runner::run(Annotation\\Extractor::extract( $controller, $method ) );\n if ( is_null( $response )\n {\n $response = call_user_func_array( array( $controller, $method ), $parameters );\n }\n}\n</code></pre>\n\n<p>Note: this code flows in a readable manner. The response is set, if the controller is using the router, the response is set to the output of <code>$controller->router()</code>, otherwise the response is set to the extracted controller method.</p>\n\n<p>If <em>that</em> is null, the response is finally set to whatever <code>$controller->$method(...)</code> produces.</p>\n\n<p>Code should <strong>always</strong> flow in a readable manner (unless it's minified, obfuscated, or encoded).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T18:03:15.703",
"Id": "1240",
"ParentId": "1239",
"Score": "11"
}
},
{
"body": "<p>Code is almost always better when you return a value instead of holding on to a value to return later (imnsho). If you simply say</p>\n\n<pre><code>if ( $controller->using_router) {\n return $controller->router();\n}\n</code></pre>\n\n<p>you've simplified the function significantly. The rest of it depends on whether the next result is null, so you will need somehow to hold onto it, but you're already looking at simpler code.</p>\n\n<p>I don't think a switch statement is what you want here. It can be shoehorned to fit - but it's not really appropriate or descriptive of what you're trying to do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T18:34:46.600",
"Id": "1242",
"ParentId": "1239",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1240",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-10T17:53:09.507",
"Id": "1239",
"Score": "5",
"Tags": [
"php",
"url-routing"
],
"Title": "Switch statement in PHP - cleaner way to determine priority?"
} | 1239 |
<p>I am locating the find method of List in C# with the single Expression type parameter</p>
<p>I am using the following ( where T is a List, in my case a SubSonic IActiveRecord )</p>
<pre><code>MethodInfo info = typeof(T).GetMethods(BindingFlags.Static | BindingFlags.Public)
.FirstOrDefault(m => m.Name == "Find" && m.GetParameters().Count() == 1);
</code></pre>
<p>This works perfectly well, but feels clunky (especially the parameter count part) and I'm not sure how future proof it is.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:06:08.313",
"Id": "2179",
"Score": "0",
"body": "IEnumerable expose one single method named GetEnumerator..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:23:10.513",
"Id": "2180",
"Score": "0",
"body": "@VirtualBlackFox It also exposes many extension methods in C#3+ for use with LINQ"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:28:57.687",
"Id": "2181",
"Score": "0",
"body": "1.GetMethod on IEnumerable<T> will never return theses. 2.None is called \"Find\" in the framework. 3.Look like you are searching on a List<T> as this one define a one parameter \"Find\" taking a predicate."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:37:56.650",
"Id": "2182",
"Score": "0",
"body": "@VirtualBlackFox Oh, you are correct. I always assumed it was an IEnumerable extension method, thanks. Question edited accordingly"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T23:24:29.660",
"Id": "2185",
"Score": "2",
"body": "Is there a reason you're not just using `GetMethod`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T23:50:16.850",
"Id": "2186",
"Score": "0",
"body": "@sepp2k It didn't work when I tried it. This is a first draft of the code, hence I'm here."
}
] | [
{
"body": "<p>When searching for methods using reflection I found that the most future-proof way is by searching exactly for the method, so not only the Count() is correct but I would also have checked both what is this parameter type and what is the return type of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T23:03:56.207",
"Id": "2183",
"Score": "0",
"body": "Thanks, less elegant, but more constrained and future proof, makes sense"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T23:13:45.603",
"Id": "2184",
"Score": "0",
"body": "Yes the case where you need to find a function with a Something<OtherThing<T>> paramter where T is a generic parameter of the parent class produce especially non elegant code. If someone took the time I guess that designing a small DSL for this could be possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:57:06.553",
"Id": "1245",
"ParentId": "1244",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1245",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-10T22:00:18.193",
"Id": "1244",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Best way to locate Find on List<T> with reflection"
} | 1244 |
<p>I would like to have my code reviewed, I'm trying to get a general model I'm using for my stuff going and I don't want to keep using wrong or inefficient code if I can.</p>
<p>My file structure is like this: </p>
<p><img src="https://i.stack.imgur.com/0equs.png" alt="File structure"></p>
<p>In conf there's a file sitting called database.conf.php with the following content: </p>
<pre><code><?php
$this->host = "localhost";
$this->user = "snowclouds_LoL";
$this->password = "****";
$this->database = "snowclouds_LoL";
?>
</code></pre>
<p>In functions I have my functions included like this in functions.php</p>
<pre><code><?php
//Constructor class for calling all function scripts.
require("database.php");
require("security.php");
require("show.php");
require("user.php");
require("misc.php");
?>
</code></pre>
<p>This is my database class:</p>
<pre><code><?php
class Database {
private $host;
private $user;
private $password;
private $database;
private $link;
public function connect(){
$this->link = mysqli_connect ($this->host, $this->user, $this->password) or die("Connection problem: " . mysqli_error());
mysqli_select_db($this->link, $this->database);
}
public function resultquery($query){
$result = mysqli_query($this->link, $query) or die(mysqli_error($this->link));
return $result;
}
public function insertquery($query){
if(mysqli_query($this->link, $query)){
return true;
}else{
return mysqli_error($this->link);
}
}
public function __construct(){
if(!file_exists("conf/database.conf.php")){
die("conf/database.conf.php file does not exist!");
}else{
include('conf/database.conf.php');
}
}
}
?>
</code></pre>
<p>Indenting is a little broke because pasting 4 spaces before every line is just time consuming :/</p>
<p>This is my index.php
<pre><code>$show->header();
$show->menu();
require("act.php");
$show->footer();
?>
</code></pre>
<p>This is my init.php</p>
<pre><code><?php
session_start();
ob_start();
require ("functions/functions.php");
//Check security for hackers.
$security = new Security();
$security->checkuri();
$user = new User();
$misc = new Misc();
$show = new Show();
?>
</code></pre>
<p>And in my act.php I write code like this:</p>
<pre><code>if(isset($_GET['act']) & $_GET['act'] == "lostpass"){
if(isset($_SESSION['username'])){
$show->error("U bent al ingelogd met een bestaand account en u kunt uw wachtoowrd dus gewoon aanpassen op de aanpas pagina.");
}else{
include("view/lostpass.php");
}
}
</code></pre>
<p>The files in view contain mostly html code with an occasional while for tables.</p>
<p>So how is this structure? </p>
<p>Is it good or unbelievably bad? (I want to stay away from stuff like Smarty because I want my own model for this kind of stuff and I'm still learning).</p>
<p>Extra stuff: </p>
<p>This is my Misc class: </p>
<pre><code><?php
class Misc{
function check_email($email) {
// First, we check that there's one @ symbol,
// and that the lengths are right.
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
?'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
?([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
}
?>
</code></pre>
<p>It's just for stuff that's pretty annoying to fully put into everything each time I need it.</p>
<p>Security: </p>
<pre><code><?php
/**
* @author Jeffro
* @copyright 2011
*/
class Security{
var $privatekey = "thisshouldgoinaconfigfileaswell";
function mcryptexists()
{
if (function_exists("mcrypt_encrypt")){
return true;
}else{
return false;
}
}
function sslactive()
{
if ($_SERVER['HTTPS']) {
return true;
}else{
return false;
}
}
function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->privatekey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->privatekey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
?>
</code></pre>
<p>That's from my new project btw. (Plesk API system)</p>
<p>And here is my show class:</p>
<pre><code> <?php
class show{
function header(){
include("view/header.php");
}
function menu(){
include("view/menu.php");
}
function footer(){
include("view/footer.php");
}
function error($message){
echo $message;
$this->footer();
die();
}
}
?>
User Class:
<?php
class User{
private $database;
function exists($user){
$this->database->connect();
if($result = $this->database->resultquery("SELECT * FROM users WHERE got_username='" . $user . "'")) {
$count = mysqli_num_rows($result);
if($count > 0){
return true;
}else{
return false;
}
}
}
function isfriend($user, $friend){
$this->database->connect();
if($result = $this->database->resultquery("SELECT * FROM friends INNER JOIN users ON friends.user_id = users.user_id WHERE users.got_username='" . $user . "' AND friends.friend_id='" . $friend . "'")) {
$count = mysqli_num_rows($result);
if($count > 0){
return true;
}else{
return false;
}
}
}
function addfriend($username, $friend){
$this->database->connect();
$user = $this->getuser($username);
$result = $this->database->insertquery("INSERT INTO friends (user_id, friend_id) VALUES ('" . $user['user_id'] . "', '" . $friend . "')");
return $result;
}
function delfriend($username, $friend){
$this->database->connect();
$user = $this->getuser($username);
$result = $this->database->insertquery("DELETE FROM friends WHERE user_id = '" . $user['user_id'] . "' AND friend_id = '" . $friend . "'");
return $result;
}
function updateuser($got_username, $eu_username, $us_username, $user_client, $play_ranked, $user_email, $user_password, $user_password_check, $comment, $ip, $date){
$this->database->connect();
$result = $this->database->insertquery("
UPDATE users SET EU_username='$eu_username', US_username='$us_username', user_client='$user_client', plays_ranked='$play_ranked', comment='$comment', user_email='$user_email', user_password='" . sha1($user_password) . "', last_login='$date', last_ip='$ip'
WHERE GoT_username='$got_username'");
return $result;
}
function updateusernopass($got_username, $eu_username, $us_username, $user_client, $play_ranked, $user_email, $comment, $ip, $date){
$this->database->connect();
$result = $this->database->insertquery("
UPDATE users SET EU_username='$eu_username', US_username='$us_username', user_client='$user_client', plays_ranked='$play_ranked', comment='$comment', user_email='$user_email', last_login='$date', last_ip='$ip'
WHERE GoT_username='$got_username'");
return $result;
}
function register($got_username, $eu_username, $us_username, $user_client, $play_ranked, $user_email, $user_password, $user_password_check, $comment, $ip, $date){
$result = $this->database->insertquery("
INSERT INTO users (GoT_username, EU_username, US_username, user_client, plays_ranked, comment, user_email, user_password, reg_date, last_login, last_ip)
VALUES ('$got_username', '$eu_username', '$us_username', '$user_client', '$play_ranked', '$comment', '$user_email', '". sha1($user_password) ."', '$date', '$date', '$ip')");
return $result;
}
function getusers(){
$this->database->connect();
$query = "SELECT * FROM users ORDER BY user_id DESC";
$result = $this->database->resultquery($query);
$array = array();
while($value = mysqli_fetch_array($result))
{
$array[] = $value;
}
return $array;
}
function inserthash($email, $hash){
$this->database->connect();
$query = "UPDATE users SET user_hash='$hash' WHERE user_email='$email'";
$result = $this->database->insertquery($query);
return $result;
}
function updatepassword($hash, $password){
$this->database->connect();
$password = sha1($password);
$query = "UPDATE users SET user_password='$password' WHERE user_hash='$hash'";
$this->database->insertquery("UPDATE users SET user_hash='' WHERE user_hash='$hash'");
$result = $this->database->insertquery($query);
return $result;
}
function existsbyemail($email){
$this->database->connect();
$query = "SELECT * FROM users WHERE user_email = '$email'";
$result = $this->database->resultquery($query);
$count = mysqli_num_rows($result);
if($count > 0){
return true;
}else{
return false;
}
}
function getuserbyemail($email){
$this->database->connect();
$query = "SELECT * FROM users WHERE user_email = '$email'";
$result = $this->database->resultquery($query);
$array = mysqli_fetch_array($result);
return $array;
}
function getuser($username){
$this->database->connect();
$query = "SELECT * FROM users WHERE GoT_username = '$username'";
$result = $this->database->resultquery($query);
$array = mysqli_fetch_array($result);
return $array;
}
function login($username, $password){
$this->database->connect();
$query = "SELECT * FROM users WHERE GoT_username = '$username' AND user_password = '". sha1($password) . "'";
$result = $this->database->resultquery($query);
$count = mysqli_num_rows($result);
if($count > 0){
return true;
}else{
return false;
}
}
function logout(){
unset($_SESSION['GoT_username']);
unset($_SESSION['users_password']);
}
public function __construct(){
$this->database = new Database();
}
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T13:51:36.463",
"Id": "2189",
"Score": "0",
"body": "Saw your comment about indenting 4 spaces to get it into a code block. Just paste it next time, highlight the code, and hit the little 101010 button. It'll auto-indent it the 4 spaces for you."
}
] | [
{
"body": "<p>That's a good split to start off with, although I strongly encourage you to place your database conf file outside the public html area on your server.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T15:04:12.267",
"Id": "2191",
"Score": "0",
"body": "Good point, will do but I guess this depends on your host though."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T15:58:53.133",
"Id": "2223",
"Score": "0",
"body": "If the config file is a php file anyway, and is non-writable... why should it be outside public html? I have yet to see a framework that does this in php."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T16:50:34.713",
"Id": "2225",
"Score": "0",
"body": "@SeanJA Most installations put them all together in the public area for convenince, but many still recommend putting it in a safer area of the webserver. It's just an extra measure of safety for the unlikely possibility that the server stops processing php files correctly and instead allows remote users to read them, and the unlikely possibility that some attacker gains access to public_html, through FTP for instance. As unlikely as these events are, it's still a measure of safety that easy to implement, and to get in the habit of implementing."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T06:41:43.367",
"Id": "2232",
"Score": "0",
"body": "Anyone got more critic on the content?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T14:56:59.980",
"Id": "1248",
"ParentId": "1247",
"Score": "3"
}
},
{
"body": "<p>The only thing I see so far is that you have high <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29\" rel=\"nofollow\">Coupling</a> between the <code>Database</code> class and the location of the config file. What you should do is either:</p>\n\n<ul>\n<li>Create a config class that handles config parsing and setting</li>\n<li>Or, at minimum, load the config file somewhere else</li>\n</ul>\n\n<p>In both cases you will need to pass the parts that matter to the <code>Database</code> constructor. This reduces <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29\" rel=\"nofollow\">Coupling</a> which, in turn, reduces the amount of rewrite needed during <a href=\"http://framework.zend.com/manual/en/zend.config.html\" rel=\"nofollow\">refactoring</a>.</p>\n\n<p>There is little more I can offer except questions. For example, what is <code>Security</code> doing? Is there only the one function? What else is declared in it? The same goes for <code>Misc</code>. Both of these classes sound like they don't really belong and are classes for the sake of being classes.</p>\n\n<p><strong>EDIT</strong></p>\n\n<blockquote>\n <p>... the config class sounds interesting. Do you have any good places where I should start looking for a decent way?</p>\n</blockquote>\n\n<p>The <a href=\"http://framework.zend.com/manual/en/zend.config.html\" rel=\"nofollow\">Zend_Config</a> documentation, part of the <a href=\"http://framework.zend.com/\" rel=\"nofollow\">Zend Framework</a>, would probably be a good place to see how people are using something like this.</p>\n\n<blockquote>\n <p>This is my Misc class:</p>\n</blockquote>\n\n<p>You could keep this I suppose, but <code>Misc</code> is a poor name for it. Calling some thing <code>Misc</code> is just asking for disorganization. If you really want this to be a function, and you can support PHP 5.3, I would wrap this in a <a href=\"http://us.php.net/namespace\" rel=\"nofollow\"><code>namespace</code></a> and treat the <code>namespace</code> similar to what most people would call a <a href=\"http://en.wikipedia.org/wiki/Modular_programming\" rel=\"nofollow\">module</a>.</p>\n\n<p><em>Example:</em></p>\n\n<pre><code><?php\nnamespace Utilities\n{\n function validateEmail( $email )\n {\n // Code\n }\n}\n</code></pre>\n\n<p>However, you should really consider refreshing yourself on the PHP documentation, specifically the newer stuff that's been added since 4.0. A perfect example of this is the use of the <a href=\"http://p://us3.php.net/filter\"><code>Filter</code></a> extension. In your case, <code>FILTER_VALIDATE_EMAIL</code> will do wonders.</p>\n\n<blockquote>\n <p>Security:</p>\n</blockquote>\n\n<p>This class, I won't really comment on because I'm not sure the use case or need. I'll assume it is necessary as is.</p>\n\n<p>Similar to <code>Database</code> you have high <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29\" rel=\"nofollow\">Coupling</a> by putting the private key directly into the class. Depending on the needs of the key, it could exist in a config file and be treated just like the <code>Database</code> config attributes. On initialization, you would pass the config var for <code>passkey</code> into <code>Security::__constructor</code>.</p>\n\n<p>Doing so means that you could have a different <code>passkey</code> per user instead of a single passkey. Expanding this to a public+private key system in the future would also be easy (just add another parameter).</p>\n\n<blockquote>\n <p>User:</p>\n</blockquote>\n\n<p>This class is also plagued with high <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_science%29\" rel=\"nofollow\">Coupling</a> because of the self loading of <code>Database</code>. There are a few ways to handle <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">dependency injection</a> and I'm not going to sway you either way on this matter. However, I'd suggest you spend some time looking through the many articles your favorite search engine will provide (or <a href=\"http://www.bing.com/search?q=dependency+injection+in+PHP\" rel=\"nofollow\">Bing! and decide...lol</a>).</p>\n\n<p>I would also keep from naming functions in all lower case. It is common for people to name functions either in <a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow\">CamelCase</a> or underlines <code>_</code> between words. Not doing so can impact readability.</p>\n\n<p>Aside form that, this class is the first I've seen you provide that is acting as a Model (thinking in terms of <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow\">MVC</a>). That's a good thing, so nice job. I would expand your understanding of <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow\">MVC</a> if this is the path you are headed for so that you don't fall into many of the common pitfalls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T18:45:38.177",
"Id": "2271",
"Score": "0",
"body": "Thank you for your thoughts, the config class sounds interesting. Do you have any good places where I should start looking for a decent way?\n\nI also added more classes for review including the ones you asked for :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T19:14:24.430",
"Id": "2272",
"Score": "0",
"body": "@Jeffro, I've updated my answer based on the information you have supplied."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T18:22:23.083",
"Id": "1295",
"ParentId": "1247",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T12:28:45.490",
"Id": "1247",
"Score": "5",
"Tags": [
"php",
"classes"
],
"Title": "Splitting code, am I doing it right?"
} | 1247 |
<p>I need to subclass <code>UIButton</code>, however the design of <code>UIButton</code> makes this really painful. This is because to create a button you really need to call:</p>
<pre><code>[UIButton buttonWithType:UIButtonTypeRoundedRect]
</code></pre>
<p>So if I want to subclass I really need to do whatever it is this method does. However, it is not possible to set the buttons underlying type.</p>
<p>One option is to use something like decorator and subclass <code>UIButton</code> but have the actual button as an ivar and defer all property/method calls to this button. The problem here is that I then need to implement most of the <code>UIButton</code> interface (yawn).</p>
<p>What I have done is something a bit sneakier in my sub class. I have created this method:</p>
<pre><code>- (id) initWithType:(UIButtonType)buttonType
{
[super init];
actualButton = [[UIButton buttonWithType:buttonType] retain];
memcpy(self, actualButton, sizeof(UIButton));
self->isa = [ABDescriptorButton class];
return self ;
}
</code></pre>
<p>I know this is pretty unorthodox, but it works and is fairly clean in terms of code. What are the pitfalls I might have with this approach? </p>
| [] | [
{
"body": "<p>I think I've realised the problem myself. Memory management gets very confused because we are now essentially tracking two objects that are actually the same object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T16:44:50.030",
"Id": "1250",
"ParentId": "1249",
"Score": "1"
}
},
{
"body": "<p>You don't need to make an <code>initWithType:</code> method. Just override the <code>buttonWithType:</code> factory method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T08:34:08.810",
"Id": "3253",
"Score": "0",
"body": "The problem is I want to create instances of my subclass. If I override the factory method the only way I can create instances of my sub class to return is by calling initWithType on them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T09:03:39.893",
"Id": "3284",
"Score": "1",
"body": "Actually you are right. If I override + (UIButton *) buttonWithType:(UIButtonType)buttonType it actually returns an instance of the subclass. I assumed because the return was UIButton it would return a UIButton not the subclass. TIL that you can call [self alloc] in a factory method which will ensure that overridden classes get created with the subclass type. I guess I am not used to even being able to override static methods."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T22:49:11.383",
"Id": "1919",
"ParentId": "1249",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-11T15:41:49.007",
"Id": "1249",
"Score": "2",
"Tags": [
"object-oriented",
"objective-c",
"memory-management",
"constructor"
],
"Title": "Subclassing UIButton"
} | 1249 |
<p>I'm making a simple container class for fun and education, but my rebuilding/resizing method seems rather inefficient. Is there an easier way to do this?</p>
<pre><code>// If FromFront is true, cells should be added or
// subtracted from the front of the array rather than the back.
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Size = NewSize; // Size is used in other methods.
Datatype* TemporaryStorage = new Datatype[OldSize]; // Allocate space for the values to be preserved while a new main array is made.
for (std::size_t Index = 0; Index < OldSize; Index++) TemporaryStorage[Index] = BasePointer[Index]; // Copy values over to the temporary array.
delete[] BasePointer; // Delete the main array...
BasePointer = new Datatype[NewSize]; // ...And rebuild it with the appropriate size.
for (std::size_t Iteration = 0; (Iteration < OldSize) && (Iteration < NewSize); Iteration++)
{
std::size_t BasePointerIndex = Iteration;
std::size_t TemporaryStorageIndex = Iteration;
if (FromFront) // We need to take special measures to give the indices offsets.
{
if (NewSize > OldSize) BasePointerIndex += (NewSize - OldSize);
else TemporaryStorageIndex += (OldSize - NewSize);
}
BasePointer[BasePointerIndex] = TemporaryStorage[TemporaryStorageIndex]; // Copy values from the temporary array to the new main array.
}
delete[] TemporaryStorage; // Finally, delete the temporary storage array.
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T18:41:52.283",
"Id": "2193",
"Score": "0",
"body": "I must be missing something...why are you even using a temporary array?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T20:00:38.553",
"Id": "2194",
"Score": "1",
"body": "@Mark Probably because I'm stupid."
}
] | [
{
"body": "<pre><code>void Rebuild(std::size_t NewSize, bool FromFront = false)\n{\n const std::size_t OldSize = Size;\n\n Datatype* NewStorage = new Datatype[NewSize]; \n</code></pre>\n\n<p>Rather then creating a temporary array and copying the existing data into it, just create the new array and copy into that.</p>\n\n<pre><code> int CopyLength = std::min(OldSize, NewSize);\n</code></pre>\n\n<p>We start by determining how many elements we will actually copy</p>\n\n<pre><code> if( FromFront )\n {\n std::copy(BasePointer + OldSize - CopyLength, BasePointer + OldSize,\n NewStorage + NewSize - CopyLength);\n }\n else\n {\n std::copy(BasePointer, BasePointer + CopyLength, NewStorage);\n }\n</code></pre>\n\n<p>I use std::copy to avoid having to write a copying for loop myself. </p>\n\n<pre><code> delete[] BasePointer; // Delete the main array...\n BasePointer = NewStorage;\n Size = NewSize; // Size is used in other methods.\n</code></pre>\n\n<p>delete the current array and replace it with my new array</p>\n\n<pre><code>}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T11:39:58.190",
"Id": "2221",
"Score": "1",
"body": "std::copy further can actually be extra smart and copy in a more efficient way if the data type supports it (something like memcpy for primitive types)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T19:12:57.220",
"Id": "1253",
"ParentId": "1252",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "1253",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T18:27:55.153",
"Id": "1252",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"classes"
],
"Title": "Simplifying a Resizing Method"
} | 1252 |
<pre><code>#include<stdafx.h>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
string temp[10];
void extract(char * c)
{
int ind = 0;
//char *temp = (char *)malloc(sizeof(char));
while(*c!= NULL)
{
if(*c!= ' ') // read all chars in a word and store in temp.
{
temp[ind]= temp[ind] + *c;
c++;
}
else if(*c== ' ') // reached end of word
{
c++;
ind++;
}
}
int length = sizeof(temp)/sizeof(temp[0]);
printf("The reversed string is");
for(int i=length;i>=0;i--)
{
cout<<temp[i];// not able to print it with printf statement
}
}
void main()
{
char *c = "seattle is good";
extract(c);
}
</code></pre>
<p>This should print the sentence in reverse order . Input is "seattle is good"
Output for the above will be "good is seattle"
I have 2 questions ,
1. I am using string array here with size of 10. How can I make it dynamic?
2. For some reason the printf("%s",temp[i]) was not giving me correct results(At the very end of extract method). I then used cout and it was fine. Any ideas why? Am I doing something silly?</p>
<p>Algorithm Description: </p>
<ul>
<li>Take the input string as char array.</li>
<li>Extract words from the string by looking for empty space. </li>
<li>Store each word in a temp string array.
temp[0] = seattle
temp[1] = is
temp[2] = good</li>
<li>Then loop backwards through this temp array and print contents.</li>
</ul>
| [] | [
{
"body": "<h3>In response to your specific questions:</h3>\n\n<ol>\n<li>Use a vector. Using a vector you can just append to the end and it will resize itself as necessary.</li>\n<li>You can not use <code>printf</code> with <code>string</code>s as <code>printf</code> is a C function and does not know C++'s <code>string</code>s. Either way you should generally avoid <code>printf</code> in C++ code.</li>\n</ol>\n\n<hr>\n\n<h3>General notes on your code:</h3>\n\n<pre><code>#include<stdafx.h>\n#include<stdio.h>\n#include<stdlib.h>\n</code></pre>\n\n<p>The correct way to include C header files in C++ is to use <code>#include <cheadername></code>, not <code>#include <headername.h></code>. Further you should avoid C-functions when there are good C++ alternatives and you should generally not mix C's stdio with C++'s iostream. In this particular program I do not believe you need any of the C headers you include.</p>\n\n<hr>\n\n<pre><code>string temp[10];\n</code></pre>\n\n<p>I don't see any reason to have your global storage as a global variable. You should move it as a local variable inside the <code>extract</code> method. And as I already said, you should use a <code>vector</code> instead of a C array.</p>\n\n<p>Also <code>temp</code> is a bad variable name.</p>\n\n<hr>\n\n<pre><code>void extract(char * c)\n</code></pre>\n\n<p>Don't mix <code>char*</code>s and <code>string</code>s unless necessary. In this case you can use <code>string</code>s all the way, so you should define <code>extract</code> with <code>const string& sentence</code> as an argument (note that <code>sentence</code> is also a more descriptive name than <code>c</code>).</p>\n\n<p>Further it seems that your <code>extract</code> function is doing too much work: it's extracting words from the sentence into an array, and then printing it in reverse. These two separate steps should be done by two functions: <code>extract</code> (or maybe <code>sentence_to_words</code> which is more descriptive) and <code>print_in_reverse</code>.</p>\n\n<p>You might even want to use 3 steps instead: extract the words, reverse them, then print them. This way your IO code is completely separate from any logic, which is always good. As a bonus point C++ already has a built-in function to reverse an array or vector, so no additional work for you.</p>\n\n<p>Either way you'd need to change your <code>extract</code> function to either return the extracted words rather than <code>void</code> or take a vector into which to store the extracted words as an argument (by reference).</p>\n\n<hr>\n\n<pre><code>//char *temp = (char *)malloc(sizeof(char));\n</code></pre>\n\n<p>This code is commented out anyway (and doesn't do anything sensible from the looks of it), but as a general principle I want to point out that there's rarely a reason to use <code>malloc</code> over <code>new</code> in C++.</p>\n\n<hr>\n\n<pre><code>int ind = 0;\nwhile(*c!= NULL)\n{\n if(*c!= ' ') // read all chars in a word and store in temp.\n {\n temp[ind]= temp[ind] + *c;\n c++;\n\n }\n else if(*c== ' ') // reached end of word\n {\n c++;\n ind++;\n }\n}\n</code></pre>\n\n<p>Using a vector you can get rid of <code>ind</code> as you can just <code>push_back</code> into the vector.</p>\n\n<p>Further if you use <code>string</code>s, you can simplify this part by using <code>find</code> to find the next space and <code>substr</code> take the substring up to that space.</p>\n\n<hr>\n\n<pre><code>int length = sizeof(temp)/sizeof(temp[0]);\n</code></pre>\n\n<p>Note that this will only ever tell you the size of an array if the array's size is known at compile time (which is more or less equivalent to: \"spelled out in the code\"). So if you want the size of the array to be dynamic, you can't use this. If you use a vector, you can just use <code>temp.size()</code>.</p>\n\n<hr>\n\n<pre><code>printf(\"The reversed string is\");\n</code></pre>\n\n<p>As I already said, you shouldn't mix <code>stdio</code> and <code>iostream</code>. There is no reason to use <code>printf</code> here.</p>\n\n<hr>\n\n<pre><code>void main()\n</code></pre>\n\n<p>The correct return value for <code>main</code> is <code>int</code>, not <code>void</code>.</p>\n\n<hr>\n\n<pre><code>char *c = \"seattle is good\";\n</code></pre>\n\n<p>Again this should just be <code>string sentence(\"seattle is good\");</code>. No reason to use <code>char*</code>.</p>\n\n<hr>\n\n<p>If I were to write this program, I might do it like this:</p>\n\n<pre><code>#include <string>\n#include <iostream>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::reverse;\n\n// Splits a sentence by spaces into a vector of words\nvoid extract(const string& sentence, vector<string>& words)\n{\n size_t pos = 0;\n while(pos != string::npos)\n { \n // Find position of next space\n int next_space = sentence.find(\" \", pos);\n // Store everything up to next space in the words vector\n words.push_back( sentence.substr(pos, next_space - pos));\n\n // Continue at the next character which is not a space.\n pos = sentence.find_first_not_of(\" \", next_space);\n }\n}\n\n// Prints the strings in the vector separated by spaces\nvoid print_strings(const vector<string>& strings)\n{\n for(size_t i = 0; i < strings.size(); i++) {\n cout << strings[i] << \" \";\n }\n cout << endl;\n}\n\nint main()\n{\n string sentence(\"seattle is good\");\n vector<string> words;\n extract(sentence, words);\n reverse(words.begin(), words.end());\n print_strings(words);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T00:24:04.920",
"Id": "2198",
"Score": "0",
"body": "Am trying to see if it is possible to do the same without the temp variable. I wanted to try a inplace replacement and I have this algorithm in mind. Algorithm: 1. Keep a start and end index. Start will be 0 and end will be length of the input string - 1."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T16:09:31.183",
"Id": "2207",
"Score": "0",
"body": "Actually, it should be `string sentence(\"seattle is good\");` No point in having it constructed and then assigning to it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-28T04:00:15.437",
"Id": "436770",
"Score": "0",
"body": "FWIW, `stdafx.h` is not even a C header."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-11T22:50:48.670",
"Id": "1255",
"ParentId": "1254",
"Score": "12"
}
},
{
"body": "<p>An alternate iterative solution is as follows. This might not be much of an improvement over the more imperative approach above, still a different algorithm might be good to learn.</p>\n\n<p>A simple function that prints out a word that starts from the current character pointer. We loop and print till we get a end-of-string ('\\0') or a blank:</p>\n\n<pre><code>#include <iostream>\n\nvoid print_word(const char* x) {\n while (*x != ' ' && *x != '\\0'){\n std::cout << x[0];\n x++;\n }\n std::cout << \" \";\n}\n</code></pre>\n\n<p>The chief function, that operates from the first letter of a word:</p>\n\n<pre><code>void iterate_words(const char* x) {\n</code></pre>\n\n<p>We remember where this word has started at pointer x.</p>\n\n<pre><code> const char *a = x;\n</code></pre>\n\n<p>We start looking for the start position of the next word (or rest of the sentence). And yes, if the string ends in the meantime, we don't need that position. We just set a flag <code>lastword</code> and exit.</p>\n\n<pre><code> bool islastword = 0;\n\n while (*a != ' ') {\n if (*a == '\\0') {\n islastword = 1;\n break;\n }\n a++;\n }\n</code></pre>\n\n<p>Now, we have the position of our current word and rest of the sentence. If we print this word, and then call up our function <code>iterate_words</code> over rest of the sentence, we shall print the sentence in its original form. But, if we do the function call first, then only after the next word has been printed shall we print the current word, i.e. in reverse!</p>\n\n<pre><code> if (!lastword) iterate_words(a + 1);\n print_word(x);\n}\n\nint main() \n{\n iterate_words(\"hello world\");\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-18T13:09:55.687",
"Id": "117143",
"ParentId": "1254",
"Score": "3"
}
},
{
"body": "<p>why char ? use string \n,use stack or vector to push contents of the word after that read it in reverse order</p>\n\n<pre><code> #include<vector>\n std::string word =\"i dont know what to do\";\n std::<vector> temp;\n for(size_t i=0;i<=word.length();i++)\n {\n temp.push_back(word[i]);\n }\n //for getting in reverse order\n for(size_t j=word.length();j<=0;j--)\n std::cout<<temp[j];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T18:44:23.563",
"Id": "241093",
"ParentId": "1254",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-11T22:08:19.547",
"Id": "1254",
"Score": "4",
"Tags": [
"c++",
"array"
],
"Title": "Reverse a word using string manipulation"
} | 1254 |
<p>I have developed an application that interacts with IBM ClearQuest. The problem is that when I run everything locally, such as, run the webservice local and then ASP page local, everything is at the speed I expect. When I post the webservice (precompiled) to the server and run the web page through the server, the call to the webmethod takes at least 10x the amount of time it should. I don't know why this is happening. I made a console application that has the function in question and executes it on the server and locally, and they both return the same amounts of time (roughly). It's just when I move to executing via the webmethod that everything grinds to a snails pace.</p>
<p>Any ideas? This happens every time not just on the first call.</p>
<p>Maybe a code review might help here?</p>
<p><strong>WebMethod (VB):</strong></p>
<pre class="lang-vb prettyprint-override"><code>Public Function RetrieveQueryResults(ByRef cqSession As ClearQuestOleServer.Session, _
ByVal sqlStmt As String) As List(Of SearchResultsSingleIssue)
Dim numCols As Integer, status As Integer, columnIdx As Integer
Dim numRows As Integer
Dim rowContents As String = ""
Dim colValue As New Object
Dim colLabel As New Object
Dim allitems As New List(Of SearchResultsSingleIssue)
Dim results As New SearchResultsSingleIssue
Dim cqResultSet As ClearQuestOleServer.OAdResultset
cqResultSet = cqSession.BuildSQLQuery(sqlStmt)
cqResultSet.Execute()
' Get the number of columns returned by the query.
numRows = 0
numCols = cqResultSet.GetNumberOfColumns
status = cqResultSet.MoveNext
' Collect query results.
Do While status = AD_SUCCESS
results = New SearchResultsSingleIssue
numRows = numRows + 1
For columnIdx = 1 To numCols
colLabel = cqResultSet.GetColumnLabel(columnIdx)
colValue = cqResultSet.GetColumnValue(columnIdx)
'Make sure that we dont pass along a null reference
If colValue = Nothing Then
colValue = ""
End If
Select Case colLabel
Case "ID"
results.IssueID = colValue
Case "HEADLINE"
results.Headline = colValue
Case "NAME"
results.State = colValue
Case "OE_CONTACT"
results.OEContact = colValue
Case "DESCRIPTION"
results.Further_Description = colValue
Case "PRODUCT_NAME"
results.Product_Name = colValue
Case "FUNCTIONAL_AREA"
results.Functional_Area = colValue
Case "SUBTOPIC"
results.Subtopic = colValue
Case "FOUND_VERSION"
results.Found_In = colValue
Case "SCHEDULED_VERSION"
results.Scheduled_For = colValue
Case "SYMPTOMS"
results.Symptoms = colValue
Case "AFFECTED_SYSTEMS"
results.Affected_System_Types = colValue
Case "ISSUE_TYPE"
results.Issue_Type = colValue
Case "ASSIGNED_TO"
results.Assigned_Developer = colValue
Case "TESTED_BY"
results.Assigned_Tester = colValue
Case "BUILT_VERSION"
results.Built_In = colValue
Case "TESTED_VERSION"
results.Tested_In = colValue
Case "NOTES_LOG"
results.Notes_Log = colValue
Case "CUSTOMER_SEVERITY"
results.Severity = colValue
Case "PRIORITY"
results.Priority = colValue
End Select
Next columnIdx
' Add the query row result to the compiled list of all rows.
allitems.Add(results)
status = cqResultSet.MoveNext
Loop
Return allitems
End Function
</code></pre>
<p><strong>Local Windows Application Method (C#):</strong></p>
<pre><code>private void button2_Click(object sender, EventArgs e)
{
start = DateTime.Now.TimeOfDay.Seconds;
int numCols = 0;
int status = 0;
int columnIdx = 0;
int numRows = 0;
string rowContents = "";
string colValue;
string colLabel;
List<SearchResultsSingleIssue> allitems = new List<SearchResultsSingleIssue>();
SearchResultsSingleIssue results = new SearchResultsSingleIssue();
ClearQuestOleServer.OAdResultset cqResultSet = default(ClearQuestOleServer.OAdResultset);
cqResultSet = (ClearQuestOleServer.OAdResultset)ClearQuestSession.BuildSQLQuery(sqlStatement);
cqResultSet.Execute();
// Get the number of columns returned by the query.
numRows = 0;
numCols = cqResultSet.GetNumberOfColumns();
status = cqResultSet.MoveNext();
// Collect query results.
while (status == 1)
{
results = new SearchResultsSingleIssue();
numRows = numRows + 1;
for (columnIdx = 1; columnIdx <= numCols; columnIdx++)
{
colLabel = (string)cqResultSet.GetColumnLabel(columnIdx);
colValue = (string)cqResultSet.GetColumnValue(columnIdx);
//Make sure that we dont pass along a null reference
if (colValue == null)
{
colValue = "";
}
switch (colLabel)
{
case "ID":
results.IssueID = colValue;
break;
case "HEADLINE":
results.Headline = colValue;
break;
case "NAME":
results.State = colValue;
break;
case "OE_CONTACT":
results.OEContact = colValue;
break;
case "DESCRIPTION":
results.Further_Description = colValue;
break;
case "PRODUCT_NAME":
results.Product_Name = colValue;
break;
case "FUNCTIONAL_AREA":
results.Functional_Area = colValue;
break;
case "SUBTOPIC":
results.Subtopic = colValue;
break;
case "FOUND_VERSION":
results.Found_In = colValue;
break;
case "SCHEDULED_VERSION":
results.Scheduled_For = colValue;
break;
case "SYMPTOMS":
results.Symptoms = colValue;
break;
case "AFFECTED_SYSTEMS":
results.Affected_System_Types = colValue;
break;
case "ISSUE_TYPE":
results.Issue_Type = colValue;
break;
case "ASSIGNED_TO":
results.Assigned_Developer = colValue;
break;
case "TESTED_BY":
results.Assigned_Tester = colValue;
break;
case "BUILT_VERSION":
results.Built_In = colValue;
break;
case "TESTED_VERSION":
results.Tested_In = colValue;
break;
case "NOTES_LOG":
results.Notes_Log = colValue;
break;
case "CUSTOMER_SEVERITY":
results.Severity = colValue;
break;
case "PRIORITY":
results.Priority = colValue;
break;
}
}
// Add the query row result to the compiled list of all rows.
allitems.Add(results);
status = cqResultSet.MoveNext();
}
seconds = (DateTime.Now.TimeOfDay.Seconds - start);
label3.Text = seconds.ToString();
}
</code></pre>
<p>The code executes in about...6 seconds.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T19:52:58.103",
"Id": "2210",
"Score": "3",
"body": "Try profiling your application on server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T23:03:45.927",
"Id": "59517",
"Score": "0",
"body": "the first block of code is VB not C#"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-06T11:16:52.990",
"Id": "59520",
"Score": "1",
"body": "Code Review can only help when you have zeroed down upon the source of slowness. Please set up a profiler (such as http://www.jetbrains.com/profiler/) and get the results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T18:11:55.533",
"Id": "63919",
"Score": "0",
"body": "To eliminate the obvious - are you trying the web method multiple times? Is the web method 10x slower upon every execution when you do? It can take some time to spool up a worker process in IIS, so your results would be skewed if you do not take this into account."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:12:50.140",
"Id": "71423",
"Score": "0",
"body": "@Sean P: Also try using a logging framework like NLog or log4net and write output at each point. These frameworks can be configured to output at a millisecond level."
}
] | [
{
"body": "<p>This being the oldest <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a> <a href=\"https://codereview.meta.stackexchange.com/a/1511/23788\">zombie</a> on the site, I thought the code could use a bit of reviewing. I don't think I can answer the question about the weird performance issue though.</p>\n\n<blockquote>\n <p><strong>VB</strong></p>\n</blockquote>\n\n<h3>Declarations</h3>\n\n<p>You're not consistent with your declaration style:</p>\n\n<pre><code>Dim numCols As Integer, status As Integer, columnIdx As Integer\n</code></pre>\n\n<p>While this is correct and avoids the common mistake of only declaring a type to the last variable declared, I don't like multiple declarations on the same line. It's more readable when they're separated. These three being declared on the same line just seems arbitrary.</p>\n\n<p>The variables should be declared as close as possible to their usage, this block of declarations at the top of your method isn't helping readability either.</p>\n\n<p>This line serves no purpose and can be eliminated:</p>\n\n<pre><code>numRows = 0\n</code></pre>\n\n<h3>Loop</h3>\n\n<p>You're fetching the first result before iterating the result set:</p>\n\n<pre><code>status = cqResultSet.MoveNext\n\n' Collect query results.\nDo While status = AD_SUCCESS\n</code></pre>\n\n<p>And then your loop ends like this:</p>\n\n<pre><code> status = cqResultSet.MoveNext\nLoop\n</code></pre>\n\n<p>I think you can eliminate the <code>status</code> identifier along with the first check, and do this instead:</p>\n\n<pre><code>Do While cqResultSet.MoveNext = AD_SUCCESS\n</code></pre>\n\n<p>The loop doesn't need to enter the <code>Select Case</code> block if <code>colValue</code> is <code>Nothing</code> - I'm more of a C# guy so this could be wrong, but I think the <code>Continue</code> keyword could be used here to skip that iteration right there:</p>\n\n<pre><code>'Make sure that we dont pass along a null reference\nIf colValue = Nothing Then Continue\n</code></pre>\n\n<p>Not sure I like the <code>Select Case</code> here, and I'm not sure the looping over returned columns is buying you anything either. I don't know this API, but if this were ADO.NET I'd recommend you get the value for each column name, and assign it to <code>result</code> if that column name exists, like this (syntax is probably wrong, and C#-like, but you get the idea):</p>\n\n<pre><code>if (cqResultSet[\"ID\"] != null) results.IssueId = cqResultSet[\"ID\"].Value;\n</code></pre>\n\n<p>The point, is that you're naming all columns and all properties anyway, so the loop+switch isn't buying you anything except the need to now track what column index you're at.</p>\n\n<h3>Naming</h3>\n\n<p>I don't like the underscore in identifiers. Stick to PascalCase convention, be consistent. Also <code>results</code> would be a better name for <code>allItems</code> (<code>Return allItems</code> becomes <code>Return result</code>), and <code>result</code> would be a better name for <code>results</code> (<code>allItems.Add(results)</code> becomes <code>results.Add(result)</code>).</p>\n\n<p>If <code>AD_SUCCESS</code> is a status code, this naming makes me think it's a constant. However status codes are a suite of closely related constants, usually mutually exclusive - this looks like a job for an <code>Enum</code>.</p>\n\n<blockquote>\n <p><strong>C#</strong></p>\n</blockquote>\n\n<p>Most of the above also applies to the C# code. Both snippets do the same thing and the code roughly seems pretty equivalent, so I'm going to keep this review DRY and won't mention again to declare variables as close as possible to their usage ;)</p>\n\n<pre><code>while (status == 1)\n</code></pre>\n\n<p>What happened to the constant? Are magic numbers any less magical in C# than in VB?</p>\n\n<h3>Timing</h3>\n\n<p>You're timing your code the VB6 way, in both snippets. Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx\" rel=\"nofollow noreferrer\">StopWatch</a> class, which is much better at this kind of task (be it just for the <code>ElapsedMilliseconds</code> property!).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:16:31.500",
"Id": "71424",
"Score": "0",
"body": "+1 ! Also, possibly refactor the switch to a method like `ApplyValueToResult(SearchResultsSingleIssue result, string label, object value)` so the for loop is short and sweet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:30:35.023",
"Id": "71426",
"Score": "0",
"body": "@DominicZukiewicz thanks! I would actually eliminate the entire loop + switch by calling the columns by their name, if that's at all possible - like `if (cqResultSet[\"ID\"] != null) results.IssueId = cqResultSet[\"ID\"].Value;`... I don't like looping over columns, we're already looping over returned rows."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:41:45.283",
"Id": "71428",
"Score": "0",
"body": "Looping over rows and columns is fine. Its just a necessary evil with DB interaction at this lower level; it bloats code, but as long as its refactored with a clearer purpose, its good to do. *Ideally*, you'd use a dedicated class to do this, which abstracts the DB layer, but this question is about why the times are not correct, not how can the OP improve the code structure :-("
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T04:24:20.000",
"Id": "41532",
"ParentId": "1257",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-11T22:52:36.640",
"Id": "1257",
"Score": "5",
"Tags": [
"c#",
".net",
"vb.net"
],
"Title": "WebMethod slower on execution than Windows application of the same code"
} | 1257 |
<p>I'm trying to figure out a way to simplify implementing paged searching in sql server.</p>
<p>My restrictions are: </p>
<ol>
<li>has to be in a proc. </li>
<li>can't use dynamic sql.</li>
</ol>
<p>Here's my sample query:</p>
<pre><code>DECLARE @TenantId int
DECLARE @MemberStatusId int
DECLARE @SearchTerm varchar(50)
DECLARE @ColumnName varchar(30)
DECLARE @PageNum int
DECLARE @RecCount int
;
WITH RowPages AS (
SELECT TOP( @PageNum * @RecCount )
RowNumber = ROW_NUMBER() OVER( ORDER BY
CASE
WHEN @ColumnName = 'Name' THEN P.LastName
WHEN @ColumnName = 'PhoneNumber' THEN M.PhoneNumber
WHEN @ColumnName = '' THEN P.LastName
END ASC,
CASE
WHEN @ColumnName = 'DateAdded' THEN P.DateAdded
END DESC
),
TotalCount = COUNT(M.MemberId) OVER ( PARTITION BY NULL),
M.MemberId, M.ExternalId, M.PhoneNumber, P.FirstName, P.LastName, P.EmailAddress
FROM membership.Members M (nolock)
INNER JOIN core.Persons P (nolock) on (P.PersonId = M.MemberId)
WHERE (M.TenantId = @TenantId)
AND ((@MemberStatusId = 0) or (M.MemberStatusId = @MemberStatusId))
AND (
(@SearchTerm = '""')
OR (CONTAINS( (P.FirstName, P.LastName, P.EmailAddress), @SearchTerm))
)
)
SELECT TotalCount, MemberId, ExternalId, PhoneNumber,
FirstName, LastName, EmailAddress
FROM RowPages
WHERE RowNumber > ((@PageNum - 1) * @RecCount)
ORDER BY RowNumber
</code></pre>
<p>What this does is perform a paged search of a couple tables. You can pass in the page number and # records per page as well as the column to sort by and it has a full text search component. This is one of the simpler queries of this style we have.</p>
<p>What I'm trying to figure out is how to optimize this. The biggest costs in the execution plan are in regards to the full text search. There is a table value function [FullTextMatch] which has a cost of 100%. </p>
<p>Ideas?</p>
| [] | [
{
"body": "<p>It looks pretty good to me. With a cost of 100% on the <code>FullTextMatch</code>, I'd consider running this as a standard statement and hard code the variables <strong>just to see what the execution plan says.</strong> \nI do have one question though. Your case statement for <code>@ColumnName = 'DateAdded'</code>... doesn't this throw an error when <code>@ColumnName <> 'DateAdded'</code> as you end up with something like:</p>\n\n<pre><code>order by P.LastName asc, desc\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T16:59:21.350",
"Id": "2379",
"Score": "0",
"body": "Actually, no it doesn't throw an error. I'm not entirely sure how the parser figures it out, but that part works just fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-20T00:25:43.003",
"Id": "1354",
"ParentId": "1258",
"Score": "3"
}
},
{
"body": "<p>Interestingly, the SP2 to SQL 2008 R2 wacked my search queries. The part where I had <code>SELECT TOP( @PageNum * @RecCount )</code> now causes it to pull back random values.</p>\n\n<p>I've since done several things. First was that I got rid of the SQL full text search matching. It was ludicrously slow. Second, I removed the <code>TOP(@PageNum * @RecCount)</code> part and in the final select added <code>SELECT TOP(@RecCount) TotalCount, ...</code></p>\n\n<p>Seems fast and easy.</p>\n\n<p>Also, the following article talks about using a key seek method that appears to be very very fast: <a href=\"http://www.sqlservercentral.com/articles/paging/69892/\" rel=\"nofollow\">http://www.sqlservercentral.com/articles/paging/69892/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-12T15:52:24.740",
"Id": "23795",
"ParentId": "1258",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "23795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-11T23:24:00.897",
"Id": "1258",
"Score": "4",
"Tags": [
"sql",
"sql-server",
"search"
],
"Title": "SQL paged search results"
} | 1258 |
<p>What do you think about this code?</p>
<pre><code>#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
#include <ctime>
#include <cstdlib>
template < typename T >
vector < T > concatenate( vector < T > _a_, T piv, vector < T > _b_ )
{
vector < T > v_list;
v_list.insert( v_list.begin(), _a_.begin(), _a_.end() );
v_list.push_back( piv );
v_list.insert( v_list.end(), _b_.begin(), _b_.end() );
return v_list;
}
template < typename T >
vector< T > quick( vector< T > vec )
{
vector< T > v_less, v_greater, v_list;
vector< T > aux1, aux2;
typename vector < T >::const_iterator iter_Const;
if( vec.size() <= 1 )
return vec;
int piv = *(vec.end() - 1);
vec.pop_back();
for( iter_Const = vec.begin(); iter_Const != vec.end(); ++iter_Const )
{
if( *iter_Const < piv )
v_less.push_back( *iter_Const );
else
v_greater.push_back( *iter_Const );
}
return concatenate( quick( v_less ), piv, quick( v_greater ) );
}
int main() {
vector < int > lista;
srand( 1 );
cout << "VECTOR" << endl;
for( int i = 0; i < 10000; i++ )
{
lista.push_back( rand() % 100 );
cout << lista[i] << " | ";
}
cout << endl;
cout << "******" << endl;
cout << "QUICKSORT" << endl;
lista = quick( lista );
vector < int > :: const_iterator it;
for( it = lista.begin(); it != lista.end(); ++it )
cout << *it << " | ";
cout << endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T03:43:23.883",
"Id": "2199",
"Score": "0",
"body": "Sorry v_list shouldn't be there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-25T11:09:48.327",
"Id": "11146",
"Score": "0",
"body": "My heapsort beats it...............:)"
}
] | [
{
"body": "<p>If this is not just a learning exercise, I have to point out that C++ already has a sorting function in its standard library and in real code you should use that. So for the rest of this answer I'm going to assume that this is in fact just a learning exercise.</p>\n\n<p>Now first a note on the algorithm: Usually quicksort is implemented in-place for better performance. Even if you want a sorting function which does not modify its argument, it's quicker to just copy the argument and then run an in-place quicksort on the argument.</p>\n\n<p>Further you're creating a lot more copies of your vectors than you need to, even when using this choice of algorithm: Every time you pass a vector by value, it is copied. Every time you pass a vector, which you do not want to modify, you should rather pass it by const reference, so as not to create an unnecessary copy.</p>\n\n<p>On the same note <code>concatenate</code> also creates an unnecessary copy by returning the result vector by value. This can be avoided by passing an empty vector by non-const reference and filling that instead of using a return value.</p>\n\n<p>Lastly there is a bit of code duplication in your <code>main</code> function: You're printing a vector separated by pipes twice - once during its creation and once after sorting. I would define a helper function <code>print_vector</code>, which prints a vector separated by pipes, and call that twice: once after creating the vector and once after sorting it. This way the first printing will have to happen after the vector creation, not during, but that's okay as doing it during the creation gives very little performance benefit (if any) and having the creation be a separate step from printing the vector improves code cleanliness.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T13:21:04.550",
"Id": "1262",
"ParentId": "1259",
"Score": "3"
}
},
{
"body": "<p>To add to sepp's answer, there are also some other finer points worth mentioning:</p>\n\n<p>Considering the worse-case. Your current implementation always uses the last element of the vector as the pivot. The worse-case is easily triggered by feeding it a sorted/reversed sorted vector turning your quicksort into a O(n^2) selection sort.</p>\n\n<p>Your quicksort can offer more flexibility by just changing it to accept a starting and ending range to sort rather than just taking the vector directly. e.g. you might want to sort from elements x to y making up a subrange of vector rather than the entire vector.size().</p>\n\n<p>The basic steps for any quicksort implementation is this:</p>\n\n<ul>\n<li>Choose a pivot. </li>\n<li>Partition the\nelements around this pivot giving a\nlow partition and a high partition. </li>\n<li>Quicksort the lower partition.</li>\n<li>Quicksort the higher partition.</li>\n</ul>\n\n<p>With those steps in mind you can rewrite your quicksort so that the code is clearer, like so:</p>\n\n<pre><code>namespace practice{\n\ntemplate <typename T>\nT partition(const T &start, const T &end);\n\ntemplate <typename T>\nvoid quicksort(const T &start, const T &end)\n{\n // empty range?\n if(start == end) return;\n\n // start by partitioning the range to sort\n // and saving the pivot used.\n T pivot = partition(start, end);\n\n // now just sort the low and high partitions\n quicksort(start, pivot);\n quicksort(pivot + 1, end);\n}\n\n}\n</code></pre>\n\n<p>The real work is happening in partition so I'll leave that part for you to handle. As Sepp said though, one of the highlights of quicksort is that it can be performed in-place.</p>\n\n<p>To do that you need to know where the lower partition ends and the higher begins. You can keep track of that with an extra pointer variable, firsthigh(or alternatively lastlow). In your partition function your range will then have 3 parts: lower partition (start to firsthigh), higher partition(firsthigh to current_element) and the unprocessed range(current_element to end). As your partition function works through the range the unprocessed gets smaller obviously. If the current element belongs in the high partition do nothing and move to the next element. If it belongs in the low partition just swap with firsthigh. Increment firsthigh by one to maintain the invariant.</p>\n\n<p>Hopfully that's enough detail to help you rewrite your qsort better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T05:03:50.220",
"Id": "1279",
"ParentId": "1259",
"Score": "3"
}
},
{
"body": "<p>I caught a couple of stylistic issues.</p>\n\n<p>Having both worked on inherited code and had to debug my own code after a couple of years, my first comment is the total lack of comments in the code. What was clear to you at 1 am in the morning may make no sense after you wake up at 10 am. It may make even less sense when you have to debug it after 2 years.</p>\n\n<p>Consider at a minimum commenting your templates and method declarations. I would also suggest commenting your basic steps as well (see Victor T's response).</p>\n\n<p>The other issue may seem like a small thing, but I have seen it cause some serious problems, especially when people go into make \"quick fixes\" to existing code.</p>\n\n<p>Here's the genesis of the problem.</p>\n\n<p>The original code:</p>\n\n<pre><code>// ** do something **\nif (a.some_value < b.call_a_func(c))\n a.some_value = 3;\n// ** do something else **\n</code></pre>\n\n<p>The patched code:</p>\n\n<pre><code>// ** do something **\nif (a.some_value < b.call_a_func(c))\n a.some_value = 3;\n call_another_func(a);\n// ** do something else **\n</code></pre>\n\n<p>What the patched code was suppose to be:</p>\n\n<pre><code>// ** do something **\nif (a.some_value < b.call_a_func(c))\n{\n a.some_value = 3;\n call_another_func(a);\n}\n// ** do something else **\n</code></pre>\n\n<p>If the original developer had used braces around the 1 line condition, the bug in the patched code may not have been introduced.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T15:39:36.587",
"Id": "1285",
"ParentId": "1259",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1262",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-12T03:36:27.133",
"Id": "1259",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"sorting",
"reinventing-the-wheel",
"quick-sort"
],
"Title": "Quicksort application"
} | 1259 |
<p>I have the following code:</p>
<pre><code>print o
# {'actor_name': [u'Keanu Reeves', u'Laurence Fishburne', u'Carrie-Anne Moss', u'Hugo Weaving', u'Glor
# ia Foster', u'Joe Pantoliano', u'Marcus Chong', u'Julian Arahanga', u'Belinda McClory', u'Matt Doran
# '], 'played': [u'Neo (Thomas Anderson)', u'Morfeusz', u'Trinity', u'Agent Smith', u'Wyrocznia', u'Cy
# pher', u'Tank', u'Apoc', u'Switch', u'Mouse']}
li = list(o.itervalues())
for index, value in enumerate(li[0]):
print [value, li[1][index]]
# [u'Keanu Reeves', u'Neo (Thomas Anderson)']
# [u'Laurence Fishburne', u'Morfeusz']
# [u'Carrie-Anne Moss', u'Trinity']
# [u'Hugo Weaving', u'Agent Smith']
# [u'Gloria Foster', u'Wyrocznia']
# [u'Joe Pantoliano', u'Cypher']
# [u'Marcus Chong', u'Tank']
# [u'Julian Arahanga', u'Apoc']
# [u'Belinda McClory', u'Switch']
# [u'Matt Doran', u'Mouse']
</code></pre>
<p>I'm curious how I could write this thing in a more Pythonic way without losing its readability.</p>
| [] | [
{
"body": "<p>You're looking for <a href=\"http://docs.python.org/library/functions.html#zip\"><code>zip()</code></a>.</p>\n\n<pre><code>print zip(o['actor_name'], o['played'])\n</code></pre>\n\n<p>or to make it look like your output</p>\n\n<pre><code>for entry in zip(o['actor_name'], o['played']):\n print entry\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T10:58:57.773",
"Id": "1261",
"ParentId": "1260",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "1261",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-12T09:47:08.833",
"Id": "1260",
"Score": "4",
"Tags": [
"python"
],
"Title": "Merging two lists from dictionary. How to do this in a better way?"
} | 1260 |
<p>Is this the proper method for creating an OpenGL 3.3+ forward-compatible context?</p>
<pre><code>// Create window
WNDCLASSEX wc;
ZeroMemory( &wc, sizeof( wc ) );
wc.cbSize = sizeof( wc );
wc.lpfnWndProc = _eventHandler;
wc.hInstance = GetModuleHandle( NULL );
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hIconSm = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.lpszClassName = "OpenGL 3.3";
if ( !RegisterClassEx( &wc ) ) Error( "Failed to register window class!" );
if ( !( _window = CreateWindowEx( WS_EX_CLIENTEDGE, "OpenGL 3.3", "OpenGL 3.3", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, GetModuleHandle( NULL ), NULL ) ) )
Error( "Failed to create the window!" );
if ( !( _hdc = GetDC( _window ) ) ) Error( "Failed to retrieve device context!" );
// Choose pixel format
int pixelFormat;
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
if ( !( pixelFormat = ChoosePixelFormat( _hdc, &pfd ) ) ) Error( "Failed to find suitable pixel format!" );
if ( !SetPixelFormat( _hdc, pixelFormat, &pfd ) ) Error( "Failed to set pixel format!" );
// Create temporary context and make sure we have support
HGLRC tempContext = wglCreateContext( _hdc );
if ( !tempContext ) Error( "Failed to create temporary context!" );
if ( !wglMakeCurrent( _hdc, tempContext ) ) Error( "Failed to activate temporary context!" );
int major, minor; glGetIntegerv( GL_MAJOR_VERSION, &major ); glGetIntegerv( GL_MINOR_VERSION, &minor );
if ( major < 3 || minor < 2 ) Error( "OpenGL 3.2 is not supported!" );
// Create forward compatible context
int attribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, major,
WGL_CONTEXT_MINOR_VERSION_ARB, minor,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
PFNWGLCREATEBUFFERREGIONARBPROC wglCreateContextAttribsARB = (PFNWGLCREATEBUFFERREGIONARBPROC)wglGetProcAddress( "wglCreateContextAttribsARB" );
if ( !wglCreateContextAttribsARB ) Error( "Failed to find pointer to wglCreateContextAttribsARB function!" );
if ( !( _context = wglCreateContextAttribsARB( _hdc, 0, (UINT)attribs ) ) ) Error( "Failed to create forward compatible context!" );
// Remove temporary context and activate forward compatible context
wglMakeCurrent( NULL, NULL );
wglDeleteContext( tempContext );
if ( !wglMakeCurrent( _hdc, (HGLRC)_context ) ) Error( "Failed to activate forward compatible context!" );
// Show window
ShowWindow( _window, SW_SHOW );
UpdateWindow( _window );
</code></pre>
<p>It seems to work (gives GL_INVALID_OPERATION when using glBegin), but I just want to make sure this is the right way to go about it.</p>
| [] | [
{
"body": "<p>This <em>looks</em> right to me. I am a bit tired right now and usually use <a href=\"http://www.glfw.org/\" rel=\"nofollow\">GLFW</a>.</p>\n\n<p>You might be interested in <a href=\"http://www.opengl.org/wiki/Tutorial%3a_OpenGL_3.1_The_First_Triangle_%28C%2B%2B/Win%29\" rel=\"nofollow\">this page on the OpenGL wiki</a> describing setting up the context after 3.1 which is essentially the same work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T08:08:24.707",
"Id": "1377",
"ParentId": "1263",
"Score": "4"
}
},
{
"body": "<p>You're creating a core profile (WGL_CONTEXT_CORE_PROFILE_BIT_ARB) which means that all deprecated functionality will be unavailable. glBegin/glEnd was deprecated in OpenGL 3. The modern way to go is to use vertex buffer objects (VBOs) instead.</p>\n\n<p>You can create a compability context to get access to the old fixed function API (including glBegin/glEnd).</p>\n\n<p>For more information, see <a href=\"http://www.opengl.org/wiki/Core_And_Compatibility_in_Contexts\" rel=\"nofollow\">http://www.opengl.org/wiki/Core_And_Compatibility_in_Contexts</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T14:17:58.377",
"Id": "2492",
"Score": "0",
"body": "Yes, I tried calling glBegin to test the deprecation mechanism."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T15:46:17.113",
"Id": "440993",
"Score": "0",
"body": "In 3.1 even core profiles contain and allow the deprecated stuff. See the wiki link above. For 3.3, yes, the core flag should do."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T15:45:45.300",
"Id": "1386",
"ParentId": "1263",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T14:34:39.043",
"Id": "1263",
"Score": "9",
"Tags": [
"c++"
],
"Title": "OpenGL forward-compatible context creation on Windows"
} | 1263 |
<p>The title sucks, but it's really very simple - given an array and a starting element, cycle between one element above, below, then two element above, and below the starting element. For example: </p>
<pre><code>Start: 5
5 > 6 > 4 > 7 > 3 > 8 > 2 ...
</code></pre>
<p>It doesn't matter if the code initially start with the element above or below. To complicate things a little, when you reach the end or beginning of the array, the code should continue to pick valid array elements, instead of going into invalid positions:</p>
<pre><code>Start: 2
2 > 3 > 1 > 4 > 0 > 5 > 6 > 7 ...
</code></pre>
<p>This is the code I have. It works, but I don't really like the way to fulfil the second condition above, having that two lines repeated twice.</p>
<pre><code>var distance = 0;
while ((currentHeight + this.heights[index]) < height) {
sections.push(index);
currentHeight += this.heights[index];
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
if (index < 0 || index >= this.heights.length) {
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
}
}
</code></pre>
<p><code>distance</code> is the distance from the starting point, <code>index</code> holds the current position. The code cycles with these two lines: </p>
<pre><code>distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
</code></pre>
<p>and it resolves the invalid array position problem by simply rerunning those two lines if it finds an invalid array position. </p>
| [] | [
{
"body": "<p>First off, your code was a bit difficult to read, because you combined the algorithm you need with your functionality, that you didn't explain. It's not only easier for people helping you, but also yourself, if you try to separate your problem from the application.</p>\n\n<p>Your attempt was to calculate an index from the previous index. I instead created a function, that mapped a increasing index (0, 1, 2, 3, 4,...) to the targets (0, 1, -1, 2, -2,...). So we are looking for a function <code>f(i)</code> where <code>f(0) = 0</code>, <code>f(1) = 1</code>, <code>f(2) = -1</code>, <code>f(3) = 2</code>, etc.</p>\n\n<p>I came up with: <code>(i % 2 ? 1 : -1) * Math.floor( (i+1) / 2 )</code>. </p>\n\n<p>Now you just need a condition to skip new indexes outside your array. I came up with the following:</p>\n\n<pre><code>var yourArray = new Array(10);\nvar start = 2;\n\nvar i = 0;\nvar max = yourArray.length;\n\nwhile (max) {\n var newI = (i%2?1:-1) * Math.floor((i+1)/2) + start;\n if (newI >= 0 && newI < yourArray.length) {\n document.write( newI + \"<br>\");\n // do something with yourArray[newI];\n max--;\n }\n i++;\n}\n</code></pre>\n\n<p><s>My problem was how to decide when to stop the loop. For now i just loop over twice the length of the array. That will usually lead to some unnecessary iterations, but maybe someone can come up with a better solution, or there maybe a condition that comes from your application.</s> <strong>UPDATE:</strong> Found a solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T19:12:04.983",
"Id": "1269",
"ParentId": "1264",
"Score": "5"
}
},
{
"body": "<p>The sequence you describe is +1, -2, +3, -4, +5, -6, ... so my idea was to keep two mutating values</p>\n\n<pre><code>var step = 0;\nvar direction = 1;\n</code></pre>\n\n<p>where <code>step</code> is incremented and <code>direction</code> is negated</p>\n\n<pre><code>step++;\ndirection *= -1;\n</code></pre>\n\n<p>and are applied to the current index</p>\n\n<pre><code>index += step * direction;\n</code></pre>\n\n<p>each time through the loop. Otherwise, the code looks the same as RoToRa's solution (+1 for the formula, btw).</p>\n\n<pre><code>var yourArray = new Array(10);\nvar index = 2;\n\nvar step = 0;\nvar direction = 1;\nvar max = yourArray.length;\n\nwhile (max) {\n if (index >= 0 && index < yourArray.length) {\n document.write( index + \"<br>\");\n // do something with yourArray[index];\n max--;\n }\n step++;\n direction *= -1;\n index += step * direction;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T22:06:49.267",
"Id": "1273",
"ParentId": "1264",
"Score": "4"
}
},
{
"body": "<p>A much easier way of doing this is:</p>\n\n<pre><code>var myarray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];\nvar start = 8, step = 1, current = start+step;\nwhile (myarray[current]) {\n console.log(myarray[current]);\n current = (current>start) ? start-(current-start)-1 : start+(start-current);\n}\n</code></pre>\n\n<p>=> 10 ,7 ,11 ,6 ,12 ,5 ,13 ,4 ,14 ,3 ,15 ,2</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-01T09:48:47.167",
"Id": "1602",
"ParentId": "1264",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1269",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T17:11:02.237",
"Id": "1264",
"Score": "4",
"Tags": [
"javascript",
"array"
],
"Title": "Cycling between element above and below current array element"
} | 1264 |
<pre><code>$($(this).parent().parent().parent().parent().parent().parent().children()[0]).html()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T02:44:44.640",
"Id": "58826",
"Score": "2",
"body": "This question appears to be off-topic because it is about how bad the code is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:46:37.177",
"Id": "58838",
"Score": "0",
"body": "@Malachi I would say it's definitely lacking proper context, but if it weren't *stub code* I'd vote to leave open."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:50:05.363",
"Id": "58839",
"Score": "2",
"body": "This question appears to be off-topic because it is about stub code. See point 3 `Is it actual code from a project rather than pseudo-code or example code?` in our [Help Center](http://codereview.stackexchange.com/help/on-topic) for more details. Also could use a bit more context."
}
] | [
{
"body": "<pre><code>.parent().parent().parent().parent().parent().parent()\n</code></pre>\n\n<p>This can be much simplified by using <code>parents()</code> which returns an array, which you can just access with an index. I.e. you can replace the above with:</p>\n\n<pre><code>.parents()[5]\n</code></pre>\n\n<p>The upsides of this, besides being more concise, are that it the reader of your code can see which parent you're accessing without having to count the calls to <code>parent</code> and that if you ever need to access a different parent, you can just change the number instead of having to add or remove calls to <code>parent</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T12:51:09.043",
"Id": "2522",
"Score": "0",
"body": "For the record, the slightly more ‘jQuery’ way to do this would be `.parents().get(5)`. But obviously sepp2k’s suggestion is more efficient (no overhead because of an extra function call) and shorter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T23:19:23.373",
"Id": "23491",
"Score": "0",
"body": "You can also do stuff like this.\n`.parents('form :first');` first being immediate parent to last being outermost container."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T18:00:35.813",
"Id": "1266",
"ParentId": "1265",
"Score": "20"
}
},
{
"body": "<p>Besides what sepp2k said:</p>\n\n<p>Instead of accessing the DOM object of the first child and then rewrapping it in a jQuery object, you can use the method <code>.eq()</code> to access it directly.</p>\n\n<p>So instead of this:</p>\n\n<pre><code>$($(this)/* ... */.children()[0]).html()\n</code></pre>\n\n<p>Use this:</p>\n\n<pre><code>$(this)/* ... */.children().eq(0).html()\n</code></pre>\n\n<p>And there are possibly more ways to optimize it, if you show the HTML it's operating on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T19:27:59.183",
"Id": "2209",
"Score": "0",
"body": "Thanks, that was one of the things I was looking for, very helpful :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T22:11:53.223",
"Id": "2214",
"Score": "0",
"body": "Can you combine your answers into `$($(this).parents().eq(5).children().eq(0)).html()`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T11:34:13.833",
"Id": "2220",
"Score": "0",
"body": "Not quite. `$(this).parents().eq(5).children().eq(0).html()` See also Inaimathi's answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T18:28:46.517",
"Id": "1267",
"ParentId": "1265",
"Score": "10"
}
},
{
"body": "<p>This...is pretty bad. But there's no real way to tell how bad it has to be given other constraints. For instance, if this is a JS file meant to affect a page whose HTML you don't have control over, then you can't do <em>much</em> better than something like </p>\n\n<pre><code>$(this).parents(\":eq(5)\").children(\":eq(0)\").html()\n</code></pre>\n\n<p>If this is an element you have to access a lot, consider adding an id or class to it, then selecting by that.</p>\n\n<pre><code>$(\"#fifth-parent-first-child\").html() //or something descriptive\n</code></pre>\n\n<p>Again, if you don't have access to the HTML, you'll need to add it yourself at runtime</p>\n\n<pre><code>$(document).ready(\n function () {\n $(foo).parents(\":eq(5)\").children(\":eq(0)\").addClass(\"something-descriptive\")\n }\n);\n$(\".something-descriptive\").html()\n</code></pre>\n\n<p>Consider pasting some surrounding code for more insight.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T13:24:11.800",
"Id": "2239",
"Score": "1",
"body": "Applying a tag in the HTML is the best approach, and applying a tag dynamically is next. Specifying the number of parent elements as a number is fragile--your code will break if the page's structure is modified."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T17:42:08.750",
"Id": "2553",
"Score": "0",
"body": "Using `:eq(5)` as a selector is significantly more expensive then calling `.eq(5)` if your not doing complex composition always use the cheaper methods instead."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-01T15:34:43.637",
"Id": "2781",
"Score": "0",
"body": "@JoshEarl - I very much agree, I have had a lot of mysteries and headaches dealing with other's jQuery code which relies on the page structure."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T19:30:37.767",
"Id": "1270",
"ParentId": "1265",
"Score": "14"
}
},
{
"body": "<p><strong>1.</strong> Instead of doing so many <code>.parent()</code> calls, you can use <code>.parents()</code>:</p>\n\n<pre><code>$(this).parents(':eq(5)');\n</code></pre>\n\n<p><strong>2.</strong> You can use <code>.eq()</code> to get the n<sup>th</sup> occurrence of an element, you don't need to do <code>[0]</code> and pass it to jQuery again.</p>\n\n<pre><code>$($(this).parents(':eq(5)').children()[0]).html()\n</code></pre>\n\n<p>This is better:</p>\n\n<pre><code>$(this).parents(':eq(5)').children().eq(0).html();\n</code></pre>\n\n<p>Though jQuery has a <code>:first-child</code> selector, which is more understandable:</p>\n\n<pre><code>$(this).parents(':eq(5)').find(':first-child').html();\n</code></pre>\n\n<p><strong>Reference</strong></p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/parents\" rel=\"nofollow\"><code>.parents()</code></a></li>\n<li><a href=\"http://api.jquery.com\" rel=\"nofollow\"><code>.eq()</code></a></li>\n<li><a href=\"http://api.jquery.com/first-child-selector/\" rel=\"nofollow\"><code>:first-child</code> selector</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T11:40:52.593",
"Id": "1280",
"ParentId": "1265",
"Score": "8"
}
},
{
"body": "<p>Assuming you don't have access to the html (where you could assign an id the child), the only real option you have is:</p>\n\n<pre><code>$(this).parents().eq(5).children().eq(0).html();\n</code></pre>\n\n<p>if you are going to be accessing the element more than once you could assign it on load:</p>\n\n<pre><code>$(document).ready(function(){\n window.foo = $(bar).parents().eq(5).children().eq(0);\n});\n...\nfoo.html();\n</code></pre>\n\n<p>knowing more about why you need to do dom traversing, may yield further advice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-01T09:17:39.510",
"Id": "1600",
"ParentId": "1265",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "1266",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T17:53:06.013",
"Id": "1265",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "How bad is this jQuery?"
} | 1265 |
<p>A while back I wrote a <a href="http://brandontilley.com/2011/01/31/gist-tag-for-jekyll.html" rel="nofollow">Fluid tag for Jekyll</a> that inserts the contents of a <a href="https://gist.github.com/" rel="nofollow">GitHub Gist</a> into the content of the page in <code><noscript></code> tags for RSS readers. I've noticed a couple things I'm not happy with since posting it, but I am interested in the critique it will generate here on Stack Exchange!</p>
<p>(Obviously, some of the internals regarding methods required to make Liquid tags work (such as the parameters to <code>initialize</code> and having a <code>render</code> method) aren't negotiable, but you get the idea.)</p>
<pre><code>require 'digest/md5'
require 'net/https'
require 'uri'
module Jekyll
class GistTag < Liquid::Tag
def initialize(tag_name, text, token)
super
@text = text
@cache = true
@cache_folder = File.expand_path "../_gist_cache", File.dirname(__FILE__)
end
def render(context)
return "" unless @text =~ /([\d]*) (.*)/
gist, file = $1.strip, $2.strip
script_url = "https://gist.github.com/#{gist}.js?file=#{file}"
code = get_cached_gist(gist, file) || get_gist_from_web(gist, file)
code = code.gsub "<", "&lt;"
string = "<script src='#{script_url}'></script>"
string += "<noscript><pre><code>#{code}</code></pre></noscript>"
return string
end
def get_gist_url_for(gist, file)
"https://gist.github.com/raw/#{gist}/#{file}"
end
def cache_gist(gist, file, data)
file = get_cache_file_for gist, file
File.open(file, "w+") do |f|
f.write(data)
end
end
def get_cached_gist(gist, file)
return nil if @cache == false
file = get_cache_file_for gist, file
return nil unless File.exist?(file)
return File.new(file).read
end
def get_cache_file_for(gist, file)
bad_chars = /[^a-zA-Z0-9\-_\.]/
gist = gist.gsub bad_chars, ''
file = file.gsub bad_chars, ''
md5 = Digest::MD5.hexdigest "#{gist}-#{file}"
File.join @cache_folder, "#{gist}-#{file}-#{md5}.cache"
end
def get_gist_from_web(gist, file)
gist_url = get_gist_url_for(gist, file)
raw_uri = URI.parse(gist_url)
https = Net::HTTP.new(raw_uri.host, raw_uri.port)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(raw_uri.request_uri)
data = https.request(request)
data = data.body
cache_gist(gist, file, data) unless @cache == false
data
end
end
class GistTagNoCache < GistTag
def initialize(tag_name, text, token)
super
@cache = false
end
end
end
Liquid::Template.register_tag('gist', Jekyll::GistTag)
Liquid::Template.register_tag('gistnocache', Jekyll::GistTagNoCache)
</code></pre>
| [] | [
{
"body": "<p>A couple of mostly minor notes and improvements:</p>\n\n<pre><code>return \"\" unless @text =~ /([\\d]*) (.*)/\ngist, file = $1.strip, $2.strip\n</code></pre>\n\n<p>I generally try to avoid magic variables where ever possible. Using <code>match</code> and the resulting <code>MatchData</code> object tends to be less error prone.</p>\n\n<hr>\n\n<pre><code>code = code.gsub \"<\", \"&lt;\"\n</code></pre>\n\n<p>Is there a reason you only escape <code><</code> characters? Unless I'm missing something, it seems preferable to use <code>CGI.escapeHTML</code> instead.</p>\n\n<hr>\n\n<pre><code>return string\n</code></pre>\n\n<p>It seems inconsistent to me that in some methods you have a <code>return</code> statement on the last line and in others you do not. I would always leave out the <code>return</code> statement on the last line as it is unnecessary.</p>\n\n<hr>\n\n<pre><code>return nil if @cache == false\n</code></pre>\n\n<p>It is pretty unidiomatic to use <code>==</code> with boolean literals - usually one would just negate the boolean instead of comparing to <code>false</code>. <code>if !@cache</code> or better <code>unless @cache</code> will read more natural to most people than <code>if @cache == false</code>.</p>\n\n<hr>\n\n<pre><code>File.new(file).read\n</code></pre>\n\n<p>You should never use <code>File.new</code> without storing its return value somewhere and then later calling <code>close</code> on it. As a matter of fact in most cases you should not use <code>File.new</code> at all, but rather <code>File.open</code> with a block, which closes the file automatically when the block's end is reached. The way you're doing it the file handle will remain open until the <code>File</code> object is garbage collected, which may be a while. This is a bad practice and can lead to subtle problems.</p>\n\n<p>However in this case you don't even need <code>File.open</code> as there is already a method which does exactly what you need: <code>File.read(file)</code>.</p>\n\n<hr>\n\n<pre><code>gist.gsub! /[^a-zA-Z0-9\\-_\\.]/, ''\n</code></pre>\n\n<p>You don't need to escape <code>.</code> as it has no special meaning inside brackets.</p>\n\n<hr>\n\n<pre><code>cache_gist(gist, file, data) unless @cache == false\n</code></pre>\n\n<p>This would really be a lot more readable without the explicit comparison and the double negation:</p>\n\n<pre><code>cache_gist(gist, file, data) if @cache\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T21:32:03.590",
"Id": "2211",
"Score": "0",
"body": "Excellent, thanks! I saw your comment on magic variables in another of your answers, and with good points; you're right about the `return`s, it's quite inconsistent (is there a better/more idiomatic way of handling the return branches in `get_cached_gist`?); and `File.new(file).read` was an embarrassing bug introduced from getting rid of the even worse `File.new(file).readlines.join`, but when I \"fixed\" it I forgot to get rid of the call to `new`!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T21:32:22.620",
"Id": "2212",
"Score": "0",
"body": "As for the boolean check, I think I just have a badly named boolean; changing it to `@caching_enabled` or similar makes the \"positive\" match much more readable in English. Thanks again for all the tips!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T21:47:26.650",
"Id": "2213",
"Score": "0",
"body": "@BinaryMuse: \"is there a better/more idiomatic way of handling the return branches in `get_cached_gist`?\" No, the way you did it seems fine."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T22:12:20.200",
"Id": "2215",
"Score": "0",
"body": "Great, thanks again. I'm quite happy with [the refactored code](https://gist.github.com/803483#file_gist_tag.rb)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T21:08:20.693",
"Id": "1272",
"ParentId": "1268",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T18:45:20.550",
"Id": "1268",
"Score": "4",
"Tags": [
"ruby",
"jekyll",
"liquid"
],
"Title": "Fluid tag for displaying GitHub Gists with noscript tags in a Jekyll post"
} | 1268 |
<p>I generally feel that the pattern I use for development is kind of wrong. I start with simple functionality, then when I realize that some pieces can be reused I usually start to write "scope root level" functions in order to be more DRY. I usually place these functions at the bottom of my "scope". Would these functions (<code>changeColumn</code>, in this case) better be methods of main object? Would this script better be organized in a more object-oriented way? Are there major problems with my coding style?</p>
<p>Unfortunately, I work directly with back-end programmers who don't give a damn about JS and so I am left with myself at this. I am trying to look at “rock stars”, but they mainly write tools, not simple interaction functionality, so for this kind of scripts I rarely get to see examples of really good code to learn from.</p>
<pre><code>/** Depends on:
* - jQuery (tested with 1.5.1)
* http://jquery.com/
* - jQuery scrolTo (tested with 1.4.2)
* http://flesler.blogspot.com/2009/05/jqueryscrollto-142-released.html
**/
// Main obj
omami = {
init: function() {
// scrollable area
var content = $('#content').css('overflow-x', 'scroll'),
// flag identifying scroll event
didScroll,
// flag identifying if scroll event
// is caused by mouse / trackpad etc.
// i.e. user action
userScroll,
// flag identifying if scroll event
// is caused by script action
scriptScroll,
// content sections
cols = content.find('.column'),
// hash table to store initial columns x-axis positions
positionsMap = {},
currentColHash,
// Checks if first argument is bigger than second
// and smaller than third
isInRange = function(num, a, b) {
return (num > a && num < b);
};
// store initial columns positions
cols.each(function() {
var col = $(this);
positionsMap[col.attr('id')] = col.position().left;
});
// don't bind complex logic directly on scroll –
// http://ejohn.org/blog/learning-from-twitter/
content.bind('scroll', function(e) {
didScroll = true;
})
// for each user initiated scroll event
// poll current section
setInterval(function() {
if ( didScroll && !scriptScroll ) {
didScroll = false;
var curScroll = content.scrollLeft(), colID;
// find what column is selected
for ( colID in positionsMap ) {
// safe sex
if ( {}.hasOwnProperty.call(positionsMap, colID) ) {
// we compare current left scroll of container element
// with initial positions of columns
if ( isInRange(curScroll, positionsMap[colID] - 150, positionsMap[colID] + 410) ) {
// cut "col-" from column ID
currentColHash = colID.substring(4);
// if current col isn't already selected
if (location.hash.indexOf(currentColHash) == '-1') {
// indicate user action
userScroll = true;
// highlight current column in the address bar
location.hash = currentColHash;
}
}
}
}
}
}, 250);
// Controller
$(window).bind('hashchange', function() {
var hash = location.hash;
if (hash != '' && hash != '#') {
// cut '#' off
hash = hash.substring(1);
// don't override user action
if (!userScroll) {
// indicate that scroll happens programmatically
scriptScroll = true;
// do the scrolling
content.scrollTo(
( content.scrollLeft() + $('#col-' + hash).position().left ) - 20
, 500, {
onAfter: function() {
// done with JavaScript scrolling
// start polling current section again
scriptScroll = false;
}
});
}
userScroll = false;
} else {
// support back-button up to empty-hash state
content.scrollTo(0);
}
// on page load, scroll to the proper section
}).trigger('hashchange');
// scroll to the next/previous column controls
// just updating location.hash
// controller will take care of taking appropriate action
$('.column .scroll').bind('click', function(e) {
e.preventDefault();
var arrow = $(this);
// change the column
changeColumn({
direction : arrow.hasClass('right') ? 'right' : 'left',
currentColumn : arrow.closest('.column')
});
});// .scroll bind('click) fn
// handle left and right arrows
$(window).bind('keyup', function(e) {
// 37 – left arrow
// 39 - right arrow
if (e.keyCode == 37 || e.keyCode == 39) {
e.preventDefault();
changeColumn({
direction: (e.keyCode == 39) ? 'right' : 'left'
});
}
});// window bind('keyup') fn
// updates location.hash with slug of the column
// user wants to view, either by scrolling to it,
// either by navigating to it with arrows/header nav
//
// @param {Object} options object
// @option {String} direction – determens change direction
// @option {jQuery} currentColumn – currently selected column
function changeColumn(opts) {
// defaults
var settings = {
direction : 'right',
currentColumn : (function(){
// calculate current column from hash if it's selected
var colHash = location.hash.substring(1);
// if it's not, we suppose we are at first column
return (colHash.length != 0) ? $('#col-' + colHash) : cols.first();
})()
};
// merge options and defaults
$.extend(settings, opts);
// what's the next column?
var nextColumn =
(settings.direction == 'right')
// scroll right
? (settings.currentColumn.next().length != 0)
// scroll to the next column
? settings.currentColumn.next()
// scroll to the first column
: settings.currentColumn.siblings().first()
// scroll left
: (settings.currentColumn.prev().length != 0)
// scroll to the previous column
? settings.currentColumn.prev()
// scroll to the last column
: settings.currentColumn.siblings().last();
// update the hash
location.hash = nextColumn.attr('id').substring(4);
}// fn changeColumn
} // fn omami.init
};// obj omami
</code></pre>
| [] | [
{
"body": "<p>That's a bit to much code for me to go through in one go but I'll take a stab at one part:</p>\n\n<pre><code>// for each user initiated scroll event \n// poll current section\nsetInterval(function() {\n if ( didScroll && !scriptScroll ) {\n didScroll = false;\n\n var curScroll = content.scrollLeft(), colID;\n\n // find what column is selected\n for ( colID in positionsMap ) {\n // safe sex\n if ( {}.hasOwnProperty.call(positionsMap, colID) ) {\n // we compare current left scroll of container element\n // with initial positions of columns\n if ( isInRange(curScroll, positionsMap[colID] - 150, positionsMap[colID] + 410) ) {\n // cut \"col-\" from column ID\n currentColHash = colID.substring(4);\n\n // if current col isn't already selected\n if (location.hash.indexOf(currentColHash) == '-1') {\n // indicate user action\n userScroll = true;\n // highlight current column in the address bar\n location.hash = currentColHash;\n }\n }\n }\n }\n }\n}, 250);\n</code></pre>\n\n<p>I'd write like this:</p>\n\n<pre><code>// for each user initiated scroll event \n// poll current section\nsetInterval(function() {\n if ( !didScroll || scriptScroll ) return;\n didScroll = false;\n var curScroll = content.scrollLeft(), colID;\n\n // find what column is selected\n for ( colID in positionsMap ) {\n // safe sex\n if ( !{}.hasOwnProperty.call(positionsMap, colID) ) continue;\n // we compare current left scroll of container element\n // with initial positions of columns\n if ( !isInRange(curScroll, positionsMap[colID] - 150, positionsMap[colID] + 410) )\n continue;\n // cut \"col-\" from column ID\n currentColHash = colID.substring(4);\n\n // if current col isn't already selected\n if (location.hash.indexOf(currentColHash) !== -1) continue;\n // indicate user action\n userScroll = true;\n // highlight current column in the address bar\n location.hash = currentColHash;\n }\n }\n}, 250);\n</code></pre>\n\n<ul>\n<li><p>Use if-guards to save on indentation. </p></li>\n<li><p>Use typechecking operators === and !== instead of == and !=. Weird things happen otherwise: <a href=\"http://wtfjs.com/2010/02/26/implicit-tostring-fun\" rel=\"nofollow\">http://wtfjs.com/2010/02/26/implicit-tostring-fun</a>, <a href=\"http://wtfjs.com/2011/02/11/all-your-commas-are-belong-to-Array\" rel=\"nofollow\">http://wtfjs.com/2011/02/11/all-your-commas-are-belong-to-Array</a></p></li>\n<li><p>str.indexOf returns a number, not a string.</p></li>\n</ul>\n\n<p>I hope this helped a little. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T11:01:17.817",
"Id": "2218",
"Score": "0",
"body": "Whoa, this if-guards approach was exactly what I was looking for - I felt there is too much indentation going on, but I wasn't sure what to do with it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T23:39:43.957",
"Id": "1275",
"ParentId": "1271",
"Score": "4"
}
},
{
"body": "<p>I don't have time for a full-blown answer.</p>\n\n<p>Here are only a few pointers:</p>\n\n<ul>\n<li><p>Instead of commenting everything, leave only the useful one. </p>\n\n<p>Sometimes (like in your first setInterval call), it is better to name the function sensibly, instead of commenting on what it does.</p></li>\n<li><p>Prefix jQuerified variable names with $. Very helpful</p></li>\n<li><p>Do not use more than one ternary (?:) operator at a time. That's just awful.</p>\n\n<p>Rewrite it as:</p>\n\n<pre><code>var current = settings.currentColumn,\n next = current[{ right: next, left: prev }[settings.direction]]();\nif (!next.length) { \n next = current.siblings()[{right: first, left: last}[settings.direction]]\n}\n</code></pre>\n\n<p>Or better: Add a method to do next with the cycle logic.</p></li>\n</ul>\n\n<p>I might add more if I do get time to do so</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T10:11:09.737",
"Id": "2217",
"Score": "0",
"body": "Thanks, @glebm!\nCouple of questions:\nHow to decide when code speaks for itself and when comment's really useful? Is there some kind of rule of thumb? \n\nCan you please explain what do you mean exactly by \"cycle\" logic?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T13:58:16.300",
"Id": "2222",
"Score": "1",
"body": "Unfortunately, good commenting skills come with experience, and there is no rule of thumb. I usually write the code first, and then comment the parts that I feel might be unclear. By \"cycle\" logic I meant circular list traversal. You could have an API like `current.next({wrap: true})`, which would do all the logic of going to the first element if there is no next element."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-12T23:41:10.073",
"Id": "1276",
"ParentId": "1271",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1275",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-12T20:45:48.200",
"Id": "1271",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"event-handling"
],
"Title": "Window-scrolling controller"
} | 1271 |
<p>I just realized that I could turn:</p>
<pre><code>import MySQLdb
def main():
db = MySQLdb.connect( .. )
try:
while True:
do_thingy()
finally:
db.close()
</code></pre>
<p>into:</p>
<pre><code>import MySQLdb, atexit
def main():
db = MySQLdb.connect( .. )
atexit.register( db.close )
while True:
do_thingy()
</code></pre>
<p>Which lets me keep the code for closing the database next to the opening, and saves me a line of code and an indentation level, which I like. Is there a reason why I shouldn't do this?</p>
| [] | [
{
"body": "<p>Firstly, an alternative:</p>\n\n<pre><code>import MySQLdb, contextlib\n\ndef main():\n db = MySQLdb.connect( .. )\n with contextlib.closing(db):\n do_thingy()\n</code></pre>\n\n<p>The database connection will be closed after the with block even in the case of exceptions.</p>\n\n<p>The primary problem created by atexit is in any attempt to reuse that code in question. It will only release the database connection when the entire program exits. That's fine in the case where this function is your entire program. But at some later point that my cease to be the case. </p>\n\n<p>If you really want the database connection to be closed at the end of the function, its clearest if you write code that does that rather then assuming that this is the only function called in the program.</p>\n\n<p>There really is not much of saving to use the atexit route. I think the clarity in the \"with\" method is worth the extra level of indentation. Additionally, you can use this same technique anywhere in code not just in a main function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T02:22:19.770",
"Id": "2216",
"Score": "0",
"body": "Oh yes, you are right, I failed to think outside of my own application. :) I didn't know about contextlib, thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-13T01:24:03.400",
"Id": "1277",
"ParentId": "1274",
"Score": "14"
}
}
] | {
"AcceptedAnswerId": "1277",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-12T22:10:10.403",
"Id": "1274",
"Score": "4",
"Tags": [
"python",
"comparative-review"
],
"Title": "Should I use atexit to close db connection?"
} | 1274 |
<p>I have written these two functions that have a similar process. The first is meant to "split" a string on a given character and the second is meant to "replace-all" instances of a character in a given string. The behavior between the two seems very similar - can you think of a good way to abstract that behavior into a third, reusable, function? (which could be executed by calling, for example, (where-found sought-letter searchee-string thing-to-do)).</p>
<pre><code>(defun split (separator splittee)
(let ((next-index (position separator splittee)))
(if next-index
(cons (subseq splittee 0 next-index) (split separator (subseq splittee (1+ next-index))))
(list splittee))))
(defun replace-all (replacand replacee replacor)
(let ((next-index (position replacand replacee)))
(if next-index
(concatenate 'string (subseq replacee 0 next-index) replacor (replace-all replacand (subseq replacee (1+ next-index)) replacor))
replacee)))
</code></pre>
<p>What do you think? Is this better than the original code, or is it too complicated?</p>
<pre><code>(defun where-found (sought-letter the-string to-do-onroute to-do-on-leaf)
(let ((next-index (position sought-letter the-string)))
(if next-index
(apply to-do-onroute
(list (subseq the-string 0 next-index)
(subseq the-string (1+ next-index))))
(apply to-do-on-leaf (list the-string)))))
(defun split (separator splittee)
(where-found separator splittee
(lambda (pre-string post-string) (cons pre-string (split separator post-string)))
(lambda (leaf-string) (list leaf-string))))
(defun replace-all (to-be-replaced-string the-patient-string the-replacement-string)
(where-found to-be-replaced-string the-patient-string
(lambda (pre-string post-string)
(format t "pre: ~a post: ~a the-replacement-string: ~a ~%" pre-string post-string the-replacement-string)
(concatenate 'string pre-string the-replacement-string (replace-all to-be-replaced-string post-string the-replacement-string)))
(lambda (leaf-string) leaf-string)))
(format t "the cat is here: ~a ~%" (replace-all #\Space "the cat is here" ""))
(format t "the cat is here: ~a ~%" (split #\Space "the cat is here"))
</code></pre>
| [] | [
{
"body": "<p>I think the later versions are unnecessarily complicated and verbose.</p>\n\n<p>My first idea was to just concatenate the splitted list parts in replace-all – for you can do <code>(concatenate 'string seqs ... )</code> – but that may not be very efficient.</p>\n\n<p>You can use map or loop for replace-all. This map version works for lists too:</p>\n\n<pre>\n(defun replace-all (seq from to)\n (map (type-of seq) (lambda (char) (if (equal from char) to char)) seq))\n</pre>\n\n<p>Naming things clearly can sometimes be hard, and I think sometimes being terse helps readability more than being too-explicit-and-specific. That if statement above could need some better naming of things...</p>\n\n<p>There is an utility library called <a href=\"http://www.cliki.net/SPLIT-SEQUENCE\" rel=\"nofollow\">split-sequence</a>, that has many useful options, like</p>\n\n<ul>\n<li>remove empty subsequences</li>\n<li>only split count times</li>\n<li>return the index position (useful for further processing)</li>\n</ul>\n\n<p>I'm still learning Lisp, so you may want to hear see other answers also.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T05:19:31.133",
"Id": "2282",
"Score": "0",
"body": "That does look pretty nice and simple. What would you do for split?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T16:05:31.327",
"Id": "1294",
"ParentId": "1282",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1294",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-14T04:21:39.820",
"Id": "1282",
"Score": "2",
"Tags": [
"strings",
"lisp",
"common-lisp"
],
"Title": "Abstract the (duplicate?) behavior between \"sort\" and \"replace\""
} | 1282 |
<p>I'm learning Python and have found <a href="http://code.google.com/codejam/contest/dashboard?c=635101#s=p0" rel="nofollow noreferrer">this problem</a> from Google Code Jam:</p>
<blockquote>
<p>How many <code>mkdir</code> commands does it take to construct a given directory tree:</p>
<h3>Input</h3>
<p>The first line of the input gives the number of test cases, <strong>T</strong>. <strong>T</strong> test cases follow. Each case begins with a line containing two integers <strong>N</strong> and <strong>M</strong>, separated by a space.</p>
<p>The next <strong>N</strong> lines each give the path of one directory that already exists on your computer. This list will include every directory already on your computer other than the root directory. (The root directory is on every computer, so there is no need to list it explicitly.)</p>
<p>The next <strong>M</strong> lines each give the path of one directory that you want to create.</p>
<p>Each of the paths in the input is formatted as in the problem statement above. Specifically, a path consists of one or more lower-case alpha-numeric strings (i.e., strings containing only the symbols 'a'-'z' and '0'-'9'), each preceded by a single forward slash. These alpha-numeric strings are never empty.</p>
<h3>Output</h3>
<p>For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of <code>mkdir</code> you need.</p>
</blockquote>
<p>I've solved it by writing code shown below, and it works correctly, but how can I make it faster?</p>
<pre><code>import sys
def split_path(path_file,line_count_to_be_read):
for i in range(line_count_to_be_read):
# Get the Path line
line = path_file.readline()
# Skip the first slash
line = line[1:]
line = line.strip()
splited = line.split('/')
# make each subpaths from the source path
for j in range(1,len(splited)+1):
joined = "/".join(splited[:j])
yield joined
def main():
file_name = ""
try:
file_name = sys.argv[1]
except IndexError:
file_name = "A-small-practice.in"
with open(file_name) as path_file:
# skip the first line
line = path_file.readline()
total_testcases = int(line) # Number of Test Cases - Unused
case_no = 0
while True:
line = path_file.readline()
if not line:
break
# Get Existing path and New path count
existing_count,new_count = line.split()
existing_count = int(existing_count)
new_count = int(new_count)
# Split Every Path and Make all Subpaths
existing_paths = list(split_path(path_file,existing_count)) # Existing Subpaths
new_paths = list(split_path(path_file,new_count)) # New Subpaths
# Remove all paths that is in Existing list from the New list
new_mkdir_set = set(new_paths) - set(existing_paths)
case_no += 1
# length of new_set contains number of needed mkdir(s)
print "Case #{0}: {1}".format(case_no,len(new_mkdir_set))
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T10:46:28.507",
"Id": "2236",
"Score": "3",
"body": "You should really comment your code. Now we will have to basically solve the problem for you before we even understand what your code does. That is a lot of work..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T02:53:55.303",
"Id": "2252",
"Score": "0",
"body": "@Lennart Sorry, I should done it first. I hope these comments will help more."
}
] | [
{
"body": "<p>Rather than using a list, consider approaching the problem from a graph perspective. Build a tree from the root directory using the existing directories, then traverse it with the new directories, and output a result line each time you have to add a leaf to the graph. This should be a little faster than comparing your two sets.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T14:52:58.857",
"Id": "1284",
"ParentId": "1283",
"Score": "5"
}
},
{
"body": "<p>You can create a tree that you'd update on each iteration (while you calculate also the creation cost). You can do that with a simple nested dictionary. For example:</p>\n\n<pre><code>start with empty filesystem -> fs = {}, cost 0\n\"/1/2/3\" -> fs = {1: {2: 3: {}}}, cost 3\n\"/1/2/4\" -> fs = {1: {2: 3: {}, 4: {}}}, cost 1\n\"/5\" -> fs = {1: {2: 3: {}, 4: {}}, 5: {}}, cost 1\n\n= cost 5\n</code></pre>\n\n<p>You can use an algorithm with recursion (functional) or loops with inplace modifications (imperative). If you are learning I'd go for the first so you can apply some functional programming concepts (basically, one rule: don't update variables!).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T03:43:04.330",
"Id": "2280",
"Score": "0",
"body": "Thanks. Is doing functional way increase speed ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T09:38:21.643",
"Id": "2283",
"Score": "0",
"body": "@gkr: probably not, but it will increase your programming skills :-p Seriously, functional programming is a whole new world (and you don't need to use Haskell to apply its principles), it's not about speed (or not only) but about writing clear, modular code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T20:26:34.507",
"Id": "1297",
"ParentId": "1283",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-14T05:43:46.670",
"Id": "1283",
"Score": "6",
"Tags": [
"python",
"performance",
"programming-challenge",
"tree",
"file-system"
],
"Title": "\"File Fix-it\" challenge"
} | 1283 |
<p>I initially posted this on StackOverflow, and was redirected here.
I have been playing around with Bouncy Castle (Java) for the last few days, and I've reached the point where I believe I can securely exchange secret keys with a Diffie-Hellman exchange.</p>
<p>Having read many posts underlining the difficulty of properly implementing a cryptographic exchange, I would like your honest opinion on my work.
All the underlying cipher operations are based on Bouncy Castle and may therefore be deemed reliable.</p>
<pre><code>String message = "Hello World";
AESCipher aes_client = new AESCipher(256);
RSACipher rsa_server = new RSACipher(2048);
// (Public key sent over the wire)
RSACipher rsa_client = new RSACipher(rsa_server.getPublicKey().getModulus(),
rsa_server.getPublicKey().getExponent());
// The client encodes his AES key with the RSA public key:
byte[] aes_key = rsa_client.encode(aes_client.getKeyBytes());
byte[] aes_iv = rsa_client.encode(aes_client.getInitializationVector());
// (Data sent back over the wire)
byte[] decoded_aes_key = rsa_server.decode(aes_key);
byte[] decoded_aes_iv = rsa_server.decode(aes_iv);
// The server creates an AES server which uses the client key:
AESCipher aes_server = new AESCipher(decoded_aes_key, decoded_aes_iv);
byte[] encoded_message = aes_client.encode(message.getBytes());
byte[] decoded_message = aes_server.decode(encoded_message);
System.out.println(new String(decoded_message));
</code></pre>
<p>Can this exchange be considered safe? Should I be sticking with SSL Sockets, eventhough it'd hurt to thrash my hard work?
Thanks in advance for your input!</p>
<p>(By the way, my Bouncy-Castle-Wrapping-Library is totally open-source, so just let me know if you want the repository's URL.)</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T19:17:35.093",
"Id": "2246",
"Score": "2",
"body": "I think you should use SSL for \"real\" encryption, simply because it's a field-proven protocol, but it would be instructive for you to see how your implementation differs from SSL, and then see if you can defend all the differences. If you can, and it stands up to scrutiny from other cryptographers (of which I'm not one), then it could work."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T19:23:47.397",
"Id": "2247",
"Score": "2",
"body": "See also: http://programmers.stackexchange.com/q/51528/5167 for my stance on using a standard encryption protocol. Obviously, you're not trying to directly use raw crypto primitives, which is good, but I'm not knowledgeable enough to vet your protocol for weaknesses. :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T16:26:45.943",
"Id": "2318",
"Score": "0",
"body": "@Chris Jester-Young: How should one best approach security in cases where one end of a connection is going to be a rather wimpy microcontroller which can't practically do SSL with a key length beyond 512 bits (which for all practical purposes one may as well not bother with)."
}
] | [
{
"body": "<p>It's very difficult to answer you, because what you've posted is a test-bed where your byte arrays are passed around in the context of a high-level language, as opposed to a real situation where you'd have (at the very least) two processes communicating down a pipe, TCP socket or similar. The details of how you do this are crucial; getting them wrong will destroy your security just as easily as if you get the crypto wrong.</p>\n\n<p>I haven't thought about your code very much, but these questions immediately come to mind:</p>\n\n<ul>\n<li>How are you sending and receiving data over the wire - how are your packets delimited and parsed?</li>\n<li>How are the crypto keys being generated - specifically, what's their random source? </li>\n<li>How are keys being stored at either end?</li>\n<li>What RSA padding and AES mode are you using?</li>\n<li>How do you know that the key you've got really belongs to the person you think it does, and not some man in the middle? In other words, how do you establish trust in that key?</li>\n</ul>\n\n<p>As others have said, you should be reusing an existing library to use a well-established protocol. You might care to read the <a href=\"http://www.moserware.com/2009/09/stick-figure-guide-to-advanced.html\" rel=\"nofollow\">stick figure guide to AES</a>: pay particular note to the Foot-Shooting Prevention Agreement; what goes for not inventing your own crypto algorithms, also goes for protocols. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T14:34:27.537",
"Id": "1327",
"ParentId": "1286",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-14T19:02:46.027",
"Id": "1286",
"Score": "4",
"Tags": [
"java",
"security",
"cryptography"
],
"Title": "Cryptographic key exchange"
} | 1286 |
<p>I have a heading, which is an integer and from it I would like to figure out the compass direction (North, North-East,...) and return the appropriate icon. I feel like I'm probably already at the cleanest solution but I would love to be proven wrong.</p>
<pre><code>public GetHeadingImage(string iconName, int heading){
if (IsNorthHeading(heading))
return iconName + "n" + ICON_FILE_EXTENTION;
if (IsNorthEastHeading(heading))
return iconName + "ne" + ICON_FILE_EXTENTION;
if (IsEastHeading(heading))
return iconName + "e" + ICON_FILE_EXTENTION;
/*A bunch more lines*/
}
private bool IsNorthHeading(int heading)
{
return heading < 23 || heading > 337;
}
/* A bunch more extracted test methods*/
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T21:30:20.857",
"Id": "23555",
"Score": "0",
"body": "Is it possible at all that the thing, whatever it may be, is not moving at all?"
}
] | [
{
"body": "<p>Small suggestion: the GetHeadingImage() has a lot of duplicate code.<br/>\nWhy not something like:</p>\n\n<pre><code>public GetHeadingImage(string iconName, int heading){\n return iconName + GetHeadingName(heading) + ICON_FILE_EXTENTION;\n}\n</code></pre>\n\n<p>You could then have the heading logic just inside GetHeadingName().</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T12:33:18.573",
"Id": "2287",
"Score": "1",
"body": "Combining this with the original code makes for a more readable result than the shorter but more cryptic suggestion. In six months this will still make sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T20:35:43.293",
"Id": "1288",
"ParentId": "1287",
"Score": "7"
}
},
{
"body": "<p>Two things: <strong>1)</strong> Extract <code>GetCompasDirection</code> as a separate method which will return an enum <strong>2)</strong> Create a collection of angles and corresponding headers to remove a lot of <code>Is...Heading</code> methods: </p>\n\n<pre><code>public enum CompasDirection\n{\n North,\n NorthEast,\n // other directions\n}\n\npublic CompasDirection GetCompasDirection(int heading)\n{\n // directions in clock-wise order:\n var directionUpperLimitAngles = new [] {\n Tuple.Create(CompasDirection.North, 22),\n Tuple.Create(CompasDirection.NorthEast, 67),\n Tuple.Create(CompasDirection.East, 112),\n // other directions,\n Tuple.Create(CompasDirection.North, 360), // north again\n };\n\n return directionUpperLimitAngles.Last(d => d.Item2 <= heading).Item1;\n}\n\npublic string GetHeadingImage(string imageName, int heading)\n{\n var directionToIconSuffixMapping = new Dictionary<CompasDirection, string> {\n { CompasDirection.North, \"n\"},\n { CompasDirection.NorthEast, \"ne\"},\n // other directions\n };\n var direction = GetCompasDirection(heading);\n return iconName + directionToIconSuffixMapping[direction] + ICON_FILE_EXTENTION;\n}\n</code></pre>\n\n<p>Some parts here can be simplify (for example you can remove second dictionary and simply name your icon files correspondingly to enum members). </p>\n\n<p>This approach with direction-heading table if I remember correctly I've taken from McConnel's <code>Code Complete</code></p>\n\n<p><strong>UPDATE</strong>: replaced inner private class with <code>Tuples</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T21:34:52.153",
"Id": "2248",
"Score": "1",
"body": "What use is the enum here? Why not simply map numbers to suffixes?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T21:37:55.503",
"Id": "2249",
"Score": "1",
"body": "@pdr, it can be mapped directly to suffixes, but only if you are sure that you will never-never-never need the directions again. Otherwise leaving them as suffixes will lead to `stringly-typed` code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T01:44:53.807",
"Id": "2251",
"Score": "0",
"body": "@Snowbear, Good point"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:05:54.743",
"Id": "2259",
"Score": "0",
"body": "+1, the main point is mentioned here, separate logic from representation! The enum is a must. Also, if the class `CompassDirectionAngle` isn't to be used outside of the class (it's correctly set to private), I would use a `Tuple<CompassDirection, int>` array instead, so the class can be removed. Giving the array a proper name is sufficient enough, the class only adds a negligible bit of readability."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:11:02.577",
"Id": "2260",
"Score": "0",
"body": "@Steven, I also thought about `Tuples` but they didn't fit into CR screen width :). But I agree, `Tuples` will look good here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:14:41.800",
"Id": "2261",
"Score": "0",
"body": "@Snowbear, they do if you use `Tuple.Create()`. ;p"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:16:41.643",
"Id": "2262",
"Score": "0",
"body": "@Steven, giant thanks, didn't know about that one. I will update the code with `Tuples`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-14T20:47:46.403",
"Id": "1289",
"ParentId": "1287",
"Score": "3"
}
},
{
"body": "<p>Another alternative:</p>\n\n<pre><code>public enum Direction\n{\n North = 0,\n NorthEast = 1,\n East = 2,\n SouthEast = 3,\n South = 4,\n SouthWest = 5,\n West = 6,\n NorthWest = 7\n}\n\npublic static class DirectionExtensions\n{\n private static readonly Dictionary<Direction, string>\n mapping = new Dictionary<Direction, string>\n {\n { Direction.North, \"n\" },\n { Direction.NorthEast, \"ne\" },\n { Direction.East, \"e\" },\n { Direction.SouthEast, \"se\" },\n { Direction.South, \"s\" },\n { Direction.SouthWest, \"sw\" },\n { Direction.West, \"w\" },\n { Direction.NorthWest, \"nw\" }\n };\n\n public static bool IncludesHeading(this Direction direction, int heading)\n {\n var adjusted = (heading + 22) % 360;\n var adjMin = (int) direction * 45;\n var adjMax = adjMin + 44;\n return (adjusted >= adjMin && adjusted <= adjMax);\n }\n\n public static string GetSuffix(this Direction direction)\n {\n return mapping[direction];\n }\n}\n</code></pre>\n\n<p>Leaves your method reading like this:</p>\n\n<pre><code>public string GetHeadingImage(string imageName, int heading)\n{\n Direction[] directions = ((Direction[]) Enum.GetValues(typeof(Direction)));\n var match = directions.First(d => d.IncludesHeading(heading));\n return imageName + match.GetSuffix() + ICON_FILE_EXTENTION;\n}\n</code></pre>\n\n<p><strong>[Edit: Taking that one step further]</strong></p>\n\n<p>Replace the IncludesHeading extension with</p>\n\n<pre><code>public static IntDirectionExtensions\n{\n public static Direction GetDirection(this int heading)\n {\n var adjusted = (heading + 22) % 360;\n var sector = adjusted / 45;\n return (Direction)sector;\n }\n}\n</code></pre>\n\n<p>And now you can simplify your method to</p>\n\n<pre><code>public string GetHeadingImage(string imageName, int heading)\n{\n return imageName + heading.GetDirection().GetSuffix() + ICON_FILE_EXTENTION;\n}\n</code></pre>\n\n<p><strong>[Edit 2: Another idea]</strong></p>\n\n<p>Another thing you could do is map to the suffix via reflection, which I think looks nicer but is probably less efficient</p>\n\n<pre><code>public enum Direction\n{\n [IconSuffix(\"n\")] North = 0,\n [IconSuffix(\"ne\")] NorthEast = 1,\n [IconSuffix(\"e\")] East = 2,\n [IconSuffix(\"se\")] SouthEast = 3,\n [IconSuffix(\"s\")] South = 4,\n [IconSuffix(\"sw\")] SouthWest = 5,\n [IconSuffix(\"w\")] West = 6,\n [IconSuffix(\"nw\")] NorthWest = 7\n}\n\npublic class IconSuffixAttribute : Attribute\n{\n public string Suffix { get; private set; }\n public IconSuffixAttribute(string suffix)\n {\n Suffix = suffix;\n }\n}\n</code></pre>\n\n<p>Replacing your GetSuffix extension (and now-defunct Dictionary mapping) with</p>\n\n<pre><code>public static string GetSuffix(this Direction direction)\n{\n var suffix = from m in typeof(Direction).GetMember(direction.ToString())\n from a in m.GetCustomAttributes(typeof(IconSuffixAttribute), false)\n select ((IconSuffixAttribute) a).Suffix;\n return suffix.First();\n}\n</code></pre>\n\n<p>Everything else remains the same.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:29:01.080",
"Id": "2263",
"Score": "0",
"body": "I don't really find an extension method appropriate here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:33:12.947",
"Id": "2264",
"Score": "0",
"body": "@Steven, any reason for that? I find it makes the GetHeadingImage method more readable. But honestly, that's not the main part of the solution (static methods are equally effective); it's the maths vs lookup that is different from the other solutions (or was, at the time I wrote it)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:46:56.957",
"Id": "2265",
"Score": "0",
"body": "IMHO, I would expect such a method to be placed in a Compass class (or in java in the enum itself?), and be called from there. Otherwise the coupling just feels wrong. The list of extension methods for int would be infinite. Personally, I only use extension methods where I would otherwise have to write a helper class because I can't modify the source of the original class. Furthermore, the math is confusing, includes unnecessary magic numbers, and I believe is more complex than Snowbear's simple lookup."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:53:19.070",
"Id": "2266",
"Score": "0",
"body": "@Steven, Ok, I disagree, but at least I understand now. Extension methods don't generally get out of hand because you limit access to them by namespace, and int is a perfect example of a class I have no access to while an enum can't have functionality. As for the magic numbers; I think Snowbear's are just hidden. Consider the directionAngles array written out in full. Any one of those numbers could be wrong and cause a subtle bug."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:54:56.650",
"Id": "2267",
"Score": "0",
"body": "I should point out here (in the midst of seeming criticism) that I voted up Snowbear's answer myself. I prefer it to the others by a long shot."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T01:42:03.653",
"Id": "1291",
"ParentId": "1287",
"Score": "2"
}
},
{
"body": "<p>A simple solution is a good solution:</p>\n\n<pre><code>public GetHeadingImage(string iconName, int heading){\n var directions = new string[] {\n \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\", \"nw\", \"n\"\n };\n\n var index = (heading + 23) / 45;\n return iconName + directions[index] + ICON_FILE_EXTENSION;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T09:53:03.543",
"Id": "2257",
"Score": "9",
"body": "+1 good and simple solution. Maybe its a good idea to replace the magic number ´45´ with ´int DegreesPerDirection = 360 / (directions.Length - 1)´ and ´23´ with ´DegreesPerDirection / 2´"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T10:58:31.030",
"Id": "2268",
"Score": "2",
"body": "The index calculation seems solid, but a simple solution isn't a reuseable solution. I would still introduce an enum to represent the heading, as well as at least document the calculation, e.g. by removing the magic numbers as k3b mentions."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T01:44:21.133",
"Id": "2277",
"Score": "0",
"body": "@k3b: Good call. @Steven: I'd introduce a `Direction` enum if there places where it was used. In this case all we're visibly using are degrees, so I'd leave it out. We can always add it later if we actually need it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T09:24:52.103",
"Id": "64417",
"Score": "0",
"body": "Same calculation in JS, with more compass points: [Is there a better way to get a compass point from 140° than a series of if's?](http://codereview.stackexchange.com/q/38613)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-15T02:17:22.150",
"Id": "1292",
"ParentId": "1287",
"Score": "26"
}
},
{
"body": "<p>Naming (minor): Something possibly more specific to the domain for sector boundaries ('left'? and 'right'? relative angles) might be instead be called a radial. Each radial in at least [aeronautical] navigation is referred to as the '#named number of radial# radial', such as 'the 025 radial', or commonly just by number, 'the 025' (read as zero two five). Perhaps this would help minimize magic numbers by declaring your boundaries as named radial constants. </p>\n\n<p>To go a step further, since you are dividing the compass into equally sized parts, or partitions, you might create constant/immutable value objects that describe these partitions. 'CardinalDirection' (n e s w) with public getters of left radial and right radial is an revised offhand suggestion. Ordinals are the next set of directional divisions (ne se sw nw).</p>\n\n<p>Hope this helps refine your model for the better. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T03:58:02.633",
"Id": "1293",
"ParentId": "1287",
"Score": "1"
}
},
{
"body": "<p>You could simplify your solution by concatenating the north/south letter with the east/west letter and thus avoid any need for <code>IsNorthEastHeading</code> and such like.</p>\n\n<pre><code>string northsouth = (heading < 23 || heading > 337) ? \"n\" :\n (heading > 157 && heading < 203) ? \"s\" : \n \"\";\nstring eastwest = ...\nreturn iconName + northsouth + eastwest + ICON_FILE_EXTENTION;\n</code></pre>\n\n<p>Is it really worth adding all those extra methods or introducing enums? Personally, I prefer this three line method over all of the much larger solutions proposed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T21:26:38.317",
"Id": "23554",
"Score": "0",
"body": "Hey! This code borrows heavily from my patented FizzBuzz algorithm implementation. My lawyer will get in touch with you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-09T18:16:25.827",
"Id": "14494",
"ParentId": "1287",
"Score": "2"
}
},
{
"body": "<p>A formula that gives the 8-way compass directions.\nIs working for any value of X and Y .For X=Y=0 the result is undefined.\nI write the formula in the same way ,that i did in excel.</p>\n\n<p>f(X,Y)=MOD(2*(2-SIGN(Y1)-(1+SIGN(X1))*(1-SIGN(Y1^2)))-SIGN(X1*Y1)-0.5*SIGN(Y1*X1^3-X1*Y1^3)</p>\n\n<pre><code> *(1+SIGN(ABS(ABS(X1)-ABS(Y1))/(ABS(X1)+ABS(Y1))-2^0.5+1-2^-22)),8) \n</code></pre>\n\n<p>The formula gives for the East =0 and NE=1,N=2,NW=3,W=4,SW=5,S=6 and SE=7.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:47:23.803",
"Id": "414433",
"Score": "2",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]. (Note: some of the existing answers are very old, and don't represent current best practice for answering!)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:23:14.117",
"Id": "214330",
"ParentId": "1287",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": "1292",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-14T20:18:13.207",
"Id": "1287",
"Score": "13",
"Tags": [
"c#"
],
"Title": "Calculating compass direction"
} | 1287 |
<p>I'll try to keep this as short as I can without losing context - we have a system for online education, where presentations often have a test.</p>
<p>Management has access to a report used for measuring compliance. The report has a few paramaters that need to be selected:</p>
<ul>
<li>A date range to look in (e.g. From 11 March 2010 to 11 March 2011)</li>
<li>One or more online tests (it's a hospital, so some topics have a clinical and a non-clinical version)</li>
<li>One or more departments (so VPs can see all their departments, managers can see just their department, etc.)</li>
<li>There are a couple of options for filtering the results (showing all results, showing only "missing" results - kinda broken at this point, excluding "missing" results)</li>
<li>The report can be pulled as an Excel spreadsheet or as a web page (The Excel option is going to go away due to some issues with Excel 2007, I just haven't had time to remove it)</li>
</ul>
<p><strong>2011-03-17 Addendum:</strong></p>
<p>As per <a href="https://codereview.stackexchange.com/questions/1298/trying-to-speed-up-a-report-that-takes-freaking-forever/1303#1303">munificent's advice</a> (and apparently an earlier me's notes) I used <a href="http://aspprofiler.sourceforge.net/" rel="nofollow noreferrer">http://aspprofiler.sourceforge.net/</a> to get a little more hard data.</p>
<p>Getting the data from SQL Server Express 2005 (which is running on the same machine) seems to be the biggest culprit.</p>
<p><code>Set objResultsRS = objSQLDB.Execute(,,adCmdText)</code> has taken anywhere from 33% to 50% of the processing time.</p>
<p><code>If Not objResultsRS.BOF Then objResultsRS.MoveFirst</code> takes another 20% - 26% of the time - I'll be damned if I can figure out why its even running... since the data is getting dumped into an array, I probably don't need to check BOF and EOF to see if I've got an empty recordset - I just need to check if the array is empty. I'll test to see if that yields any improvements worth reporting.</p>
<p>Nothing else is taking more than 3% of the processing time. I've run a fairly typical report checking system-wide compliance with two online test from 11 March 2010 to 11 March 2011. (a report that is being run constantly this month by just about every VP, and the source of half the support calls I've been taking.)</p>
<p>The SQL for that run ends up looking like:</p>
<pre><code>SELECT LEmp.LawsonID, LEmp.LastName, LEmp.FirstName, LEmp.MidInit, LEmp.winUserName, LPos.Position, LEmp.AccCode, LDept.DisplayName, LEmp.EmpStatus,
Log.VerificationID, Log.WinLogon, Log.Name, Log.Position, Log.Pass, Log.DoneTime, Log.Title
FROM ((Lawson_Employees AS LEmp LEFT JOIN Lawson_DeptInfo AS LDept ON LEmp.AccCode = LDept.AccCode)
INNER JOIN Lawson_PositionCodes AS LPos ON LEmp.PosCode = LPos.PosCode)
LEFT JOIN (
SELECT V.VerificationID, V.WinLogon, V.LawsonID, V.Name, V.Position, V.Pass, V.DoneTime, C.Title
FROM Testing_TestLogs AS V LEFT JOIN Testing_Content AS C ON V.PresID = C.PresID
WHERE V.PresID IN (284,285)
AND V.DoneTime >= '20100311000000' AND V.DoneTime <= '20110311235959' AND V.Name <> 'program check'
) AS Log ON LEmp.LawsonID = Log.LawsonID
WHERE LEmp.CurrentEmp = 1 AND LEmp.AccCode <> '106000'
AND LEmp.EmpStatus NOT IN ('CT','EN','R1','R2','T1','T2','T3')
ORDER BY LEmp.AccCode ASC, LEmp.LastName ASC, LEmp.FirstName ASC, Log.DoneTime ASC;
</code></pre>
<p><strong>2011-03-23 Addendum:</strong></p>
<p>As much as I'd like to devote more time to this PITA, I've got other deadlines pressing in. The sub-query seems to be what is causing the most grief from the SQL Server end (<a href="https://codereview.stackexchange.com/questions/1298/trying-to-speed-up-a-report-that-takes-freaking-forever/1311#1311">thanks Mongus</a>), but I ran out of time to devote too much attention to it.</p>
<p>By duming whatever was returned into the array anyway, and then checking if the array was empty, I was able to get a ~20% improvement. So that section now looks like this:</p>
<pre><code>Dim objSQLDB : Set objSQLDB = CreateObject("ADODB.Command")
objSQLDB.ActiveConnection = strTestingConn
objSQLDB.CommandText = strSQL
Set objResultsRS = objSQLDB.Execute(,,adCmdText)
arrResults = objResultsRS.GetRows(adGetRowsRest)
intTotResults = UBound(arrResults,2)
objResultsRS.Close
Set objResultsRS = Nothing
Set objSQLDB = Nothing
If Not IsArray(arrResults) Then
'No results, show the page then end the script'
objResultsRS.Close
Set objResultsRS = Nothing
Set objSQLDB = Nothing
Response.End()
End If
</code></pre>
<hr>
<p>I'm leaving the (somewhat snipped) code at the bottom for reference/context.</p>
<pre><code>%><!-- #include virtual="/educationtesting/inc_testingstuff.asp" --><%
'--> Removed some variable declarations that are used by the library below, but not in the main code below <--'
%><!-- #include virtual="/forum/inc_func_common.asp"--><%
'--> Removed declarations and validation of incoming data <--'
strSQL = "SELECT LEmp.LawsonID, LEmp.LastName, LEmp.FirstName, LEmp.MidInit, LEmp.winUserName, LPos.Position, LEmp.AccCode, LDept.DisplayName, LEmp.EmpStatus, "
strSQL = strSQL & "Log.VerificationID, Log.WinLogon, Log.Name, Log.Position, Log.Pass, Log.DoneTime, Log.Title "
strSQL = strSQL & "FROM ((Lawson_Employees AS LEmp LEFT JOIN Lawson_DeptInfo AS LDept ON LEmp.AccCode = LDept.AccCode) "
strSQL = strSQL & "INNER JOIN Lawson_PositionCodes AS LPos ON LEmp.PosCode = LPos.PosCode) "
strSQL = strSQL & "LEFT JOIN "
strSQL = strSQL & "(SELECT V.VerificationID, V.WinLogon, V.LawsonID, V.Name, V.Position, V.Pass, V.DoneTime, C.Title "
strSQL = strSQL & "FROM Testing_TestLogs AS V LEFT JOIN Testing_Content AS C ON V.PresID = C.PresID "
strSQL = strSQL & "WHERE V.PresID IN (" & intPresID & ") "
strSQL = strSQL & "AND V.DoneTime >= '" & strFrom & "' AND V.DoneTime <= '" & strTo & "' "
strSQL = strSQL & "AND V.Name <> 'program check') "
strSQL = strSQL & "AS Log ON LEmp.LawsonID = Log.LawsonID "
strSQL = strSQL & "WHERE LEmp.CurrentEmp = 1 "
Select Case LCase(strAccCode)
Case "all"
Case "mgmt"
strSQL = strSQL & "AND (LDept.VP = '" & Session(strCookieURL & "strWinFullName") & "' "
strSQL = strSQL & "OR LDept.SLD = '" & Session(strCookieURL & "strWinFullName") & "' "
strSQL = strSQL & "OR LDept.DeptMgr = '" & Session(strCookieURL & "strWinFullName") & "') "
Case Else
strSQL = strSQL & "AND LEmp.AccCode IN (" & strAccCode & ") "
End Select
'Filter out the suspense account'
strSQL = strSQL & "AND LEmp.AccCode <> '106000' "
'Filter out LOA, FMLA, etc.'
strSQL = strSQL & "AND LEmp.EmpStatus NOT IN ('CT','EN','R1','R2','T1','T2','T3') "
Dim strRptHead : strRptHead = ""
Select Case UCase(Trim(Request.Form("Filter")))
Case "C"
strSQL = strSQL & "AND Log.VerificationID IS NOT NULL "
strSQL = strSQL & "ORDER BY LEmp.AccCode ASC, LEmp.LastName ASC, LEmp.FirstName ASC, Log.DoneTime ASC;"
strRptHead = "Only completed records"
Case "NC"
strSQL = strSQL & "AND Log.VerificationID IS NULL "
strSQL = strSQL & "ORDER BY LEmp.AccCode ASC, LEmp.LastName ASC, LEmp.FirstName ASC;"
strRptHead = "All missing records"
Case Else
strSQL = strSQL & "ORDER BY LEmp.AccCode ASC, LEmp.LastName ASC, LEmp.FirstName ASC, Log.DoneTime ASC;"
strRptHead = "All compliance results"
End Select
Dim objResultsRS, arrResults, intTotResults
Dim objSQLDB : Set objSQLDB = CreateObject("ADODB.Command")
objSQLDB.ActiveConnection = strTestingConn
objSQLDB.CommandText = strSQL
Set objResultsRS = objSQLDB.Execute(,,adCmdText)
If Not objResultsRS.BOF Then objResultsRS.MoveFirst
If objResultsRS.EOF Then
'No results, show the page then end the script'
'--> Snipped code that showed message re: no records, and what may be at issue <--'
objResultsRS.Close
Set objResultsRS = Nothing
Set objSQLDB = Nothing
Response.End()
Else
'Results, drop the recordset into an array and close out the DB connection'
arrResults = objResultsRS.GetRows(adGetRowsRest)
intTotResults = UBound(arrResults,2)
objResultsRS.Close
Set objResultsRS = Nothing
Set objSQLDB = Nothing
End If
'send mime type et al for headings'
Select Case strDisplay
Case "page"
'--> Snipped code to write out HTML header info <--'
Case "excel"
'Returns the result as an Excel spread sheet.'
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "content-disposition","attachment;filename=AllResults_" & strFrom & "_To_" & strTo & ".xls"
'--> Snipped code to write out Excel header info <--'
Case Else
Response.Redirect("oops.asp?Err=BadDisplay")
End Select
Select Case strDisplay
Case "page"
Response.Write("<table class=""fcc iffc c tc tbc"" cellspacing=""0"" style=""font-size:8pt;"">" & vbNewLine)
If LCase(strAccCode) = "mgmt" Then
'--> Show a note to managers re: what to do if a department is/not on the list that should/not be there <--'
End If
'--> Write out the main report header, formatted for a web page <--'
strExcelExtra = ""
Case "excel"
'--> Write out the main report header, formatted for an Excel sheet <--'
strExcelExtra = " style=""mso-number-format:\@;"""
Case Else
Response.Redirect("oops.asp?Err=BadDisplay")
End Select
'--> Removed some declarations for variables used below <--'
'Write out each row of data'
'--> Removed the horridly long chunk of code for writing out each row - profiler showed it was not that big of a time suck <--'
'Done, close up table'
Response.Write("</table>" & vbNewLine)
If strDisplay = "page" Then Response.Write("<h3 class=""c""><a href=""#"" onClick=""window.close()"">Close this window</a></h3>" & vbNewLine & "</center>" & vbNewLine)
Response.Write("</body>" & vbNewLine & "</html>")
%>
</code></pre>
<p><strong>Footnote:</strong>
Don't think it will matter, but I will be stripping out the Excel support sometime in the near future. As a dev team of 1 (and server admin, db admin, designer, tester, maintainer, etc.), there are a couple other projects that need to get finished before I can do that.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T23:23:40.453",
"Id": "2275",
"Score": "1",
"body": "Yeesh! Is it `Set objResultsRS = objSQLDB.Execute(,,adCmdText)` that's taking so long? If so then capture the SQL before executing. People will find that a lot easier to analyse."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T00:31:55.307",
"Id": "2276",
"Score": "0",
"body": "@pdr: not as far as I've been able to tell - it's certainly worth re-visiting."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T02:06:54.507",
"Id": "2278",
"Score": "1",
"body": "You really must do some basic profiling to narrow down where the time is taken. Certainly building the SQL query takes almost no time compared to running it. Processing the results (I didn't read that far) may take a significant amount of time, or not. But you should add some simple timing around the major sections to find out. Then you can ask a more useful question that will lead you to an answer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T20:49:25.463",
"Id": "2298",
"Score": "0",
"body": "@David - as a sanity-check, which points would you reccomend using as reference points?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T00:11:03.420",
"Id": "2303",
"Score": "0",
"body": "@AnonJr - At least time the query since that's probably the culprit. And of course time the whole thing. If you find the query takes 90% of the time, that's where you need to drill down. I'm sure the query you end up building is rather complex, and the only way to see what's happening is to use your database's explain feature which tells you how it will execute the query: what indexes it uses, how many rows it gets along the way, if it does any table scans, etc."
}
] | [
{
"body": "<p>It makes me sad how few people seem to know this basic advice: If you have a program that's slow <em>profile it</em>. It takes five minutes to download a trial of a profiler, hook it up to your app, and see <em>exactly</em> where the bottlenecks are. Computers are much too complicated to reason about performance from first principles anymore.</p>\n\n<p>As long as you have the right algorithm (which you <em>do</em> need to reason about before you get this far) you'll make progress much faster with a profiler than you will just trying to guess at stuff. Almost every time I've had a performance problem, a profiler has revealed it wasn't at all where I thought it was.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T23:34:12.717",
"Id": "2302",
"Score": "0",
"body": "Try googling \"profiler <your language>\" and see what turns up. I'm not that familiar with SQL so I don't know if there's any mistakes there."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T20:37:09.083",
"Id": "2325",
"Score": "0",
"body": "Damnedest thing... I had to increase the buffer size to be able to get full results from the profiler, and now I'm getting different (slightly better) results on the basic stats."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T20:56:21.843",
"Id": "2327",
"Score": "0",
"body": "Cleaning up my earlier comments, and added some information from the profiler - that I'd used 2 years ago and forgotten that I had..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T23:26:59.430",
"Id": "2470",
"Score": "0",
"body": "It's not as optimal as I'd like, but it's as optimal as I have time to make it. Thanks for the profiling reminder."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T02:02:55.213",
"Id": "1303",
"ParentId": "1298",
"Score": "6"
}
},
{
"body": "<p>How large is the data that you are pulling in? </p>\n\n<p>If the Testing_TestLogs table is massive (the name makes me think it might be), have you got indexes on the LawsonID column?</p>\n\n<p>If Testing_Content is massive - have you got an index on the PresID column?</p>\n\n<p>As both of these tables get pulled in to the query the database is having to sort the data by these columns. The more data, the slower this operation will be.</p>\n\n<p>I would recommend getting the exeuction plan of this query to see which joins are the slowest. The right index in the right place makes a massive difference!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T18:36:34.127",
"Id": "2297",
"Score": "0",
"body": "It is massive, and there are indexes on the ID columns. I've tried to get some execution plans, but I'm not sure I'm running them right... my SQL Server knowledge comes more \"trial by fire\" than \"excellence in education\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T09:29:06.330",
"Id": "2307",
"Score": "0",
"body": "In Management Studio select Query -> Include Actual Execution Plan. Then run your query. You will get an Execution Plan tab next to your results. This will be massive, but well worth going over. It shows all the operations that SQL Server had to do together with the Cost. Find the items with the highest cost."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T21:00:02.690",
"Id": "2357",
"Score": "0",
"body": "\"Clustered Index Scan Testing_TestLogs\" seems to cost 92%; Seems to be related to the sub-query."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T13:09:04.207",
"Id": "1311",
"ParentId": "1298",
"Score": "4"
}
},
{
"body": "<p>Since others have answered re: make sure you have proper indexes (any FK'd column and any column you are filtering/selecting on pretty much), and to check you execution plan - I can see a couple of problems.</p>\n\n<p>Just a cursory glance through the proc - I can see there are a large number of non-sargable statements. This prevents effective use of your indexes and will slow the query down considerably on large datasets.</p>\n\n<p>For times, you should use the built in \"BETWEEN\" keyword.</p>\n\n<p><a href=\"http://www.dotnet4all.com/snippets/factsheet%20SQL%20Server.pdf\" rel=\"nofollow\">http://www.dotnet4all.com/snippets/factsheet%20SQL%20Server.pdf</a></p>\n\n<p>Look at the sargability, and checklist for indexes on the above link. It is a great quick-resource.</p>\n\n<p>Also since you made a note of it, you need to check for BOF or EOF otherwise you'll get a 500 when you attempt to access the recordset [if it is empty].</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T21:54:53.210",
"Id": "2398",
"Score": "0",
"body": "My thought on the BOF/EOF was more along the lines of \"since I'm dumping it into an array anyway, it may be faster to check if `arrResults` is an array or not\". I've not had a chance to do some a/b testing yet. (\"other job duties\" and all)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T17:44:36.270",
"Id": "2415",
"Score": "0",
"body": "Using `BETWEEN` has made no difference one way or the other, but dumping the recordset to an array and then checking to see if the array is empty sped things up by ~20%... go figure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T14:44:43.063",
"Id": "1360",
"ParentId": "1298",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1303",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-15T22:05:39.067",
"Id": "1298",
"Score": "3",
"Tags": [
"optimization",
"vbscript",
"asp-classic"
],
"Title": "Trying to speed up a report that takes freaking forever"
} | 1298 |
<p>One of my side projects is a table driven scanner/parser generator, in an effort to reduce the size of the transition table I represent the generated table <code>A[x, y]</code> as <code>A'[x + I[y]]</code> instead of <code>A'[x + y * c]</code>. This allows me to overlap identical parts of the table.</p>
<p>The following is the code responsible for actually arranging the rows. I'm not very happy with it, particularly the number of arrays that need to be constructed. Any improvements to readability/performance/effectiveness would be much appreciated.</p>
<pre><code>/// <remarks>
/// A two dimentional array, or table, can be represented by a single dimentional table
/// where the data for position (x, y) is stored at index x + table_width * y. If the
/// table is read-only then the multiplication can be replaced with an index lookup
/// allowing identical portions of the table to be overlapped thus (depending on the
/// data) reducing the memory footprint of the table.
///
/// The purpose of this class is to take a bunch of rows and try to find an arrangement
/// with a good approximation of the minimal space required. Finding the optimal solution
/// reduces to the "Traveling Sailsman Problem", so a good approximation is sufficient.
///
/// This particular algorithm is intended to work with the characteristics of the sparse
/// state transition tables of the lexer/parser and will probably perform very poorly
/// for other cases.
///
/// Algorithm Overview:
///
/// * If two fragments with the same content are encountered, they are combined with
/// identical offsets.
///
/// * Each fragment gets two tags, one for each end. all start tags are put into one list
/// and all end tags in another.
///
/// * Sort both lists first by "end value" (the very first value for a start tag and the
/// very last value for an end tag) and second by "end length" (the number of
/// consecutive times "end value" appears) in descending order.
///
/// * Make a single pass over both lists at the same time, combining distinct fragments
/// with the longest sequence of an identical value.
///
/// * All remaining fragments are appended end to end.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
internal sealed class TableFragment : IList<int>, ICollection
{
public TableFragment(int[] values, int state)
: this(values, new int[] { state }, new int[] { 0 }, 0) { }
public TableFragment(int[] values, int state, int skip)
: this(values, new int[] { state }, new int[] { -skip }, skip) { }
TableFragment(int[] values, int[] states, int[] offsets, int skip)
{
this._skip = skip;
this._values = values;
this._states = states;
this._offsets = offsets;
}
/// <summary>
/// Attempt to combine multiple TableFragments into a single fragment.
/// </summary>
/// <remarks>
/// This method attempts to minimise the total length of the result by adjusting the
/// offsets so that identical portions overlap.
/// </remarks>
public static TableFragment Combine(IList<TableFragment> fragments)
{
if (fragments == null) throw new ArgumentNullException("fragments");
if (fragments.Count == 0) throw new ArgumentException("fragments list cannot be empty", "fragments");
List<TableFragmentTag> startTags = new List<TableFragmentTag>(fragments.Count);
List<TableFragmentTag> endTags = new List<TableFragmentTag>(fragments.Count);
Dictionary<int, List<TableFragmentTag>> map = new Dictionary<int, List<TableFragmentTag>>();
for (int i = 0; i < fragments.Count; i++)
{
TableFragmentTag startTag;
TableFragmentTag endTag;
int hash;
CreateTags(fragments[i], out startTag, out endTag, out hash);
List<TableFragmentTag> list;
if (!map.TryGetValue(hash, out list))
{
list = new List<TableFragmentTag>();
list.Add(startTag);
map.Add(hash, list);
startTags.Add(startTag);
endTags.Add(endTag);
}
else if (!AddEquivilenceList(list, startTag))
{
startTags.Add(startTag);
endTags.Add(endTag);
}
}
startTags.Sort(Comparison);
endTags.Sort(Comparison);
LinkedList<TableFragmentTag> startFragments = new LinkedList<TableFragmentTag>(startTags);
LinkedList<TableFragmentTag> endFragments = new LinkedList<TableFragmentTag>(endTags);
return Combine(startFragments, endFragments);
}
/// <summary>
/// Indicates the number of "don't care" elements between the offset origin and the first value.
/// </summary>
/// <remarks>
/// This is useful if it is known that the first N elements can never be used, and as such can have
/// any value.
/// </remarks>
public int Skip
{
[DebuggerStepThrough]
get { return _skip; }
}
public int this[int index]
{
[DebuggerStepThrough]
get { return _values[index]; }
}
/// <summary>
/// Gets the offset into this fragment where the values associated with the given state can be found.
/// </summary>
/// <remarks>
/// Returns null if the state was never combined into this fragment.
/// </remarks>
public int? GetOffset(int state)
{
int index = Array.BinarySearch(_states, state);
return index < 0 ? new int?() : _offsets[index];
}
static void CreateTags(TableFragment fragment, out TableFragmentTag startTag, out TableFragmentTag endTag, out int hash)
{
if (fragment == null) throw new ArgumentNullException("fragment");
int[] values = fragment._values;
int startIndex = 0;
int startValue = values[0];
int endIndex = 0;
int endValue = values[values.Length - 1];
uint currentHash = 0;
bool startSet = false;
for (int i = 0; i < values.Length; i++)
{
int val = values[i];
if (!startSet && val != startValue)
{
startSet = true;
startIndex = i;
}
if (val != endValue)
{
endIndex = i;
}
currentHash = unchecked(((currentHash >> 5) | (currentHash << 27)) ^ (uint)val);
}
startTag = new TableFragmentTag()
{
Fragment = fragment,
EndLen = startSet ? startIndex : values.Length,
EndValue = startValue,
};
endTag = new TableFragmentTag()
{
Fragment = fragment,
EndLen = startSet ? values.Length - endIndex - 1 : values.Length,
EndValue = endValue,
};
startTag.Partner = endTag;
endTag.Partner = startTag;
hash = (int)currentHash;
}
/// <summary>
/// Replace the TableFragments referenced by the two tags with a single fragment that
/// contains their combined values.
/// </summary>
/// <remarks>
/// The end of tag1 will be made to overlap the start of tag2 as far as possible.
/// </remarks>
static void Combine(TableFragmentTag tag1, TableFragmentTag tag2)
{
int overlap;
if (tag1.EndValue != tag2.EndValue)
{
overlap = 0;
}
else
{
overlap = Math.Min(tag1.EndLen, tag2.EndLen);
}
TableFragment fragment = Combine(tag1.Fragment, tag2.Fragment, overlap);
tag1.Partner.Fragment = fragment;
tag2.Partner.Fragment = fragment;
tag1.Partner.Partner = tag2.Partner;
tag2.Partner.Partner = tag1.Partner;
}
static TableFragment Combine(TableFragment fragment1, TableFragment fragment2, int overlap)
{
int[] values1 = fragment1._values;
int[] values2 = fragment2._values;
int[] states1 = fragment1._states;
int[] states2 = fragment2._states;
int[] offsets1 = fragment1._offsets;
int[] offsets2 = fragment2._offsets;
int offset = values1.Length - overlap;
int[] values = new int[offset + values2.Length];
int[] states = new int[states1.Length + states2.Length];
int[] offsets = new int[states.Length];
Array.Copy(values1, values, offset);
Array.Copy(values2, 0, values, offset, values2.Length);
int read1 = 0;
int read2 = 0;
int write = 0;
while (read1 < states1.Length && read2 < states2.Length)
{
int diff = states1[read1] - states2[read2];
if (diff == 0)
throw new InvalidOperationException("attempting to combine 2 fragments that both contain the state " + states1[read1]);
if (diff < 0)
{
states[write] = states1[read1];
offsets[write] = offsets1[read1];
write++;
read1++;
}
else
{
states[write] = states2[read2];
offsets[write] = offsets2[read2] + offset;
write++;
read2++;
}
}
while (read1 < states1.Length)
{
states[write] = states1[read1];
offsets[write] = offsets1[read1];
write++;
read1++;
}
while (read2 < states2.Length)
{
states[write] = states2[read2];
offsets[write] = offsets2[read2] + offset;
write++;
read2++;
}
return new TableFragment(values, states, offsets, Math.Max(fragment1.Skip, fragment2.Skip - offset));
}
static TableFragment Combine(LinkedList<TableFragmentTag> startFragmentTags, LinkedList<TableFragmentTag> endFragmentTags)
{
LinkedList<TableFragmentTag> finalFragments = new LinkedList<TableFragmentTag>();
while (startFragmentTags.Count > 0 && endFragmentTags.Count > 0)
{
LinkedListNode<TableFragmentTag> tailNode = startFragmentTags.First;
LinkedListNode<TableFragmentTag> leadNode = endFragmentTags.First;
if (tailNode.Value.Fragment == leadNode.Value.Fragment)
{
// if the tailNode and leadNode reference the same fragment, then try to replace one
// of them as bad things happen when overlapping a fragment with itself.
if (leadNode.Next != null)
{
leadNode = leadNode.Next;
}
else if (tailNode.Next != null)
{
tailNode = tailNode.Next;
}
else
{
startFragmentTags.Remove(tailNode);
finalFragments.AddLast(tailNode);
break;
}
}
int leadEnd = leadNode.Value.EndValue;
int tailStart = tailNode.Value.EndValue;
if (leadEnd < tailStart)
{
endFragmentTags.Remove(leadNode);
}
else if (tailStart < leadEnd)
{
startFragmentTags.Remove(tailNode);
finalFragments.AddLast(tailNode);
}
else
{
endFragmentTags.Remove(leadNode);
startFragmentTags.Remove(tailNode);
TableFragment.Combine(leadNode.Value, tailNode.Value);
}
}
while (startFragmentTags.Count > 0)
{
LinkedListNode<TableFragmentTag> node = startFragmentTags.First;
startFragmentTags.Remove(node);
finalFragments.AddLast(node);
}
return ForceCombine(finalFragments);
}
/// <summary>
/// Append all fragments end to end without any attempt to overlap any of them.
/// </summary>
/// <remarks>
/// Used as a last resort for when all attempts to overlap the fragments have failed.
/// </remarks>
static TableFragment ForceCombine(LinkedList<TableFragmentTag> finalFragments)
{
int totalLen = 0;
int totalStates = 0;
foreach (TableFragmentTag tag in finalFragments)
{
TableFragment fragment = tag.Fragment;
totalLen += fragment._values.Length;
totalStates += fragment._states.Length;
}
int newSkip = 0;
int[] newValues = new int[totalLen];
int[] newStates = new int[totalStates];
int[] newOffsets = new int[totalStates];
totalLen = 0;
totalStates = 0;
foreach (TableFragmentTag tag in finalFragments)
{
TableFragment fragment = tag.Fragment;
int[] values = fragment._values;
int[] states = fragment._states;
int[] offsets = fragment._offsets;
newSkip = Math.Max(newSkip, tag.Fragment.Skip - totalLen);
Array.Copy(states, 0, newStates, totalStates, states.Length);
Array.Copy(values, 0, newValues, totalLen, values.Length);
for (int i = 0; i < states.Length; i++)
{
newOffsets[i + totalStates] = offsets[i] + totalLen;
}
totalLen += values.Length;
totalStates += states.Length;
}
Array.Sort(newStates, newOffsets);
return new TableFragment(newValues, newStates, newOffsets, newSkip);
}
/// <remarks>
/// check for fragments with the same values, if one is found then combine them, otherwise add startTag to the list.
/// </remarks>
static bool AddEquivilenceList(List<TableFragmentTag> list, TableFragmentTag startTag)
{
for (int i = 0; i < list.Count; i++)
{
TableFragmentTag existingTag = list[i];
TableFragment existing = existingTag.Fragment;
TableFragment fragment = startTag.Fragment;
if (ValuesEquivilent(existing._values, fragment._values))
{
existingTag.Partner.Fragment = existingTag.Fragment = Combine(existing, fragment, existing.Count);
return true;
}
}
list.Add(startTag);
return false;
}
static bool ValuesEquivilent(int[] values1, int[] values2)
{
if (values1.Length != values2.Length) return false;
for (int i = 0; i < values1.Length; i++)
{
if (values1[i] != values2[i]) return false;
}
return true;
}
static int Comparison(TableFragmentTag tag1, TableFragmentTag tag2)
{
int diff = tag1.EndValue - tag2.EndValue;
return diff != 0 ? diff : tag2.EndLen - tag1.EndLen;
}
#region IList<int> Members
// ...
#endregion
#region ICollection<int> Members
public void CopyTo(int[] array, int arrayIndex)
{
Array.Copy(_values, 0, array, arrayIndex, _values.Length);
}
// ...
#endregion
#region ICollection Members
// ...
#endregion
#region IEnumerable<int> Members
// ...
#endregion
#region IEnumerable Members
// ...
#endregion
/// <summary>
/// The TableFragmentTag class is a reference to one end of a TableFragment, either the start or the end.
/// </summary>
[DebuggerDisplay("{EndValue} x {EndLen}")]
sealed class TableFragmentTag
{
/// <summary>
/// The Fragment this tag references.
/// </summary>
public TableFragment Fragment { get; set; }
/// <summary>
/// The tag for the other end of the fragment.
/// </summary>
public TableFragmentTag Partner { get; set; }
/// <summary>
/// The value at this end of the fragment.
/// </summary>
public int EndValue { get; set; }
/// <summary>
/// The number of consecitive times EndValue appears.
/// </summary>
public int EndLen { get; set; }
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
readonly int _skip;
readonly int[] _values;
readonly int[] _states;
readonly int[] _offsets;
}
</code></pre>
<hr>
<p>And here is a simple example of how can be used.</p>
<pre><code>int[][] table = GenerateTable();
TableFragment[] fragments = new TableFragment[table.Length];
for (int state = 0; state < table.Length; state++)
{
fragments[state] = new TableFragment(table[state], state);
}
TableFragment result = TableFragment.Combine(fragments);
int[] A = new int[result.Count + result.Skip];
result.CopyTo(A, result.Skip);
int[] I = new int[table.Length];
for (int state = 0; state < table.Length; state++)
{
I[state] = result.GetOffset(state).Value;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T11:45:04.467",
"Id": "2285",
"Score": "1",
"body": "I feel kinda bad about posting such a large piece of code for review, but I think trimming too much more would compromise the review."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T15:22:21.203",
"Id": "2296",
"Score": "1",
"body": "For starters, at least add documentation on the public methods/properties. Combine? Skip? Offset? Tag?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T08:42:01.083",
"Id": "2305",
"Score": "3",
"body": "I have added comments, unfortunately a lack of comments is one of my bad habits I need to work on."
}
] | [
{
"body": "<p>Did some reading during the past few days about clean code and I can spot a bit of complexity in yours. Just some things that I think would improve the readability:</p>\n\n<p>Multiple similar blocks like :</p>\n\n<pre><code> states[write] = states1[read1];\n offsets[write] = offsets1[read1];\n write++;\n read1++;\n</code></pre>\n\n<p>if this could be refactored into a function it would mean a + for readability.</p>\n\n<p>Because of the <code>else if</code> I would also replace</p>\n\n<pre><code> if (diff < 0)\n {\n states[write] = states1[read1];\n ---\n }\n else if (diff > 0)\n {\n states[write] = states2[read2];\n ---\n }\n else\n {\n throw new InvalidOperationException ....\n }\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if (diff == 0)\n throw new ....\n\nif (diff > 0)\n{\n ...\n}\nelse\n{\n ...\n}\n</code></pre>\n\n<p>This also looks like duplicate code:</p>\n\n<pre><code> while (read1 < states1.Length)\n {\n states[write] = states1[read1];\n offsets[write] = offsets1[read1];\n write++;\n read1++;\n }\n\n while (read2 < states2.Length)\n {\n states[write] = states2[read2];\n offsets[write] = offsets2[read2] + offset;\n write++;\n read2++;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T08:48:26.770",
"Id": "2306",
"Score": "0",
"body": "I have taken up your suggestion regarding the throw in the else clause, though I'm not entirely sold on it yet. I looked at extracting those blocks you mentioned, but that would require passing more arguments to the extracted method than I am happy with, will need to think about it some more ..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T17:16:10.107",
"Id": "1313",
"ParentId": "1308",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T11:38:43.833",
"Id": "1308",
"Score": "6",
"Tags": [
"c#",
"collections",
"hash-map"
],
"Title": "Overlapping table fragments"
} | 1308 |
<p>As you review this, please keep in mind I'm using Jython 2.1 as shipped with IBM's WebSphere 7.0 (their latest-and-greatest). I don't have decorators, properties, new style objects, or any other Python feature invented in the last decade.</p>
<p>Problem:</p>
<p>Using WebSphere's Jython interface to determine app server configuration information is not exactly fast. I had already begun work on a simple Jython module to encapsulate the convoluted WebSphere Jython API when I decided to try and cache the results of each method invocation. WebSphere configuration details tend not to change very often. </p>
<p>Inspired by Python 3.2's @functools.lru_cache and Python 2.2's properties I came up with:</p>
<pre><code>from org.python.core import PyString, PyTuple
class Getter:
def getter(self,attr,valid_attrs):
if attr == 'valid_attrs': return valid_attrs
if attr not in valid_attrs.keys(): raise AttributeError
attr_value = None
if type(valid_attrs[attr]) == PyString:
function = getattr(self,valid_attrs[attr])
attr_value = function()
elif type(valid_attrs[attr]) == PyTuple:
function = getattr(self,valid_attrs[attr][0])
args = []
kwargs = {}
for arg in valid_attrs[attr][1:]:
if type(arg) == PyTuple:
if len(arg) > 2:
err = ('Named argument tuple %s in %s length > 2.'
% (arg, self.__class__.__name__ ))
raise NameError(err)
kwargs[arg[0]] = arg[1]
elif type(arg) == PyString:
args.append(arg)
else:
err = ('Unknown argument in %s __getattr__ dispatch list'
% self.__class__.__name__ )
raise NameError(err)
attr_value = function(*args,**kwargs)
else:
raise AttributeError
return attr_value
class App(Getter):
def __init__(self, name=None):
if name:
self.app_name = name
else:
print 'App instance requires name.'
raise NameError
def __getattr__(self,attr):
valid_attrs = { 'app_id': ('get_app_id'),
'deployed_nodes': ('get_deployed_nodes'),
'deployed_servers': ('get_deployed_servers'),
}
attr_value = Getter.getter(self,attr,valid_attrs)
setattr(self,attr,attr_value)
return attr_value
def get_app_id(self):
return AdminConfig.getid('/Deployment: %s/' % self.app_name)
def get_deployed_node(self):
### ...
def get_deployed_servers(self):
### ...
</code></pre>
<p>As I use this in other classes I change the function dispatch dict (<code>valid_attrs</code>) as needed.</p>
<p>Is this an evil abuse of <code>__getattr__</code>? Next to code execution speed, I'm most worried about maintainability. Does this trigger a "WTF?" Or, does it make sense when viewed against the limitations of Jython 2.1 and features, such as @property, found in newer versions?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T05:29:10.360",
"Id": "2337",
"Score": "4",
"body": "Were I prone to making uneducated and accusatory statements, I would venture to say that WebSphere is the WTF. Instead, I will just wonder what their rationale is in shipping such an age-old version of Jython. Maybe not very many people are using Jython with WebSphere?"
}
] | [
{
"body": "<p>I'd say calling <code>self.setattr</code> from <code>__getattr__(self, )</code> is borderline abuse in itself.</p>\n\n<p>I guess you are trying to implement lazy attributes, right?</p>\n\n<p>However in your case valid attributes are constant and their values appear constant too, so why not set them at class \"declaration\" time?</p>\n\n<p>Also, python syntax for a tuple with 1 element is <code>(1,)</code> not <code>(1)</code> that you have in valid attrs extensively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-07T09:53:39.733",
"Id": "8733",
"ParentId": "1314",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-16T19:33:06.480",
"Id": "1314",
"Score": "10",
"Tags": [
"jython"
],
"Title": "Encapsulating the WebSphere Jython API"
} | 1314 |
<p>I have a word-wrap algorithm that basically generates lines of text that fit the width of the text. Unfortunately, it gets slow when I add too much text.</p>
<p>I was wondering if I oversaw any major optimizations that could be made. Also, if anyone has a design that would still allow strings of lines or string pointers of lines that is better I'd be open to rewriting the algorithm.</p>
<p>Thanks</p>
<pre><code>void AguiTextBox::makeLinesFromWordWrap()
{
textRows.clear();
textRows.push_back("");
std::string curStr;
std::string curWord;
int curWordWidth = 0;
int curLetterWidth = 0;
int curLineWidth = 0;
bool isVscroll = isVScrollNeeded();
int voffset = 0;
if(isVscroll)
{
voffset = pChildVScroll->getWidth();
}
int AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
int len = getTextLength();
int bytesSkipped = 0;
int letterLength = 0;
size_t ind = 0;
for(int i = 0; i < len; ++i)
{
//get the unicode character
letterLength = _unicodeFunctions.bringToNextUnichar(ind,getText());
curStr = getText().substr(bytesSkipped,letterLength);
bytesSkipped += letterLength;
curLetterWidth = getFont().getTextWidth(curStr);
//push a new line
if(curStr[0] == '\n')
{
textRows.back() += curWord;
curWord = "";
curLetterWidth = 0;
curWordWidth = 0;
curLineWidth = 0;
textRows.push_back("");
continue;
}
//ensure word is not longer than the width
if(curWordWidth + curLetterWidth >= AdjWidthMinusVoffset &&
curWord.length() >= 1)
{
textRows.back() += curWord;
textRows.push_back("");
curWord = "";
curWordWidth = 0;
curLineWidth = 0;
}
//add letter to word
curWord += curStr;
curWordWidth += curLetterWidth;
//if we need a Vscroll bar start over
if(!isVscroll && isVScrollNeeded())
{
isVscroll = true;
voffset = pChildVScroll->getWidth();
AdjWidthMinusVoffset = getAdjustedWidth() - voffset;
i = -1;
curWord = "";
curStr = "";
textRows.clear();
textRows.push_back("");
ind = 0;
curWordWidth = 0;
curLetterWidth = 0;
curLineWidth = 0;
bytesSkipped = 0;
continue;
}
if(curLineWidth + curWordWidth >=
AdjWidthMinusVoffset && textRows.back().length() >= 1)
{
textRows.push_back("");
curLineWidth = 0;
}
if(curStr[0] == ' ' || curStr[0] == '-')
{
textRows.back() += curWord;
curLineWidth += curWordWidth;
curWord = "";
curWordWidth = 0;
}
}
if(curWord != "")
{
textRows.back() += curWord;
}
updateWidestLine();
}
</code></pre>
| [] | [
{
"body": "<p>I have some high-level advice based on a cursory read of your code. It would really help if you could refactor it into multiple methods as this function is too long and does too much. That won't help your speed, but it will make it easier for others to grok your code and provide more advice.</p>\n\n<p><strong>Profile your code</strong></p>\n\n<p>You can't hope to make things faster in an orderly fashion without finding out what parts take the most time. Yes, you can devise a faster algorithm, but you might end up spending days optimizing an O(n^2) algorithm to O(log n) only to find out that part took 1ms anyway.</p>\n\n<p><strong>Split each word first</strong></p>\n\n<p>If you only split at word boundaries, you may as well seek forward for a boundary and extract the substring in one call.</p>\n\n<p><strong>Calculate word widths instead of letter widths</strong></p>\n\n<p>First, when I wrote a similar function in Java many years ago, the cost of calling calculating the width of a string had a fairly high overhead that didn't change with the length of the string. Getting the width a character at a time was significantly more costly than calculating the length of a word. Also, since there may be kerning involved that adjusts the space between letters based on the letter pairs, you can't add up the character widths to arrive at the word width.</p>\n\n<p><strong>If you end up needing to split a word midway, use a binary search to find the cutoff point</strong></p>\n\n<p>This goes with the two above, but you won't really know the best route until you profile.</p>\n\n<p><strong>Make sure you're not using a linked list</strong></p>\n\n<p>You add the string to the list (<code>vector</code>?) and modify it for each character. If this is a linked list instead of an array, it will be very costly. I'm not very familiar with the STL if that's what you're using (those declarations would help), so maybe it maintains a tail pointer. In any case, I would build each line and add it to the list only once it's complete even if you're using an array-based vector. It just seems cleaner.</p>\n\n<p><strong>Show a disabled scroll bar instead of restarting once you determine that scrolling is necessary</strong></p>\n\n<p>Really, a disabled scroll bar isn't that horrendous. ;)</p>\n\n<p><strong>Calculate the widest line as you wrap</strong></p>\n\n<p>I'm betting that the work done in <code>updateWidestLine()</code> is very similar to what you're already doing in <code>makeLinesFromWordWrap()</code>. Take advantage of that and maintain a maxLength local variable as you do the wrapping.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T11:01:56.947",
"Id": "2311",
"Score": "1",
"body": "Regarding list vs. vector, a `std::list` is (equivalent to) a doubly-linked list with an end pointer, so `push_back()` does take constant time. However, a `std::vector` is typically faster in most situations, including this case of populating it sequentially, since it will perform fewer memory allocations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T01:29:02.183",
"Id": "1317",
"ParentId": "1316",
"Score": "4"
}
},
{
"body": "<p>One obvious improvement would be to store an array of split points instead of text rows. Say we have this string:</p>\n\n<pre><code>This is some text\n</code></pre>\n\n<p>We find a break point between \"some\" and \"text\". In this algorithm, you have the following stored:</p>\n\n<pre><code>Original string = \"This is some text\"\ntextRows[0] = \"This is some\"\ntextRows[1] = \"text\"\n</code></pre>\n\n<p>The repetition isn't necessary and creating the textRows vector involves a lot of pointless string copying. It'd be better to store this instead:</p>\n\n<pre><code>Original string = \"This is some text\"\ntextSplit[0] = 12\ntextSplit[1] = 16\n</code></pre>\n\n<p>To print the text:</p>\n\n<pre><code>lastSplit = 0\nfor i = 0 to len(textSplit)\n print original text from lastSplit to textSplit[i]\n print linebreak\n lastSplit = textSplit[i]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T17:43:56.253",
"Id": "2320",
"Score": "2",
"body": "+1 Also, depending on how the string class is implemented, you could simply overwrite the spaces where line breaks occur with nulls. This could be done on-the-fly while calculating word widths to avoid all string copying (and undone except at the line breaks)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T10:22:28.683",
"Id": "1320",
"ParentId": "1316",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-16T23:55:27.277",
"Id": "1316",
"Score": "6",
"Tags": [
"c++",
"optimization"
],
"Title": "Optimizing WordWrap Algorithm"
} | 1316 |
<blockquote>
<p><strong>3.1</strong></p>
<p>Write a program that computes the arithmetic sum of a constant
difference sequence:</p>
<pre><code>D0 = A
Dn+1 = Cdn + B
</code></pre>
<p>Run the following values and compare to the closed form solution:</p>
<pre><code>Maximum index = 10,000, a = 1:0; c = 5; b = 2^-15
</code></pre>
</blockquote>
<p>I am not sure I perfectly understand the problem above or how to confirm that I have the correct answer, but I wrote the following short program and I would appreciate any feedback.</p>
<pre><code>(defun d-n-plus-1 (d-n c b) (+ (* d-n c) b))
(defun d-depth (depth d-n c b a)
(if (equal depth 0) (d-n-plus-1 d-n c b)
(d-depth (1- depth)
(if (null d-n) a (d-n-plus-1 d-n c b))
c b a)))
(format t "result: ~a ~%" (d-depth 10000 nil 5 (expt 2 -15) 1))
</code></pre>
<p>In addition, I wrote a version that just uses a loop. I'm not crazy about "loop for x from 1 to depth" or that I used setq in this version. Can you think of a better way? Any other suggestions for this version are also welcome.</p>
<pre><code>(defun d_n+1 (d_n c b) (+ (* d_n c) b))
(defun d-depth (depth d_n c b)
(loop for x from 0 to depth do
(setq d_n (d_n+1 d_n c b)))
d_n)
(format t "result: ~a ~%" (d-depth 10000 1 5 (expt 2 -15)))
</code></pre>
| [] | [
{
"body": "<p>I notice three things about your code:</p>\n\n<ol>\n<li>You're relying on tail-recursion. This is okay if you know your program will only ever run on implementations that perform tail call optimization, but you should be aware that the Common Lisp standard does not require TCO (and more practically speaking some implementations do indeed not offer it). So if you want your program to be portable, you should rewrite it using a loop¹.</li>\n<li>Your <code>d-depth</code> function takes <code>d-n</code> and <code>a</code> as parameters, but only uses <code>a</code> in place of <code>d-n</code> if <code>d-n</code> is <code>nil</code>. It'd make more sense to me to remove the <code>a</code> parameter and instead pass in the <code>a</code> value as the initial value for <code>d-n</code> (instead of <code>nil</code>).</li>\n<li>I would also write <code>d_n</code> instead of <code>d-n</code> to emphasize that <code>n</code> is an index, which is usually written using an underscore in ASCII. Also I'd call <code>d-n-plus-1</code> <code>d_n+1</code> instead, there's no reason to spell out \"plus\" in lisp.</li>\n</ol>\n\n<hr>\n\n<p>In response to your update:</p>\n\n<blockquote>\n <p>I'm not crazy about \"loop for x from 1 to depth\" or that I used setq in this version. Can you think of a better way?</p>\n</blockquote>\n\n<p><code>for x from 1 to depth</code> is equivalent to <code>repeat depth</code> (unless you actually use <code>x</code>, which you don't). However in your code you're actually starting at 0, not 1 so you'd need <code>repeat (+ 1 x)</code> to get the same number of iterations.</p>\n\n<p>The setq can be replaced using the <code>for var = start then replacement-form</code> syntax. The result would be something like this:</p>\n\n<pre><code>(defun d-depth (depth a c b)\n (loop repeat (+ 1 depth) \n for d_n = a then (d_n+1 d_n c b)\n finally (return d_n)))\n</code></pre>\n\n<hr>\n\n<p>¹ Or in scheme :p</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T03:48:09.773",
"Id": "2335",
"Score": "0",
"body": "If I want to get started with scheme on OSX, do you have any software recommendations?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T04:27:47.883",
"Id": "2336",
"Score": "1",
"body": "@jaresty: I was mostly kidding about switching to scheme. That being said, if you do want to take a look at scheme, racket seems to be the most popular implementation currently and is available on OSX."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T12:52:22.550",
"Id": "2341",
"Score": "0",
"body": "+1 for starting with [Racket](http://racket-lang.org/download/). Their [docs/tutorials](http://docs.racket-lang.org/) are amazing, and their [libraries](http://planet.racket-lang.org/)/[package system](http://docs.racket-lang.org/planet/index.html) are fairly extensive (they still have a gap in document generation; last I checked my own v0.001 postscript library is the only semi-helpful module in that vein). Though I have to point out, as a former Racketeer, I'm somewhat biased."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T03:49:24.077",
"Id": "2405",
"Score": "0",
"body": "What are the advantages/disadvantages of learning Common Lisp vs. Scheme?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T03:58:34.833",
"Id": "2406",
"Score": "0",
"body": "@jaresty: [This answer](http://stackoverflow.com/questions/108201/common-lisp-or-scheme/108221#108221) contains a good summary of the differences between the two (though it's possibly a bit biased given the source that has been quoted)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T17:29:34.363",
"Id": "1328",
"ParentId": "1318",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1328",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T05:56:07.507",
"Id": "1318",
"Score": "3",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Compute arithmetic sum of a constant difference sequence"
} | 1318 |
<p>I was asked to update a business rule to allow a specific column to be added. Because our datalayer uses only DataSets as an interface to the database that is what we work with in the business layer.</p>
<p>Here I have created a couple of <code>DataTable</code> and <code>DataRow</code> extensions to use for this businessrule and I would like your opinion on things I might have missed.
This is the method I use to search for changes:</p>
<pre><code>private static bool hasColumnChanged(StringComparison stringComparison, bool ignoreWhitespace, DataRow row, DataColumn col)
{
bool isEqual = true;
if (row[col, DataRowVersion.Original] != DBNull.Value && row[col, DataRowVersion.Current] != DBNull.Value)
{
if (ignoreWhitespace)
isEqual = row[col, DataRowVersion.Original].ToString().Trim().Equals(row[col, DataRowVersion.Current].ToString().Trim(), stringComparison);
else
isEqual = row[col, DataRowVersion.Original].ToString().Equals(row[col, DataRowVersion.Current].ToString(), stringComparison);
}
else
isEqual = row[col, DataRowVersion.Original].Equals(row[col, DataRowVersion.Current]);
return !isEqual;
}
</code></pre>
<p>And these are simply the extensions using the code:</p>
<pre><code>public static List<DataColumn> GetChangedColumns(this DataTable table)
{
return table.GetChangedColumns(StringComparison.InvariantCultureIgnoreCase, false);
}
public static List<DataColumn> GetChangedColumns(this DataTable table, bool ignoreWhitespace)
{
return table.GetChangedColumns(StringComparison.InvariantCultureIgnoreCase, ignoreWhitespace);
}
public static List<DataColumn> GetChangedColumns(this DataTable table, StringComparison stringComparison, bool ignoreWhitespace)
{
if (table == null) throw new ArgumentNullException("table");
List<DataColumn> columnsChanged = new List<DataColumn>();
foreach (DataRow row in table.GetChanges().Rows)
{
foreach (DataColumn col in row.Table.Columns)
{
if (!columnsChanged.Contains(col) && hasColumnChanged(stringComparison, ignoreWhitespace, row, col))
columnsChanged.Add(col);
}
}
return columnsChanged;
}
public static List<DataColumn> GetChangedColumns(this DataRow row)
{
return row.GetChangedColumns(StringComparison.InvariantCultureIgnoreCase, false);
}
public static List<DataColumn> GetChangedColumns(this DataRow row, bool ignoreWhitespace)
{
return row.GetChangedColumns(StringComparison.InvariantCultureIgnoreCase, ignoreWhitespace);
}
public static List<DataColumn> GetChangedColumns(this DataRow row, StringComparison stringComparison, bool ignoreWhitespace)
{
if (row == null) throw new ArgumentNullException("row");
List<DataColumn> columnsChanged = new List<DataColumn>();
foreach (DataColumn col in row.Table.Columns)
{
if (!columnsChanged.Contains(col) && hasColumnChanged(stringComparison, ignoreWhitespace, row, col))
columnsChanged.Add(col);
}
return columnsChanged;
}
</code></pre>
<p>To test the above code I use this simple unit test:</p>
<pre><code>[TestMethod]
public void DataTableAndDataRowGetChangedColumns()
{
DataSet ds = GetDummyDataSet();
ds.Tables[0].Rows[0][3] = DateTime.Now;
ds.Tables[0].Rows[0][2] = ds.Tables[0].Rows[1][2].ToString() + " ";
ds.Tables[0].Rows[0][1] = DBNull.Value;
List<DataColumn> changesForRow = ds.Tables[0].Rows[0].GetChangedColumns(true);
List<DataColumn> changesForTable = ds.Tables[0].GetChangedColumns(true);
// For now we just verify if the amount of changes is the same (ez way out)
Assert.IsTrue(changesForRow.Count.Equals(changesForTable.Count));
}
</code></pre>
<p>In the business rule I have implemented this piece of code which verifies if there are other datacolumns that have changed:</p>
<pre><code>List<DataColumn> columnsChanged = dsChanges.Tables[0].GetChangedColumns(true);
if(columnsChanged.Any(c=>!c.ColumnName.Equals("DateUntill", StringComparison.InvariantCultureIgnoreCase)))
throw new BusinessException("This premium can not be changed, only DateUntill can still change");
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p><code>hasColumnChanged</code> method. Inside first <code>if</code> you have two almost same lines. Duplicated code should be extracted:</p>\n\n<pre><code>if (row[col, DataRowVersion.Original] != DBNull.Value && row[col, DataRowVersion.Current] != DBNull.Value) \n{ \n string originalVersionToCompare = row[col, DataRowVersion.Original].ToString();\n string currentVersionToCompare = row[col, DataRowVersion.Current].ToString();\n if (ignoreWhitespace)\n {\n originalVersionToCompare = originalVersionToCompare.Trim();\n currentVersionToCompare = currentVersionToCompare.Trim();\n }\n isEqual = originalVersionToCompare.Equals(currentVersionToCompare, stringComparison);\n} \n</code></pre></li>\n<li><p>If you have .Net 4.0 then 6 <code>GetChangedColumns</code> methods I would refactor into 2 with optional parameters.</p></li>\n<li><p><code>foreach</code> inside <code>GetChangedColumns</code> for <code>DataRow</code> looks like a copypaste. I cannot imagine a situation when <code>columnsChanged.Contains(col)</code> will be true in this method.</p></li>\n<li><p><code>hasColumnChanged</code> seems to be named incorrectly. It should be <code>hasCellChanged</code> since it checks for intersection of row and column. Maybe also <code>PascalCase</code>?</p></li>\n<li><p>LINQify it!</p>\n\n<p>Original:</p>\n\n<pre><code>List<DataColumn> columnsChanged = new List<DataColumn>();\nforeach (DataRow row in table.GetChanges().Rows)\n{\n foreach (DataColumn col in row.Table.Columns)\n {\n if (!columnsChanged.Contains(col) && hasColumnChanged(stringComparison, ignoreWhitespace, row, col))\n columnsChanged.Add(col);\n }\n}\nreturn columnsChanged;\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>return table.GetChanges().Rows.Cast<DataRow>()\n .SelectMany(dr => table.Columns.Cast<DataColumn>(), (row, column) => new {row, column})\n .Where(c => hasColumnChanged(stringComparison, ignoreWhitespace, c.row, c.column))\n .Select(c => c.column)\n .Distinct()\n .ToList();\n</code></pre></li>\n<li><p><code>DateUntill</code> - double <code>l</code>?</p></li>\n<li><p>Why do you compare items by casting them to string? Why don't you compare them as objects?</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T10:40:06.867",
"Id": "2308",
"Score": "0",
"body": "Wauw this is some really good feedback. I thought my initial code was a very good start so I wouldn't get much suggested changes. But you've made it much clearer and taught me a thing or two :-) I'm using camelCasing on the private methods as this is our inhouse coding convention. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T10:47:17.480",
"Id": "2309",
"Score": "0",
"body": "7. I compare them by string so I'm able to specify a StringComparison type, else I have to check if the column datatype is of string first. In the end I don't see the problem in doing this as the result of \"1\"==\"1\" equals 1==1. And this is true for all datatypes since the conversion from datatype to string is the same for both."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T10:57:11.570",
"Id": "2310",
"Score": "0",
"body": "@Peter, I would better add `string` type check other than remembering how different objects are converted to string. For example usually `DateTime.ToString()` doesn't print milliseconds so your comparison will not catch changes in milliseconds. That's just an example, probably it won't be an often situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-17T12:28:57.160",
"Id": "24022",
"Score": "0",
"body": "On `5.`: The original is clearer, so I would prefer it. Maintainability trumps most other values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T10:42:49.750",
"Id": "56924",
"Score": "1",
"body": "Actually, optional arguments is not a feature of .net 4.0, but of the c# 4.0 compiler (which is included in VS2010 and **can be used also with .net 3.5 for example**)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-09T20:37:51.683",
"Id": "176166",
"Score": "1",
"body": "Though I have a question, shouldn't you simply use: !Equals(row[col, DataRowVersion.Original], row[col, DataRowVersion.Current])?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T10:23:06.373",
"Id": "1321",
"ParentId": "1319",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "1321",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T09:39:36.007",
"Id": "1319",
"Score": "16",
"Tags": [
"c#"
],
"Title": "Verify which columns have changed in a datatable or datarow"
} | 1319 |
<p>I have the following 'custom' tree data structure. This concept was to be thought of as, if given ("abb", 20) and ("abc", 30), then</p>
<blockquote>
<pre><code>Tree['a']['b']['b'] == 20
</code></pre>
</blockquote>
<p></p>
<blockquote>
<pre><code>Tree['a']['b']['c'] == 30
</code></pre>
</blockquote>
<p>Or</p>
<blockquote>
<pre><code>a
\
b
/ \
b c
</code></pre>
</blockquote>
<p>With b == 30, and c == 20.</p>
<p>Therefore taking up very limited space, and a very fast search.
However, as depth increases, the number of bytes for a fully explored tree was exponential. In the above case, 4 * 256 bytes were required for valid indexing to occur. This was not good.</p>
<p>It now works in the following way; for each branch, compare its value against the n character; i.e. introducing a worst case O(256) character comparison for each depth. This is not ideal, and what I want to attempt to change.</p>
<hr>
<p>The other question was (and still is), what is it? I couldn't quite classify it as anything but a Tree; nor relate it to any <code>std::</code> containers for comparison. It is very good at what it does though, out-performing a <code>std::map</code> with small strings and very large strings (sizes ~20, ~500 respectively); past 600, the data structure begins to get too heavy.</p>
<p>Obviously, this code is a bit sketchy in how it handles the templates at the moment. A number of things could go wrong, but my interest (other than classification) is on improving this data structure.</p>
<pre><code>template <class K, class V>
class Tree {
unsigned int depth;
Tree* parent;
std::vector<Tree> branches;
public:
K key;
V val;
int n_trees;
Tree(K key = 0, int depth = 0, Tree* parent = 0) : depth(depth), parent(parent), key(key) {
val = 0;
n_trees = 0;
inc();
}
void inc() {
if (parent) parent->inc();
n_trees++;
}
void add(const K* search, const unsigned int length, const V value) {
const int index = search[depth];
if (length <= depth) {
val = value;
return;
}
for (unsigned int i = 0; i < branches.size(); ++i) {
if (branches[i].key == index) {
branches[i].add(search, length, value);
return;
}
}
branches.push_back(
Tree(index, depth + 1, this)
);
branches.back().add(search, length, value);
}
V find(const K* search, const unsigned int length) {
const int index = search[depth];
if (length <= depth) {
return val;
}
for (unsigned int i = 0; i < branches.size(); ++i) {
if (branches[i].key == index) {
return branches[i].find(search,length);
}
}
return 0; // won't work for all types lol
}
};
</code></pre>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<p>You are using a vector for your branches but you are using an index loop to iterate through the vector.<br/>\nI'd consider using the vector iterator.<br/>\nThis will make your code a bit clearer and versatile (if you decide to change the container type for example). Will also get rid of the double branches[i] access in each loop.</p>\n\n<p>Should the n_trees be public? You could write a get function but I'm guessing the client code shouldn't be allowed to change that.</p>\n\n<p>For the return value at the end, if you cast it to V, I think that might work for all types, although I'm not sure about that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T22:14:31.933",
"Id": "1336",
"ParentId": "1322",
"Score": "5"
}
},
{
"body": "<p>Why do you have <code>m_parent</code>? I don't think there are any reasonable operations on a trie that require a parent pointer in each node, and removing it can reduce the space used a lot.</p>\n\n<hr>\n\n<p>I don't love using a <code>depth</code> argument in <code>add</code>. I'd use the following instead:</p>\n\n<pre><code>void add(const std::string& key, const T& value) {\n return add(key.data(), key.size(), value);\n}\nvoid add(const char *key, const T& value) {\n return add(key, std::strlen(key), value);\n}\nvoid add(const char* key, std::size_t len, const T& value); // impl below\n</code></pre>\n\n<hr>\n\n<p>I suggest that you keep the children sorted by <code>m_key</code>. Write a comparison functor like so:</p>\n\n<pre><code>struct KeyLessThan {\n bool operator()(const PrefixTree& l, const PrefixTree& r) const {\n return l.m_key < r.m_key;\n }\n bool operator()(const PrefixTree& tree, char c) const {\n return l.m_key < c;\n }\n};\n</code></pre>\n\n<p>Now you can rewrite <code>add</code> like this (using the signature above):</p>\n\n<pre><code>void PrefixTree::add(const char* key, std::size_t len, const T& value) {\n assert(len >= 0);\n if (len == 0) {\n m_value = value;\n return;\n }\n auto it = std::lower_bound(begin(m_branches), end(m_branches),\n *key, KeyLessThan());\n if (it == end || it->m_key != *key) {\n it = m_branches.emplace(it, *key);\n }\n it->add(key + 1, len - 1, value);\n}\n</code></pre>\n\n<p>The size of <code>m_branches</code> is bounded to be quite small (256 elements in theory; in practice if you're doing English words only it'll be 26 or 52 at the root and much smaller in interior nodes), so this should be quite fast, and it'll make <code>find</code> faster.</p>\n\n<hr>\n\n<p>Speaking of <code>m_branches</code>, <code>m_children</code> would be a more usual name for it.</p>\n\n<hr>\n\n<p>It's not really clear that you want <code>find</code> to return a <code>T*</code>; it's odd to give out handles to internal memory in a data structure like this. I would make the signature one of</p>\n\n<pre><code>const T* find(const std::string& key) const\nstd::pair<bool, const T&> find(const std::string& key) const\n</code></pre>\n\n<p>or</p>\n\n<pre><code>std::pair<bool, T> find(const std::string& key) const\n</code></pre>\n\n<p>(if you have access to a C++14 implementation, even better is </p>\n\n<pre><code>std::optional<T> find(const std::string& key) const\n</code></pre>\n\n<p>Whichever you choose, use the same overloads as with <code>add</code> for <code>const char *</code>, etc.</p>\n\n<hr>\n\n<p>It is very weird to me to see an <code>#include</code> that's not at the top of the file, and to see <code>printf</code>s in the middle of a C++ file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T04:21:18.367",
"Id": "45452",
"Score": "0",
"body": "Thanks for your suggestions!\nThe random include was because these code snippets were plastered together for the example. The `printf`s were just debugging."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T03:09:51.997",
"Id": "28857",
"ParentId": "1322",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T11:29:19.817",
"Id": "1322",
"Score": "6",
"Tags": [
"c++",
"tree"
],
"Title": "Optimising a custom tree data structure"
} | 1322 |
<blockquote>
<p><strong>4.2 Machine Epsilon</strong></p>
<p>Find the floating point number epsi that has
the the following properties:</p>
<ol>
<li>1.0+epsi is greater than 1.0 and</li>
<li>Let m b e any number less than epsi. Then 1.0+m is equal to 1.0.</li>
</ol>
<p>epsi is called machine epsilon. It is of great importance in understanding floating point numbers.</p>
</blockquote>
<p>I have written the following program to try and find my machine epsilon value to a given search depth (10). Do you have any ideas how I could write this program better?</p>
<pre><code>(defpackage :find-epsi (:use cl))
(in-package :find-epsi)
(defun smaller-scale (&OPTIONAL (epsi 1.0)) (if (> (+ 1.0 epsi) 1.0) (smaller-scale (/ epsi 10)) epsi))
(defun bigger (epsi inc-unit) (if (< (+ 1.0 epsi) 1.0) (bigger (+ epsi inc-unit) inc-unit) epsi))
(defun smaller (epsi dec-unit) (if (> (+ 1.0 epsi) 1.0) (smaller (+ epsi dec-unit) dec-unit) epsi))
(defun find-epsi (&OPTIONAL (search-depth 10) (epsi (smaller-scale)) (incdec-unit epsi))
(if (= search-depth 0) epsi (find-epsi (1- search-depth) (bigger (smaller epsi incdec-unit) incdec-unit) incdec-unit)))
(format t "epsi: ~a ~%" (find-epsi))
</code></pre>
<p>It seems that it should be much simpler to find epsilon than I originally thought. What do you think about the following program?</p>
<pre><code>(defpackage :find-epsi (:use cl))
(in-package :find-epsi)
(defun find-epsi (&OPTIONAL (epsi 1.0))
(if (> (+ 1.0 epsi) 1.0) ; if the variable epsi is still significant
(find-epsi (/ epsi 2)) ; halve it and try again
epsi)) ; otherwise, we have found epsilon
(format t "epsi: ~a ~%" (find-epsi))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T22:55:06.343",
"Id": "2334",
"Score": "0",
"body": "As a general note you should get used to writing comments and (at least in this case) shorter lines."
}
] | [
{
"body": "<p>If we assume that a float is represented in memory as a (sign, mantissa, exponent) tuple, and assume a radix of 2, then we can find the machine epsilon exactly. That is, if we can assume the machine stores floats using base-2 representations of the mantissa and exponent, then we know that:</p>\n\n<ul>\n<li>The machine will store a value of <code>1</code> in floating point exactly - this would be stored as <code>1</code> for the mantissa, and <code>0</code> for the exponent, i.e. <code>1 * 2^0</code>.\n<li>The machine will store all powers of two that it can represent using a single bit in the mantissa, and by varying the exponent. E.g. <code>1/4</code> could be represented as <code>1 * (2 ^ -2)</code>. Any representable power of two will be stored without losing information.\n<li><code>1 + epsi</code> will be the smallest value greater than 1 that can be stored in the mantissa of the floating-point number.\n</ul>\n\n<p>EDIT</p>\n\n<p>The second version looks much better than the first, but I believe there's an off-by-one error in the number of times you recurse in <code>find-epsi</code>. I suggest that you create a test function, to see if your result is the machine epsilon:</p>\n\n<pre><code>(defun epsi-sig-p (epsi)\n (> (+ 1.0 epsi) 1.0))\n</code></pre>\n\n<p>You'll probably find that <code>(is-sig (find-epsi))</code> is <code>#f</code>... This also suggests that you can refactor (under the <A HREF=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY principle</A>) <code>find-epsi</code> to use this test function in <code>find-epsi</code>:</p>\n\n<pre><code>(defun find-epsi (&OPTIONAL (epsi 1.0))\n (if (epsi-sig-p epsi)\n (find-epsi (/ epsi 2))\n epsi))\n</code></pre>\n\n<p>but we didn't change the behavior to fix the calculation, yet. For this, I'd suggest another routine, to check whether we should try the next possible <code>epsi</code>:</p>\n\n<pre><code>(defun next-epsi (epsi) (/ epsi 2))\n(defun is-epsi-p (epsi)\n (and (epsi-sig-p epsi) (not (epsi-sig-p (next-epsi epsi)))))\n(defun find-epsi (&OPTIONAL (epsi 1.0))\n (if (is-epsi-p epsi)\n epsi\n (find-epsi (next-epsi epsi))))\n</code></pre>\n\n<p><code>is-epsi-p</code> should return <code>#t</code>, now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T22:51:09.203",
"Id": "2333",
"Score": "2",
"body": "I'm pretty sure jaresty is going through some collection of exercises voluntarily (or possibly in preparation for an exam), not as homework. It seems unlikely that a university would give out homework at the rate at which he's asking questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T22:38:27.307",
"Id": "1337",
"ParentId": "1324",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1337",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T13:49:47.917",
"Id": "1324",
"Score": "2",
"Tags": [
"lisp",
"common-lisp",
"floating-point"
],
"Title": "Machine epsilon - find epsi"
} | 1324 |
<p>How can I improve this code?</p>
<pre><code>public class Address {
public string house_no { get; set; }
public string street { get; set; }
public string zip { get; set; }
}
public class Contact {
public string email { get; set; }
public string ph_no { get; set; }
public Address address { get; set; }
}
//Test program
class Program {
static void GetContacts(string input) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, Contact> ContactList = serializer.Deserialize<Dictionary<string, Contact>>(input);
}
static void Main(string[] args) {
//jsonText is a string that I retrieve from a web service.
string jsonText = ws.GetContactList();
GetContacts(jsonText);
}
}
</code></pre>
| [] | [
{
"body": "<p>It is already short and to the point. One minor formatting change; I would make your class properties upper camel case, which is typical for C#. I also dropped the abbreviations.</p>\n\n<pre><code>public class Address { \n public string HouseNumber { get; set; } \n public string Street { get; set; } \n public string Zip { get; set; }\n}\n\npublic class Contact { \n public string Email { get; set; } \n public string PhoneNumber { get; set; } \n public Address Address { get; set; } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T20:22:44.290",
"Id": "2323",
"Score": "0",
"body": "It is subjective point. Lower case is regular for javascript, that's probably why they are named in lower camel case."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T20:31:12.210",
"Id": "2324",
"Score": "0",
"body": "Snowbear is right. They are lowercase so that they are consistent with the JSON that is coming in."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T19:12:40.423",
"Id": "2380",
"Score": "0",
"body": "That's PascalCase, but otherwise, yeah. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T02:45:21.463",
"Id": "2383",
"Score": "0",
"body": "@Noldorin PascalCase == UpperCamelCase"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T17:41:28.203",
"Id": "2393",
"Score": "0",
"body": "Not in the Microsoft book. ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T19:43:07.510",
"Id": "1331",
"ParentId": "1329",
"Score": "8"
}
},
{
"body": "<p>There is nothing to actually review here so let's start nit-picking process: </p>\n\n<p>1) I would use <code>var</code> for contacts. Anyway you already have <code>Dictionary<...></code> at the same line. Var makes it little bit less noisy.<br>\n2) Lower camel case for variable <code>Contacts</code> name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T20:25:27.410",
"Id": "1332",
"ParentId": "1329",
"Score": "5"
}
},
{
"body": "<p>Since Skeeterburg and Snowbear have already covered the basics, the only change I'd reccomend is changing address and contact from classes to structs. You aren't doing anything by reference and you don't need mutable objects. It could clean up a bit since you don't need the getters and setters. Structs (IMO) are particularly useful for this type of JSON passing.</p>\n\n<p>There was a good discussion on SO about this a while back: \n<a href=\"https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class\">https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class</a></p>\n\n<p>Also: since the struct is created on the stack, you do get a bit of a performance gain.\n<a href=\"http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T14:32:13.033",
"Id": "1359",
"ParentId": "1329",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T19:17:15.110",
"Id": "1329",
"Score": "3",
"Tags": [
"c#",
"json"
],
"Title": "Getting contact information"
} | 1329 |
<p>I have a model I have created to generate iCal and the necessary JSON for the jQuery calendar plugin <a href="http://arshaw.com/fullcalendar/">Full Calendar</a> to work. When I display the page, the JSON generation takes about 7 seconds. The query itself has been running in only a few microseconds. So I know my code is the problem. </p>
<p>I was trying to get the format like what <a href="http://arshaw.com/fullcalendar/docs/event_data/Event_Object/">Full Calendar expects</a> thus why I wrote the code how I did. My guess is that the below is the problem. Any thoughts on where I can improve this?</p>
<pre><code>#region Event
public class Event
{
public string Title { set; get; }
public string Description { set; get; }
public string URL { set; get; }
public string UID { set; get; }
public DateTime DateTimeStamp { set; get; }
public DateTime CreatedDateTime { set; get; }
public DateTime Start { set; get; }
public DateTime End { set; get; }
public bool AllDay { set; get; }
}
#endregion
public class Calendar
{
#region Model
public string CalendarName { set; get; }
public string Product { set; get; }
public string TimeZone { set; get; }
public List<Event> Events { private set; get; }
#endregion
/// <summary>
/// Creates a calendar json string.
/// </summary>
/// <returns></returns>
public string ToFullCalendarJsonString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
int count = Events.Count;
int i = 0;
foreach (Event eventItem in Events)
{
sb.Append("{");
sb.AppendFormat("\"title\":\"{0}\",", eventItem.Title);
sb.AppendFormat("\"allDay\":\"{0}\",", eventItem.AllDay);
if (eventItem.AllDay)
{
sb.AppendFormat("\"start\":\"{0}T00:00:00\",", eventItem.Start.ToString("yyyy-MM-dd"));
sb.AppendFormat("\"end\":\"{0}T00:00:00\",", eventItem.End.ToString("yyyy-MM-dd"));
}
else
{
sb.AppendFormat("\"start\":\"{0}T{1}\",", eventItem.Start.ToString("yyyy-MM-dd"), eventItem.Start.ToString("HH:mm:ss"));
sb.AppendFormat("\"end\":\"{0}T{1}\",", eventItem.End.ToString("yyyy-MM-dd"), eventItem.End.ToString("HH:mm:ss"));
}
sb.AppendFormat("\"url\":\"{0}\"", eventItem.URL);
sb.Append("}");
i++;
if (i < count)
{
sb.Append(",");
}
}
sb.Append("]");
return sb.ToString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T19:39:51.803",
"Id": "2322",
"Score": "0",
"body": "This is for `[asp.net-mvc-2]` but I can't tag it as such."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T21:08:31.850",
"Id": "2331",
"Score": "2",
"body": "How many events do you have?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T14:05:54.867",
"Id": "2345",
"Score": "0",
"body": "About 80 and more as we keep going."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T14:45:56.527",
"Id": "2348",
"Score": "0",
"body": "@Mike, well, sounds very strange. I was testing in console application and I had 5 seconds for about 20,000 events."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:30:33.523",
"Id": "2351",
"Score": "0",
"body": "The data comes from an iSeries. I hope that isn't part of the problem."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:32:02.503",
"Id": "2352",
"Score": "0",
"body": "@Mike, what is it?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:34:07.343",
"Id": "2354",
"Score": "0",
"body": "@Snowbear What is an [iSeries](http://www-03.ibm.com/systems/i/)? It is an enterprise level database/application server. A midrange computer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:39:35.633",
"Id": "2355",
"Score": "0",
"body": "@Mike, I didn't know it. And due to some exception in my mind I thought that first google `iseries` results are not related to your `iseries`. Regarding your concern. I thought it was the first thing you've tested - that this exact function is performance bottleneck. Otherwise all our answers won't make any sense."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:46:07.973",
"Id": "2356",
"Score": "0",
"body": "The query itself takes 200 ms or so. I got the performance to a couple seconds. For now that is acceptable. I'll have to restructure quite a bit more if I more complaints. For now I am moving on. The software is in beta anyway. When people start to complain and I have more time, then I'll re-factor everything to try and make it faster."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T16:01:58.270",
"Id": "2362",
"Score": "0",
"body": "@Mike Wills: I'm guessing the major speed difference between our tests and your observations indicate another problem. How exactly did you determine that it is the particular code you mention here which is slow? For quick time checks, like those posted in my answer I simply use `Environment.Ticks` before and after the particular code I'm trying to measure, and look at the difference between the two. When more advanced profiling is needed, use a profiler."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T13:31:18.227",
"Id": "2390",
"Score": "0",
"body": "@Steven: I know where another problem lies. I don't have time at this point to fix it. There are 3 or 4 loops in the entire process of generating this. I am going to eliminate a couple of the loops and see if that helps at some point."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T13:41:45.630",
"Id": "2391",
"Score": "0",
"body": "@Mike Wills: It might be worthwhile posting the code of these loops in a new question. ;p"
}
] | [
{
"body": "<p>Couple of tricks to improve performance (i've got around +10%, not that much though): </p>\n\n<p>1) Preallocate <code>stringBuilder</code> size. You can roughly calculate it's total size as <code>Events.Count * charsPerEvent</code><br>\n 2) In this line: <code>sb.AppendFormat(\"\\\"end\\\":\\\"{0}T{1}\\\",\", eventItem.End.ToString(\"yyyy-MM-dd\"), eventItem.End.ToString(\"HH:mm:ss\"));</code> combine two parameters into 1 using following format string for date: <code>yyyy-MM-ddTHH:mm:ss</code></p>\n\n<p>Also I doubt you will be able to gain performance. Maybe you can workaround it somehow? For example caching the results. Also you may try instead of creating a new string simply write it to response via <code>HTTPHandler</code> if Asp.Net MVC still allows to do it easily. Not sure that it will help also.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T21:42:27.933",
"Id": "1334",
"ParentId": "1330",
"Score": "6"
}
},
{
"body": "<p>I just <a href=\"http://www.dotnetperls.com/stringbuilder-1\" rel=\"nofollow noreferrer\">read somewhere</a> that <code>AppendFormat()</code> can be slower than simple <code>Append()</code> calls. Being shocked by reading this, I decided to investigate.</p>\n\n<p>For 1,000,000 empty events the times required are:</p>\n\n<ul>\n<li>With AppendFormat: <strong>9297</strong> ticks</li>\n<li>Without AppendFormat: <strong>8268</strong> ticks</li>\n</ul>\n\n<p>That is a considerable difference of <strong>11%</strong>!</p>\n\n<p>I'm guessing this is due to the lookup of the arguments and such. It would be nice if <code>AppendFormat()</code> would be recompiled to <code>Append()</code> calls only by default.</p>\n\n<p>This is the code:</p>\n\n<pre><code> /// <summary>\n /// Creates a calendar json string.\n /// </summary>\n /// <returns></returns>\n public string ToFullCalendarJsonStringFaster()\n {\n StringBuilder sb = new StringBuilder();\n\n sb.Append( \"[\" );\n\n int count = Events.Count;\n int i = 0;\n\n foreach ( Event eventItem in Events )\n {\n sb.Append( \"{\" );\n\n sb.Append(\"\\\"title\\\":\\\"\");\n sb.Append(eventItem.Title);\n sb.Append(\"\\\",\");\n sb.Append(\"\\\"allDay\\\":\\\"\");\n sb.Append(eventItem.AllDay);\n sb.Append(\"\\\",\");\n\n if ( eventItem.AllDay )\n {\n // My test never comes here, so I left it out.\n }\n else\n {\n sb.Append(\"\\\"start\\\":\\\"\");\n sb.Append(eventItem.Start.ToString(\"yyyy-MM-dd\"));\n sb.Append(\"T\");\n sb.Append(eventItem.Start.ToString(\"HH:mm:ss\"));\n sb.Append(\"\\\",\");\n\n sb.Append(\"\\\"end\\\":\\\"\");\n sb.Append(eventItem.End.ToString(\"yyyy-MM-dd\"));\n sb.Append(\"T\");\n sb.Append(eventItem.End.ToString(\"HH:mm:ss\"));\n sb.Append(\"\\\",\");\n }\n sb.Append(\"\\\"url\\\":\\\"\");\n sb.Append(eventItem.URL);\n sb.Append(\"\\\"\");\n sb.Append( \"}\" );\n\n i++;\n\n if ( i < count )\n {\n sb.Append( \",\" );\n }\n }\n\n sb.Append( \"]\" );\n\n return sb.ToString();\n }\n</code></pre>\n\n<p>By also applying Snowbear's earlier replies:</p>\n\n<ul>\n<li>Using <code>yyyy-MM-ddTHH:mm:ss</code> as format strings, gives an extra speed difference of <strong>5%</strong></li>\n<li>Preallocating <code>StringBuilder</code> size, gives an extra speed difference of <strong>6%</strong></li>\n</ul>\n\n<p>In total, after applying all changes, the code is <strong>22%</strong> faster. :)</p>\n\n<p>Bottomline is, there probably isn't a 'magic' solution which can make it go instant with so many events, but you can improve the speed considerably. I suggest you run the processing on a <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\"><code>BackgroundWorker</code></a>.</p>\n\n<hr>\n\n<p>... this is getting even more ridiculous. Changing the date formatting to the following:</p>\n\n<pre><code>//sb.Append(eventItem.Start.ToString( \"yyyy-MM-ddTHH:mm:ss\" ) );\nsb.Append(eventItem.Start.Year);\nsb.Append(\"-\");\nsb.Append(eventItem.Start.Month);\nsb.Append(\"-\");\nsb.Append(eventItem.Start.Day);\nsb.Append(\"T\");\nsb.Append(eventItem.Start.Hour);\nsb.Append(\":\");\nsb.Append(eventItem.Start.Minute);\nsb.Append(\":\");\nsb.Append(eventItem.Start.Second);\nsb.Append(\"\\\",\");\n</code></pre>\n\n<p>... gives another speed increase and makes it <strong>34%</strong> faster in total. Might slow down \nagain if you need more specific formatting.</p>\n\n<hr>\n\n<p><strong>Beware</strong>: this last update is probably erronous. I asked <a href=\"https://stackoverflow.com/q/5352491/590790\">a question about proper usage of PLINQ</a>.</p>\n\n<p>I haven't used <a href=\"http://msdn.microsoft.com/en-us/library/dd460688.aspx\" rel=\"nofollow noreferrer\">Parallel LINQ (PLINQ)</a> yet. But this seemed a nice use for it. After replacing the for by:</p>\n\n<pre><code>Events.AsParallel().AsOrdered().ForAll( eventItem =>\n{\n ...\n} ); \n</code></pre>\n\n<p>I get a total speed increase of <strong>43%</strong>, again 9% faster. :) This is on a dual core processor. PC's with more cores should perform better. I don't know how PLINQ works exactly, but I would think it could work even faster if one iteration doesn't need to wait on another. The <code>StringBuilder</code> and <code>i</code> are exposed as closures. Anyone got any better approaches than <code>ForAll()</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T09:11:29.657",
"Id": "2338",
"Score": "0",
"body": "I've also noticed with your last approach that I got some improvement by explicit conversion of each date component to string before passing it to `Append`. Though I hadn't time to check it or research on it, but it was surprising to me."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T11:45:19.840",
"Id": "2339",
"Score": "0",
"body": "So ... how could we have forgotten PLINQ? Anybody more experience with it? A simple ForAll already results in another 9% speed increase."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T13:29:12.543",
"Id": "2342",
"Score": "1",
"body": "Wow... your work is impressive on this. Thanks! I'll take a look at your suggestions."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T14:24:31.357",
"Id": "2346",
"Score": "1",
"body": "You have to use [Aggregate](http://msdn.microsoft.com/en-us/library/dd384149.aspx) to get the behavior you want. The specific overload I linked can aggregate over ranges of the result in parallel, and then merges all the results at the end."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T01:10:57.167",
"Id": "1338",
"ParentId": "1330",
"Score": "11"
}
},
{
"body": "<p>Note this is off topic (not a codereview solution but an idea of how to solve the performance problem.)</p>\n\n<p><strong>It's hard for me to believe that this is really the bottleneck</strong></p>\n\n<p>Are you sure that this is really the bottleneck? You can test it by returning the same constant fake json string.</p>\n\n<pre><code> string fake2000Events = @\"{.......}\";\n\n public string ToFullCalendarJsonString()\n {\n return fake2000Events\n }\n</code></pre>\n\n<p>If performance is much better than calculating real data then you may think of caching results.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T11:51:10.177",
"Id": "2340",
"Score": "0",
"body": "It's not off topic IMHO. It's working code, which is being reviewed, in this particular case for performance. I'd even say that's something which could be added in the FAQ."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T13:35:06.797",
"Id": "2343",
"Score": "0",
"body": "Well, when initially creating it I had a small result set. It was showing immediately. Now that there is real data (about 80-85 in the result set) it is now taking 11 seconds. Yes, it went up from yesterday as more data has been added."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T13:46:40.233",
"Id": "2344",
"Score": "2",
"body": "@Mike Wills: only 85? You should use a profiler and see which calls are slowest."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T19:32:07.703",
"Id": "2353",
"Score": "0",
"body": "@Steven Can a profiler be used when getting data from the iSeries?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T06:05:22.230",
"Id": "1340",
"ParentId": "1330",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1338",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T19:39:16.483",
"Id": "1330",
"Score": "8",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-2"
],
"Title": "My Calendar generation code is slow. How do I improve it?"
} | 1330 |
<p>The below code feels ugly, how can I make it better? (The part i don't like is the ||=. I also don't know if I like the resulting data structure. (An array of hashes)</p>
<pre><code>def survey_results
@survey_results = []
unless params[:step_survey_id].blank?
SurveyResult.find_by_step_survey_id(params[:step_survey_id]).step_survey.step_survey_questions.each do |survey_question|
survey_result = {:question => survey_question.value}
answers = {}
survey_question.survey_result_answers.each do |survey_result_answer|
#Setup initial answer hash with key as the response, only used when needed
answers[survey_result_answer.response] ||= 0
answers[survey_result_answer.response] += 1
end
survey_result[:answers] = answers
@survey_results.push(survey_result)
end
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T21:31:41.877",
"Id": "2332",
"Score": "0",
"body": "Could you please describe the relevant models (especially SurveyResult and StepSurvey) and their relation to each other? Also which class is `survey_results` a method of?"
}
] | [
{
"body": "<p>Regarding the data structure: In cases like this where you always use the same keys for the hashes (i.e. <code>:answers</code> and <code>:question</code> in this case), it is often a good idea to use a simple class instead, which has accessors for the given properties. You can use <code>Struct</code> to easily create such classes. In this case this would look like this:</p>\n\n<pre><code>SurveyResultInformation = Struct.new(:question, :answers)\n</code></pre>\n\n<p>Using a class instead of a hash is more robust as mistyped attribute names will cause an exception. It is also more extensible as it allows you to add methods to the class - like for example <code>most_common_answer</code>.</p>\n\n<p>However in this particular case where the method is called <code>survey_results</code> and there exists a class called <code>SurveyResult</code> one has to wonder whether <code>survey_results</code> couldn't/shouldn't return instances of the existing <code>SurveyResult</code> class instead.</p>\n\n<p>My guess is you should be returning an array of <code>SurveyResult</code> objects and extend that class to offer the functionality you need. Though without knowing more of your code it's hard to say for sure.</p>\n\n<p>At the very least you should rename the method or the class to avoid the impression that the method returns instances of that class.</p>\n\n<hr>\n\n<p>Now to your code:</p>\n\n<p>First of all your method names sounds like it would return the collected survey results, but in fact it just stores them in an instance variable and apparently returns nothing of consequence. You should either make it return the results (possible caching them in the instance variable) or change its name to something imperative-sounding like <code>initialize_survey_results</code> instead.</p>\n\n<hr>\n\n<p>You're creating an empty array and then appending to it once per iteration in an each-loop. If you do this you can (and should) almost always use <code>map</code> instead.</p>\n\n<hr>\n\n<pre><code>answers[survey_result_answer.response] ||= 0\nanswers[survey_result_answer.response] += 1\n</code></pre>\n\n<p>As you already pointed out this is a bit ugly. Luckily ruby's Hash class has a feature that gets rid of the need for <code>||=</code> here: It allows you to set default values which will be returned instead of <code>nil</code> if a key was not found. If we replaces <code>answers = {}</code> with <code>answers = Hash.new(0)</code> to set the default value to 0, you can just get rid of the <code>||=</code> line.</p>\n\n<hr>\n\n<pre><code>SurveyResult.find_by_step_survey_id(params[:step_survey_id]).step_survey\n</code></pre>\n\n<p>This line stumped be a bit when I first read it. It is not apparent why you're not just calling <code>StepSurvey.find(step_survey_id)</code>. First I thought maybe you don't want to get the step survey when there is no survey result pointing to it, but in that case the above code would cause an exception, so that can't be it.</p>\n\n<hr>\n\n<p>If I were to write this, I would do something like this:</p>\n\n<pre><code>def survey_results\n if params[:step_survey_id].blank?\n []\n else\n StepSurvey.find(params[:step_survey_id]).step_survey_questions.map do |survey_question|\n survey_result = SurveyResultInformation.new(survey_question.value)\n answers = Hash.new(0)\n survey_question.survey_result_answers.each do |survey_result_answer|\n answers[survey_result_answer.response] += 1\n end\n survey_result.answer = answers\n survey_result\n end \n end \nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-17T21:48:47.883",
"Id": "1335",
"ParentId": "1333",
"Score": "4"
}
},
{
"body": "<p>Using:</p>\n\n<ul>\n<li><a href=\"http://rubyworks.github.com/facets/doc/api/core/Enumerable.html\" rel=\"nofollow\">Facets</a>'s <code>frequency</code>.</li>\n<li><a href=\"http://code.google.com/p/tokland/wiki/RubyIdioms#Functional_Ruby\" rel=\"nofollow\">Functional programming</a> principles (no <code>Enumerable#each</code> and <code>Array#push</code> and other bad companies).</li>\n</ul>\n\n<p>You can write:</p>\n\n<pre><code>def survey_results\n result = SurveyResult.find_by_step_survey_id(params[:step_survey_id])\n questions = result ? result.step_survey.step_survey_questions : []\n questions.map do |survey_question|\n {\n :question => survey_question.value,\n :answers => survey_question.survey_result_answers.map(&:response).frequency\n }\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-30T14:38:45.333",
"Id": "1547",
"ParentId": "1333",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1335",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-17T20:32:06.763",
"Id": "1333",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Setting responses on survey results"
} | 1333 |
<blockquote>
<p><strong>3.23 Palindromes</strong></p>
<p>A palindrome is a number that reads the same forwards
and backwards, like 12321. Write a
program that tests input integers for
the palindrome property.</p>
<p>Hint: This should not be done with the numbers in
their input (character) format.</p>
</blockquote>
<p>For the task above, I have written the following program. Rather than converting the number to a string, I recursively divide the number to create a list of individual digits and then compare the digits from outside to in to determine if it's a palindrome. What do you think of my strategy and of my code in general? I understand that tail recursion is not guaranteed to work in Common Lisp - should I rewrite this code to use loops instead?</p>
<pre><code>(defun collect-digits (candidate &OPTIONAL (digit-list ()))
; make a list out of the digits of the number
; example: (= (collect-digits 12321) (1 2 3 2 1)) is true
(if (< candidate 10)
(cons candidate digit-list)
(multiple-value-call
(lambda (sub-candidate onesdigit)
(collect-digits sub-candidate (cons onesdigit digit-list)))
(floor candidate 10))))
(defun reflection-p (candidate-list &OPTIONAL (len (length candidate-list)))
; if c-l[first] = c-l[last]
(and (= (car candidate-list) (car (last candidate-list 1)))
; and the list is 3 or smaller ex. (3 1 3), it is a reflection
(if (<= len 3) t
; if longer, keep looking
(reflection-p (subseq candidate-list 1 (1- len)) (- len 2)))))
(defun palindrome-p (candidate)
(reflection-p (collect-digits candidate)))
(format t "12321: ~a ~%3456789 ~a ~%" (palindrome-p 12321) (palindrome-p 3456789))
</code></pre>
| [] | [
{
"body": "<p>This one is easy! Remember the <a href=\"https://codereview.stackexchange.com/questions/1219/common-lisp-print-an-integer-and-its-digits-reversed\"><code>reverse-digits</code> function</a>? If a number is the same as its reverse, then it's a palindrome.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T06:19:18.600",
"Id": "1341",
"ParentId": "1339",
"Score": "4"
}
},
{
"body": "<p>Regarding your use of recursion: Generally when you consider whether to use recursion (and you don't specifically write for a platform which guarantees tail-call optimization to be performed), you need to consider the recursion depth that is likely to be reached. If it is too deep your program will use up lots of stack space and might even cause a stack overflow. However if the recursion won't be very deep, there won't be a problem.</p>\n\n<p>In this the recursion depth will equal the number of digits in the number. Since your function will be unlikely to be called with numbers which have more than 100 digits, using recursion here is perfectly fine.</p>\n\n<hr>\n\n<p>Regarding your <code>reflection-p</code> function. You're determining whether a list is a palindrome in the same way one would do so with an array, basically iterating from both sides. However linked lists and arrays have different performance characteristics and what works well for arrays, can be very slow for linked lists (or vice versa of course).</p>\n\n<p>In this case, you're making heavy use of <code>last</code> and some use of <code>length</code>, both of which are <code>O(n)</code> operations. This makes your <code>reflection-p</code> function quite inefficient. The easiest way to check efficiently whether a list is palindromic, is just to reverse the list and check whether the original list is equal to its reverse.</p>\n\n<hr>\n\n<p>Also a note regarding comments: The commenting convention in lisp (which is also enforced/heavily encouraged by e.g. emacs's indentation behavior) is as follows:</p>\n\n<ol>\n<li><p>A comment describing a single line of code should use a single semicolon and be written on the same line as the code. I.e:</p>\n\n<pre><code>(format t \"hello world\") ; Print hello world\n</code></pre>\n\n<p>and not </p>\n\n<pre><code>; Print hello world\n(format t \"hello world\")\n</code></pre></li>\n<li>A comment describing multiple lines of code should be written before those lines using two semicolons and indented at the same level as the lines it describes.</li>\n<li>A comment documenting a function should be written with three semicolons.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T20:55:15.120",
"Id": "1346",
"ParentId": "1339",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-18T05:38:26.310",
"Id": "1339",
"Score": "3",
"Tags": [
"lisp",
"common-lisp",
"palindrome"
],
"Title": "Testing input integers for the palindrome property"
} | 1339 |
<p>Typical tutorials suggest simple CoreLocation code similar to the following:</p>
<p>Header</p>
<pre><code>#import<CoreLocation/CoreLocation.h>
@interface MyCLController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locManager;
}
@property (nonatomic, retain) CLLocationManager *locManager;
@end
</code></pre>
<p>Setup</p>
<pre><code>....
self.locManager = [[[CLLocationManager alloc] init] autorelease];
if(!self.locManager.locationServicesEnabled)
{
NSLog(@"User has opted out of location services");
}
self.locManager.delegate = self;
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locManager.distanceFilter = 880.0f; // About 1/10th mile, in meters
[self.locManager startUpdatingLocation];
....
</code></pre>
<p>Methods</p>
<pre><code>- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
// Respond to errors
NSLog(@"Location manager error: %@", [error description]);
return;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"%@\n", [newLocation description]);
}
</code></pre>
<p>Deallocate</p>
<pre><code>....
[self.locManager release]
....
</code></pre>
<p>The above code works, but what common problems should I expect once I start testing on the most common iOS devices and versions? (assuming target of iOS 3.2 and above, building on iOS 4.3 SDK, code should work on all iOS devices that support at least 3.2 and any devices that support above 3.2)</p>
<p>Many simple examples online are 1-2 years old - are there improvements to the above that should be made due to changes in CoreLocation and the new devices released since 3.2?</p>
<p>What other suggestions would make the above more robust, and are there any other pitfalls developers should be aware of as they develop for CoreLocation?</p>
| [] | [
{
"body": "<p>Apple's LocateMe sample has been kept up to date and shows how to properly handle getting a fix with accuracy evalutation and timeout. It's quite an excellent sample so why not start there?</p>\n\n<p>Devices without cellular won't have the benefit of cell triangulation but that's all abstracted anyway. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T06:31:37.253",
"Id": "2726",
"ParentId": "1342",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2726",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T13:56:07.550",
"Id": "1342",
"Score": "0",
"Tags": [
"objective-c",
"ios"
],
"Title": "Core Location - Practices for Supporting Common iOS Devices"
} | 1342 |
<p>After growing tired of all the ways in which a file loop can be broken (<code>find -print | while read</code>) or unreadable (<code>find -exec</code> with complex commands), I think I've managed to build a <a href="https://github.com/l0b0/tilde/blob/master/examples/safe-find.sh"><code>find</code> template</a> which can handle <strong>any and all files</strong> which could possibly exist on a Linux system (not so famous last words). Can you find a way to break it, by changing either the <code>test_</code> variables or the environment? For example, is it possible to mess with file descriptor 9 outside the script so that it won't work?</p>
<p>The only requirement is "sanity." In other words, <code>test_file_name</code> and <code>test_dir_path</code> cannot contain <code>\0</code> or <code>/</code>, <code>test_file_path</code> cannot contain <code>\0</code> (or be more than 1 level deep, since <code>mkdir</code> for the sake of the test is run without <code>-p</code>), and <code>/bin/bash</code> must be a stable version of Bash 4.</p>
<pre><code>#!/bin/bash
# Filenames can contain *any* character except only null (\0) and slash (/);
# here's some general rules to handle them:
#
# $'...' can be used to create human readable strings with escape sequences.
#
# ' -- ' in commands is necessary to separate arguments from filenames, since
# filenames can start with '--', and would therefore be handled as parameters.
# To handle parameters properly (like GNU tools) use `getopt`.
#
# `find` doesn't support this syntax, so we use `readlink` to get an absolute
# path which by definition starts with slash.
#
# The "$()" construct strips trailing newlines, so we have to add a different
# character and then strip it outside the "$()" construct.
#
# `IFS=` is necessary to avoid that any characters in IFS are stripped from
# the start and end of $path.
#
# '-r' avoids interpreting backslash in filenames specially.
#
# '-d '' splits filenames by the null character.
#
# '-print0' separates find output by null characters.
#
# Variables inside '$()' have to be quoted just like outside this construct.
#
# Use process substitution with "<(" instead of pipes to avoid broken pipes.
#
# Use file descriptor 9 for data storage instead of standard input to avoid
# greedy commands like `cat` eating all of it.
set -o errexit
set -o nounset
set -o noclobber
test_file_name=$'--$`\! *@ \a\b\e\E\f\r\t\v\\\"\' \n'
test_dir_path="$test_file_name"
test_file_path="${test_dir_path}/${test_file_name}"
mkdir -- "$test_dir_path"
touch -- "$test_file_path"
absolute_dir_path_x="$(readlink -fn -- "$test_dir_path"; echo x)"
absolute_dir_path="${absolute_dir_path_x%x}"
exec 9< <( find "$absolute_dir_path" -type f -print0 )
while IFS= read -r -d '' -u 9
do
file_path="$(readlink -fn -- "$REPLY"; echo x)"
file_path="${file_path%x}"
echo "START${file_path}END"
done
rm -- "$test_file_path"
rmdir -- "$test_dir_path"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T10:59:01.850",
"Id": "2435",
"Score": "0",
"body": "Either nobody here knows bash, or nobody can break it. ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T05:48:49.457",
"Id": "2476",
"Score": "2",
"body": "If you're talking about `gnu find`, you hardly ever need `find | while read`, or `for` or `xargs` and the like. Read the manpage for `find`, especially the part about -exec, -execdir, -ok and -okdir. Find already iterates over the the result, so you don't need an iterator to catch and rethrow the results to some other command or program."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T20:55:06.110",
"Id": "2542",
"Score": "2",
"body": "I haven't found a bug, so have my sole nitpick so far: `printf \"%q\\n\" \"$file_path\"` is nicer than `echo` (and there's an unbalanced quote in your comments)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-30T11:02:52.377",
"Id": "2678",
"Score": "0",
"body": "@Tobu: I disagree with the `printf` statement (do you have a reference or more elaborate reasoning?), but thanks for the quote fix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T01:53:43.900",
"Id": "3451",
"Score": "0",
"body": "@sepp2k: IANAL, but it's *probably* not a good idea to copy code from someone's hyperlink and paste it to the site without explicit permission. Content on StackExchange sites is CC BY-SA, so in theory, doing so could imply that the software has a license that the owner of the code never granted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T17:08:42.590",
"Id": "9582",
"Score": "0",
"body": "@l0b0: `echo` doesn't have a standard interface (beyond \"none at all\" anyway) whereas `printf` does. In general `printf` should be used in preference to `echo`. It also means that you can cleanly say things like `printf '%s costs $%d\\n' \"$string\" \"$dollars\"`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-30T11:17:02.790",
"Id": "13510",
"Score": "0",
"body": "It's been 11 days, and a week of bounty, with no submissions showing functional errors in the code. As user unknown pointed out, there are more *elegant* solutions in case you only want to run a single command on each file within a separate subshell. But at this point I guess it's safe to say that this is a really safe way to loop over any and all files without tripping over names, executing arbitrary strings, prematurely terminating, or ending up with an undocumentable picket fence. Thanks to everyone who tried!"
}
] | [
{
"body": "<pre><code>find . -type f -execdir echo START{}END \";\"\nSTART./--$`\\! *@\n\n \\\"' \n/--$`\\! *@\n\n \\\"' \nEND\n</code></pre>\n\n<p>In which cases to you fail with find?</p>\n\n<pre><code>find . -type f -execdir md5sum {} \";\"\n\\d41d8cd98f00b204e9800998ecf8427e ./--$`\\\\! *@\n\n \\\\\"' \\n/--$`\\\\! *@\n\n \\\\\"' \\n\n</code></pre>\n\n<p>(changed from -exec to -execdir after useful hint).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T07:57:23.903",
"Id": "2479",
"Score": "0",
"body": "What do you mean?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T08:14:33.000",
"Id": "2480",
"Score": "0",
"body": "I mean, your solution solves no problem."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T08:42:18.267",
"Id": "2481",
"Score": "0",
"body": "How to loop over files is asked several times per day in different SO sites, and half-assed solutions are suggested every time. This was a solution which worked for heavily unit-tested code, so I thought it might be generally safe. `-exec` is nice if you want to run a single command, but my solution was also supposed to be readable if you have more complex commands to run for each file."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T08:45:50.990",
"Id": "2482",
"Score": "0",
"body": "`find . -type f -exec complexScript.sh {} \";\"`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T08:58:33.390",
"Id": "2483",
"Score": "2",
"body": "`complexScript.sh` is run in a separate subshell - You'd need to add parameter passing + parsing if you want any context from the source script. Also, for some reason nobody suggests using `-execdir` even though the man page says \"There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T09:08:01.207",
"Id": "2484",
"Score": "0",
"body": "You're right, I changed it to `execdir`. About parameter-passing and -parsing: Where's the problem? You need it as well."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T06:13:49.250",
"Id": "1421",
"ParentId": "1343",
"Score": "2"
}
},
{
"body": "<p>This code is vulnerable to <a href=\"http://en.wikipedia.org/wiki/Time-of-check-to-time-of-use\">TOCTOU</a>. There is a tiny gap between the time that \"plain files\" are read from the process substitution (<code>find -type f ...</code>) and the time that <code>readlink(1)</code> is called on those filenames.</p>\n\n<p>An attacker could create a program that waits for your program to run and then quickly deletes one of those files found by <code>find(1)</code> and replaces it with a symlink to somewhere else. <code>readlink(1)</code> will then dutifully return the target of that symlink and this is the path that will be output. The target could be outside <code>$absolute_dir_path</code> and a file of any type (directory, device node, ...).</p>\n\n<p>Eg:</p>\n\n<pre><code>#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o noclobber\n\n# setup directory containing two plain files\n# hardcode absolute_dir_path to /tmp/dir for simplicity\nmkdir -p /tmp/dir\nrm -f /tmp/dir/a /tmp/dir/b\ntouch /tmp/dir/a /tmp/dir/b\n\n# emulate OP's find loop, but with inserted actions\n# performed by an attacker (in real attack these would\n# happen in an external program).\nexec 9< <( find /tmp/dir -type f -print0 )\nwhile IFS= read -r -d '' -u 9\ndo\n file_path_x=\"$(readlink -fn -- \"$REPLY\"; echo x)\"\n file_path=\"${file_path_x%x}\"\n ls -l \"${file_path}\"\n # attacker jumps in here and does:\n rm /tmp/dir/b\n ln -s /etc/passwd /tmp/dir/b\ndone\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>-rw-r--r-- 1 martin martin 0 2011-03-31 10:56 /tmp/dir/a\n-rw-r--r-- 1 root root 2119 2011-03-28 11:35 /etc/passwd\n</code></pre>\n\n<p>The risk can be mitigated by only seeking files in directories beneath which untrusted users do not have write access. Directories such as <code>/tmp</code> and <code>/var/tmp</code> are problematic though and this is hard to solve. See the source of (eg) <a href=\"http://packages.debian.org/stable/admin/tmpreaper\">tmpreaper</a> for some ideas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-05T10:55:16.923",
"Id": "2908",
"Score": "0",
"body": "Excellent observation. I guess one fix would be to avoid the `readlink` altogether (which would work since filenames would start with `/tmp/dir` in any case), and make sure that none of the commands within the loop traverse symbolic links."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T15:23:06.197",
"Id": "2981",
"Score": "0",
"body": "Thanks! That's a definite improvement, but an attacker could substitute a directory or named pipe or... (or even just delete the file). That's less obviously exploitable but could still cause problems with whatever processes the supposed list of plan files (aim to \"fail fast, fail hard\", don't rely on pre-emptive tests)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T10:11:47.093",
"Id": "1575",
"ParentId": "1343",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "1575",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-18T14:33:49.160",
"Id": "1343",
"Score": "12",
"Tags": [
"security",
"bash"
],
"Title": "'find' template for handling any file"
} | 1343 |
<p>I have a section of code I use to extract an event log out of a large text file. It works well, it's just my use of <code>list(itertools.takewhile(...))</code> that feels a little sketchy to me.</p>
<p>Is there a nicer way of doing this? </p>
<pre><code>import itertools
testdata = '''
Lots of other lines...
Really quite a few.
*************
* Event Log *
*************
Col1 Col2 Col3
----- ----- -----
1 A B
2 A C
3 B D
Other non-relevant stuff...
'''
def extractEventLog(fh):
fhlines = (x.strip() for x in fh)
list(itertools.takewhile(lambda x: 'Event Log' not in x, fhlines))
list(itertools.takewhile(lambda x: '-----' not in x, fhlines))
lines = itertools.takewhile(len, fhlines) # Event log terminated by blank line
for line in lines:
yield line # In the real code, it's parseEventLogLine(line)
</code></pre>
<p>Expected output:</p>
<pre><code>>>> list(extractEventLog(testdata.splitlines()))
['1 A B', '2 A C', '3 B D']
</code></pre>
| [] | [
{
"body": "<p>Yes, it is indeed a bit sketchy/confusing to use <code>takewhile</code> when you really don't want to take the lines, but discard them. I think it's better to use <code>dropwhile</code> and then use its return value instead of discarding it. I believe that that captures the intent much more clearly:</p>\n\n<pre><code>def extractEventLog(fh):\n fhlines = (x.strip() for x in fh)\n lines = itertools.dropwhile(lambda x: 'Event Log' not in x, fhlines)\n lines = itertools.dropwhile(lambda x: '-----' not in x, lines)\n lines.next() # Drop the line with the dashes\n lines = itertools.takewhile(len, lines) # Event log terminated by blank line\n for line in lines:\n yield line # In the real code, it's parseEventLogLine(line)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T23:03:23.557",
"Id": "2366",
"Score": "0",
"body": "Much nicer! My eyes must have glossed over `dropwhile`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T20:42:10.343",
"Id": "1345",
"ParentId": "1344",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-18T20:15:13.427",
"Id": "1344",
"Score": "3",
"Tags": [
"python"
],
"Title": "Extracting lines from a file, the smelly way"
} | 1344 |
<p>I figured it's about time to jump into some Haskell, so here's a first attempt at an oddly specific SVG parser:</p>
<pre><code>import System.Environment
import Text.ParserCombinators.Parsec
parseFile fname = parseFromFile (manyTill (try tag) (try readEnd)) fname
tag = do manyTill anyChar . try $ lookAhead tagStart
char '<'
name <- many $ noneOf " "
props <- tagContents
char '>'
junk
return (name, props)
tagContents = do props <- manyTill property . try . lookAhead $ char '>'
junk
return props
property = do spaces
name <- many1 $ noneOf "="
string "=\""
val <- manyTill anyChar $ char '"'
junk
return (name, val)
junk = optional . many $ oneOf "\n\r\t\\/"
readEnd = do optional $ string "</svg>"
junk
eof
tagStart = do char '<'
tagName
tagName = string "rect"
<|> string "polygon"
<|> string "polyline"
<|> string "circle"
<|> string "path"
<|> string "g"
<|> string "svg"
</code></pre>
<p>Before anyone asks, one of the objectives for this program (other than learning) is that it should accept invalid SVGs (for example, a partial SVG or one that has been saved as an <code>rtf</code>), which is why I'm making liberal use of <code>try</code>, and cherry-picking tags.</p>
<p>As implied by the title, this is my first non-tutorial attempt at Haskell, so give me all the style pointers you can muster (and highlight anything that signals a broken understanding on my part).</p>
<p>I'd also appreciate pointers on how to cherry-pick properties (and not just tags). I've tried writing <code>property</code> as </p>
<pre><code>property = do manyTill anyChar . try $ lookAhead tagName
name <- many1 $ noneOf "="
string "=\""
val <- manyTill anyChar $ char '"'
junk
return (name, val)
</code></pre>
<p>and defining <code>propName</code> as </p>
<pre><code>propName = string "points"
<|> string "x"
<|> string "y"
<|> string "r"
<|> string "d"
<|> string "cx"
<|> string "cy"
<|> string "width"
<|> string "height"
<|> string "transform"
</code></pre>
<p>This seems like it should work since it's basically how I got <code>tag</code> jumping to the next desired tag, but it gives me unexpected input errors.</p>
<hr>
<p>Edit The Second:</p>
<pre><code>import System.Environment
import Text.ParserCombinators.Parsec
type TagName = String
type Property = (PropName, Value)
type PropName = String
type Value = String
parseFile fname = parseFromFile (manyTill (try tag) (try readEnd)) fname
tag :: GenParser Char st (TagName, [Property])
tag = do manyTill anyChar . try $ lookAhead tagStart
name <- tagStart
props <- tagContents
char '>'
junk
return (name, props)
tagContents :: GenParser Char st [Property]
tagContents = do props <- manyTill property . try . lookAhead $ char '>'
junk
return props
property :: GenParser Char st (PropName, Value)
property = do manyTill anyChar . try $ lookAhead propName
name <- many1 $ noneOf "="
string "=\""
val <- manyTill anyChar $ char '"'
junk
return (name, val)
junk = many $ oneOf "\n\r\t\\/{} "
tagStart :: GenParser Char st TagName
tagStart = do char '<'
name <- tagName
return name
readEnd = do optional $ string "</svg>"
junk
eof
tagName = oneStringOf ["rect", "polygon", "polyline", "circle", "path", "g", "svg"]
propName = oneStringOf ["points", "x", "y", "r", "d", "cx", "cy", "width", "height", "transform"]
oneStringOf :: [String] -> GenParser Char st String
oneStringOf = choice . map (try . string)
</code></pre>
<ul>
<li>Added <code>try</code> to the definition of <code>oneStringOf</code></li>
</ul>
| [] | [
{
"body": "<p>Ok, here are some things I noticed:</p>\n\n<p>First of all, while the code seems easy enough to follow as it is, a couple of comments here and there certainly couldn't hurt.</p>\n\n<hr>\n\n<pre><code>tag = do manyTill anyChar . try $ lookAhead tagStart\n char '<'\n name <- many $ noneOf \" \"\n</code></pre>\n\n<p>It seems weird that you first use <code>tagStart</code> to find until where to match, but then don't use it to actually match the tag start.</p>\n\n<hr>\n\n<pre><code>junk = optional . many $ oneOf \"\\n\\r\\t\\\\/\"\n</code></pre>\n\n<p>Since many can already match the empty string, making it optional doesn't change anything.</p>\n\n<hr>\n\n<pre><code>tagName = string \"rect\" \n <|> string \"polygon\" \n <|> string \"polyline\" \n <|> string \"circle\" \n <|> string \"path\" \n <|> string \"g\" \n <|> string \"svg\"\n</code></pre>\n\n<p>That looks a bit repetitive. I'd define a helper function which matches one of a list of strings:</p>\n\n<pre><code>-- Takes a list of strings and returns a Parser which matches any of those strings\noneStringOf = choice . map (try . string)\n\ntagName = oneStringOf [\"rect\", \"polygon\", \"polyline\"] -- etc\n</code></pre>\n\n<p>By adding the <code>try</code> we also made it so that it actually works correctly now (thanks to Joey Adams for pointing out that fix).</p>\n\n<hr>\n\n<p>As for why your alternative definition for <code>property</code> doesn't work: I'm not sure whether it's the only thing that keeps it from working, but one mistake is that you wrote <code>tagName</code> when you meant <code>propName</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-19T07:59:20.150",
"Id": "1348",
"ParentId": "1347",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-19T05:53:38.157",
"Id": "1347",
"Score": "8",
"Tags": [
"beginner",
"haskell",
"svg",
"parsec"
],
"Title": "First attempt at a SVG parser"
} | 1347 |
<p>The idea here is to implement a simple, threadsafe, observable collection that clients can bind to, whilst background threads can update. Changes in the contained items raise the <code>CollectionChanged</code> event. </p>
<p>Feedback appreciated:</p>
<pre><code>public class ThreadSafeObservableCollection<T> : INotifyCollectionChanged
where T: INotifyPropertyChanged
{
private readonly Object _lock = new Object();
private readonly Collection<T> _items = new Collection<T>();
private ReadOnlyCollection<T> _readonlyItems;
public ThreadSafeObservableCollection()
{
}
public ThreadSafeObservableCollection(IEnumerable<T> items)
{
_items = new ObservableCollection<T>(items);
foreach (T item in _items)
{
((INotifyPropertyChanged) item).PropertyChanged += ItemPropertyChangedHandler;
}
}
public ReadOnlyCollection<T> Items
{
get { return _readonlyItems ?? (_readonlyItems = new ReadOnlyCollection<T>(_items)); }
}
public virtual void Add(T obj)
{
lock(_lock)
{
((INotifyPropertyChanged) obj).PropertyChanged += ItemPropertyChangedHandler;
_items.Add(obj);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, obj));
}
}
public virtual void Remove(T obj)
{
lock (_lock)
{
((INotifyPropertyChanged) obj).PropertyChanged -= ItemPropertyChangedHandler;
_items.Remove(obj);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, obj));
}
}
#region INotify Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
var copy = CollectionChanged;
if(copy != null)
{
CollectionChanged(this, args);
}
}
private void ItemPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(args);
}
#endregion
}
</code></pre>
<p><strong>Update</strong></p>
<p>In response to the comments about the ReadOnlyCollection, I have switch its implementation for a yield block that is locked (Using a ReaderWriterLock) for the length of the enumeration, like so:</p>
<pre><code> public IEnumerable<T> Items
{
get
{
_lock.AcquireReaderLock(_lockTimeout);
try
{
foreach (T item in _items)
{
yield return item;
}
}
finally
{
_lock.ReleaseReaderLock();
}
}
}
</code></pre>
<p>Any thoughts?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T09:55:55.860",
"Id": "2372",
"Score": "1",
"body": "why item's `propertyChanged` raises `Reset` on the entire collection?"
}
] | [
{
"body": "<p>Your <code>Items</code> initialization I believe isn't threadsafe. Use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?redirectedfrom=MSDN&view=net-5.0\" rel=\"nofollow noreferrer\"><code>Lazy<T></code></a> for thread safe lazy initialization instead.</p>\n<p>The <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.readonlycollection-1?redirectedfrom=MSDN&view=net-5.0\" rel=\"nofollow noreferrer\"><code>ReadOnlyCollection</code></a> isn't thread safe.</p>\n<blockquote>\n<p>A ReadOnlyCollection can support\nmultiple readers concurrently, as long\nas the collection is not modified.\nEven so, enumerating through a\ncollection is intrinsically not a\nthread-safe procedure. To guarantee\nthread safety during enumeration, you\ncan lock the collection during the\nentire enumeration. To allow the\ncollection to be accessed by multiple\nthreads for reading and writing, you\nmust implement your own\nsynchronization.</p>\n</blockquote>\n<p>Consider using a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?redirectedfrom=MSDN&view=net-5.0\" rel=\"nofollow noreferrer\"><code>ReaderWriterLock</code></a> to support a single writer, but multiple readers.</p>\n<hr />\n<p>Furthermore, consider reading <a href=\"https://stackoverflow.com/questions/528999/why-arent-classes-like-bindinglist-or-observablecollection-thread-safe/529028#529028\">this reply</a>, and the blog post mentioned there, which discusses <a href=\"https://docs.microsoft.com/en-us/archive/blogs/jaredpar/why-are-thread-safe-collections-so-hard\" rel=\"nofollow noreferrer\">why thread safe collections are so hard</a>, and not necessarily useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-19T17:30:51.217",
"Id": "1350",
"ParentId": "1349",
"Score": "6"
}
},
{
"body": "<p>The Remove function, removes the object without checking if the object is in the collection.<br/>\nThis will probably work fine for most cases, but it would be better to make sure the object can be removed before actually modifying the object itself and the collection.</p>\n\n<p>What if the object in question belonged to another collection?<br/>\nThis code</p>\n\n<pre><code>((INotifyPropertyChanged) obj).PropertyChanged -= ItemPropertyChangedHandler; \n</code></pre>\n\n<p>would actually remove the change handler from the object but would not remove the object from the correct list.</p>\n\n<p>Another thing I noticed was</p>\n\n<pre><code>var copy = CollectionChanged;\nif(copy != null)\n</code></pre>\n\n<p>At first I though you made a copy of the event handler to make sure another thread is not changing it in between testing for null and calling it, but then you call the handler directly, so why make the copy at all? (maybe there's a good reason, I just don't know it myself)</p>\n\n<p>Sometimes I find it handy to declare the event with an empty delegate, this way I never have to test for null before calling it:</p>\n\n<pre><code>public event NotifyCollectionChangedEventHandler CollectionChanged = delegate {};\n</code></pre>\n\n<p>I'm not sure if this makes the code slower as this empty method will be called every time the event is raised, but even if it is, in some cases it might be worth the trade off.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T18:24:33.100",
"Id": "2363",
"Score": "0",
"body": "**(1)** The Remove() also throws an exception when calling it incorrectly on an ordinary collection, so I would preserve that analogy. **(2)** Removing the event handler won't do anything wrong, it refers to the event handler of this class, which was never added. **(3)** Relating to the copy made of the event handler, read [this question](http://stackoverflow.com/q/786383/590790)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T19:33:39.800",
"Id": "2364",
"Score": "0",
"body": "I did mean to raise the copy, rather than the original. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T18:12:02.227",
"Id": "1351",
"ParentId": "1349",
"Score": "2"
}
},
{
"body": "<p>As a warning, the main problem with the implementation of Items is that it lets a caller totally block write access by not finishing the iteration (i.e. blocking). You really leave yourself exposed. Which might be totally fine, but you should be aware of the issues opened up by your design.</p>\n\n<p>From Jon Skeets <a href=\"http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx\" rel=\"nofollow\">C# in depth</a>:</p>\n\n<blockquote>\n <p>It's worth remembering that most finally blocks in code aren't written explicitly in C# - they're generated by the compiler as part of lock and using statements. lock is particularly dangerous in iterator blocks - any time you've got a yield return statement inside a lock block, you've got a threading issue waiting to happen. Your code will keep hold of the lock even when it has yielded the next value - and who knows how long it will be before the client calls MoveNext() or Dispose()? Likewise any try/finally blocks which are used for critical matters such as security shouldn't appear in iterator blocks: the client can deliberately prevent the finally block from executing if they don't need any more values.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T10:09:57.990",
"Id": "8357",
"ParentId": "1349",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-19T17:10:18.933",
"Id": "1349",
"Score": "7",
"Tags": [
"c#",
".net",
"thread-safety"
],
"Title": "ThreadSafeObservableCollection of (T)"
} | 1349 |
<p>How can this code be improved?</p>
<pre><code>using System;
//using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace Combinatorics
{
public class Permutation
{
private int[] data = null;
private int order = 0;
public Permutation(int n)
{
this.data = new int[n];
for (int i = 0; i < n; ++i)
{
this.data[i] = i;
}
this.order = n;
}
public Permutation(int n, int k)
{
this.data = new int[n];
this.order = this.data.Length;
// Step #1 - Find factoradic of k
int[] factoradic = new int[n];
for (int j = 1; j <= n; ++j)
{
factoradic[n - j] = k % j;
k /= j;
}
// Step #2 - Convert factoradic to permuatation
int[] temp = new int[n];
for (int i = 0; i < n; ++i)
{
temp[i] = ++factoradic[i];
}
this.data[n - 1] = 1; // right-most element is set to 1.
for (int i = n - 2; i >= 0; --i)
{
this.data[i] = temp[i];
for (int j = i + 1; j < n; ++j)
{
if (this.data[j] >= this.data[i])
++this.data[j];
}
}
for (int i = 0; i < n; ++i) // put in 0-based form
{
--this.data[i];
}
} // Permutation(n,k)
private Permutation(int[] a)
{
this.data = new int[a.Length];
a.CopyTo(this.data, 0);
this.order = a.Length;
}
public int Order
{
get
{
return this.order;
}
}
public Object[] ApplyTo(Object[] arr)
{
Object[] result = new Object[arr.Length];
for (int i = 0; i < result.Length; ++i)
{
result[i] = arr.GetValue(this.data[i]);
}
return result;
}
public Permutation Next()
{
Permutation result = new Permutation(this.order);
int left, right;
for (int k = 0; k < result.order; ++k) // Step #0 - copy current data into result
{
result.data[k] = this.data[k];
}
left = result.order - 2; // Step #1 - Find left value
while ((result.data[left] > result.data[left + 1]) && (left >= 1))
{
--left;
}
if ((left == 0) && (this.data[left] > this.data[left + 1]))
return null;
right = result.order - 1; // Step #2 - find right; first value > left
while (result.data[left] > result.data[right])
{
--right;
}
int temp = result.data[left]; // Step #3 - swap [left] and [right]
result.data[left] = result.data[right];
result.data[right] = temp;
int i = left + 1; // Step #4 - order the tail
int j = result.order - 1;
while (i < j)
{
temp = result.data[i];
result.data[i++] = result.data[j];
result.data[j--] = temp;
}
return result;
}
public Permutation Element(int n)
{
int[] result = new int[data.Length];
int[] factoradic = new int[data.Length];
// Find the factoradic
for (int i = 1; i <= data.Length; i++)
{
factoradic[data.Length - i] = n % i;
n /= i;
}
// Convert the factoradic to the permutation
IList<int> tempList = new List<int>(data);
for (int i = 0; i < data.Length; i++)
{
result[i] = tempList[factoradic[i]];
tempList.RemoveAt(factoradic[i]);
}
return new Permutation(result);
}
public Permutation this[int n]
{
get { return this.Element(n); }
}
public static ArrayList Generate(Object[] list, bool random)
{
Permutation p = new Permutation(list.Length);
ArrayList result = new ArrayList();
if (random){
int permNum = new Random().Next(Util.Factorial(list.Length));
result.Add( p[permNum].ApplyTo(list));
} else {
while (p != null) {
result.Add(p.ApplyTo(list));
p = p.Next();
}
}
return result;
}
}
public class Combination
{
private int n = 0;
private int k = 0;
private int[] data = null;
public Combination(int n, int k)
{
this.n = n;
this.k = k;
this.data = new int[k];
for (int i = 0; i < k; ++i)
this.data[i] = i;
} // Combination(n,k)
public Combination(int n, int k, int[] a) // Combination from a[]
{
this.n = n;
this.k = k;
this.data = new int[k];
for (int i = 0; i < a.Length; ++i)
this.data[i] = a[i];
} // Combination(n,k,a)
public bool IsValid()
{
if (this.data.Length != this.k)
return false; // corrupted
for (int i = 0; i < this.k; ++i)
{
if (this.data[i] < 0 || this.data[i] > this.n - 1)
return false; // value out of range
for (int j = i + 1; j < this.k; ++j)
if (this.data[i] >= this.data[j])
return false; // duplicate or not lexicographic
}
return true;
} // IsValid()
public Combination Next()
{
if (this.data[0] == this.n - this.k)
return null;
Combination ans = new Combination(this.n, this.k);
int i;
for (i = 0; i < this.k; ++i)
ans.data[i] = this.data[i];
for (i = this.k - 1; i > 0 && ans.data[i] == this.n - this.k + i; --i)
;
++ans.data[i];
for (int j = i; j < this.k - 1; ++j)
ans.data[j + 1] = ans.data[j] + 1;
return ans;
} // Successor()
public Combination First()
{
Combination ans = new Combination(this.n, this.k);
for (int i = 0; i < ans.k; ++i)
ans.data[i] = i;
return ans;
} // First()
public Object[] ApplyTo(Array arr)
{
Object[] result = new Object[arr.Length];
for (int i = 0; i < result.Length; ++i)
{
result[i] = arr.GetValue(this.data[i]);
}
return result;
}
public Object[] ApplyTo(Object[] strarr)
{
Object[] result = new Object[this.k];
for (int i = 0; i < result.Length; ++i)
result[i] = strarr[this.data[i]];
return result;
} // ApplyTo()
public static int Choose(int n, int k)
{
if (n < k)
return 0; // special case
if (n == k)
return 1;
int delta, iMax;
if (k < n - k) // ex: Choose(100,3)
{
delta = n - k;
iMax = k;
}
else // ex: Choose(100,97)
{
delta = k;
iMax = n - k;
}
int ans = delta + 1;
for (int i = 2; i <= iMax; ++i)
{
checked { ans = (ans * (delta + i)) / i; } // Throws OverFlow Exception
}
return ans;
} // Choose()
// return the mth lexicographic element of combination C(n,k)
public Combination Element(int m)
{
int[] ans = new int[this.k];
int a = this.n;
int b = this.k;
int x = (Choose(this.n, this.k) - 1) - m; // x is the "dual" of m
for (int i = 0; i < this.k; ++i)
{
ans[i] = LargestV(a, b, x); // largest value v, where v < a and vCb < x
x = x - Choose(ans[i], b);
a = ans[i];
b = b - 1;
}
for (int i = 0; i < this.k; ++i)
{
ans[i] = (n - 1) - ans[i];
}
return new Combination(this.n, this.k, ans);
} // Element()
public Combination this[int m]
{
get { return this.Element(m); }
}
// return largest value v where v < a and Choose(v,b) <= x
private static int LargestV(int a, int b, int x)
{
int v = a - 1;
while (Choose(v, b) > x)
--v;
return v;
} // LargestV()
public static ArrayList Generate(Object[] list, int choose, bool random)
{
Combination c = new Combination(list.Length, choose);
ArrayList result = new ArrayList();
if (random)
{
int permNum = new Random().Next(Util.Combination(list.Length, choose));
result.Add(c[permNum].ApplyTo(list));
}
else
{
while (c != null)
{
result.Add(c.ApplyTo(list));
c = c.Next();
}
}
return result;
}
}
public class Variation
{
//public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
//{
// IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
// return sequences.Aggregate(
// emptyProduct,
// (accumulator, sequence) =>
// from accseq in accumulator
// from item in sequence
// select accseq.Concat(new[] { item }));
//}
public static ArrayList Generate(Object[][] lists)
{
int seqCount = lists.Length;
ArrayList accum = new ArrayList(seqCount);
if (seqCount > 0)
{
Stack enumStack = new Stack();
Stack itemStack = new Stack();
int index = seqCount - 1;
IEnumerator enumerator = lists[index].GetEnumerator();
while (true)
if (enumerator.MoveNext())
{
itemStack.Push(enumerator.Current);
if (index == 0)
{
accum.Add(itemStack.ToArray());
itemStack.Pop();
}
else
{
enumStack.Push(enumerator);
enumerator = lists[--index].GetEnumerator();
}
}
else
{
if (++index == seqCount)
break;
itemStack.Pop();
enumerator = enumStack.Pop() as IEnumerator;
}
}
return accum;
}
}
public class Util
{
public static int Factorial(int n)
{
int f = 1;
while (n > 1) { f *= n; --n; }
return f;
}
public static int Combination(int n, int k)
{
return Factorial(n) / (Factorial(k) * Factorial(n - k));
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T02:35:02.527",
"Id": "2367",
"Score": "3",
"body": "Did you tag this as functional-programming because you want to take the code into a more functional direction? Otherwise I don't see the reason for the tag, this code is as imperative as it gets."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T03:14:42.947",
"Id": "2369",
"Score": "2",
"body": "Ok, this is a lot of code. Some comments and documentation for the various methods as well as a description of how you're using (or planning on using) the code and an explanation of your design decisions would greatly help people to give you meaningful advice."
}
] | [
{
"body": "<ol>\n<li><p>Why have you commented out <code>Linq</code> namespace? Use it at least here:</p>\n\n<pre><code>this.data = new int[n];\nfor (int i = 0; i < n; ++i)\n{\n this.data[i] = i;\n}\n</code></pre>\n\n<p>It can be replaced with:</p>\n\n<pre><code>this.data = Enumerable.Range(0, n).ToArray();\n</code></pre></li>\n<li><p>In first two <code>Permutation</code> constructors you have:</p>\n\n<pre><code>public Permutation(int n)\n{\n this.data = new int[n];\n ...\n this.order = n;\n}\n\npublic Permutation(int n, int k)\n{\n this.data = new int[n];\n this.order = this.data.Length;\n ...\n}\n</code></pre>\n\n<p>Effectively, <code>order</code> is being set to the same value, but you're doing it in a different way in similar scenarios. This makes it more confusing. Either use <code>order = n</code> in both places or use <code>order = data.Length</code>. Keep it consistent.</p></li>\n<li><p>In the <code>Permutation</code> class, you have field <code>order</code> which is always set to be a length of <code>data</code> and you also have a property to retrieve this field. I believe this additional field makes this code more error prone because you have to remember to set this field. I would remove it and replace <code>Order</code> property to return <code>data.Length</code>.</p></li>\n<li><p>In many places, it is unclear what's going on and how to use these classes. Add some documentation. I would never guess how <code>Permutation.Element(n)</code> would return new <code>Permutation</code>.</p></li>\n<li><p>This statement in the second <code>Permutation</code> constructor is misleading: </p>\n\n<pre><code>for (int i = 0; i < n; ++i)\n{\n temp[i] = ++factoradic[i]; // <-- Why ++ ???\n}\n</code></pre>\n\n<p>I would remove <code>++</code> here. In this way it makes me think that <code>factoradic[i]</code> is used somewhere else, but it is not. Use <code>factoradic[i] + 1</code> instead. Remember that when somebody will read/review your code he will have to keep in mind all the variables in method. This line just made this reviewer to update variable value which is not a cheap operation for people.</p>\n\n<p>Also consider using LINQ here and replace it with:</p>\n\n<pre><code>int[] temp = factoradiac.Select(i => i + 1).ToArray();\n</code></pre></li>\n</ol>\n\n<p>I wasn't strong enough to read through second class, so probably some my points will be applicable there also.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-20T09:52:43.337",
"Id": "1357",
"ParentId": "1352",
"Score": "4"
}
},
{
"body": "<p>A couple of things that I've noticed (though I haven't worked through all of the code in detail):</p>\n\n<pre><code>public Object[] ApplyTo(Object[] arr)\n</code></pre>\n\n<p>Again I don't know how this is going to be used, but this looks suspiciously as if you were doing something like <code>Foo[] myFoos = (Foo[]) myPermutation.ApplyTo(oldFoos)</code>, which is bad. You should make <code>ApplyTo</code> generic, so you don't need to cast the returned array back to the original type.</p>\n\n<hr>\n\n<pre><code>result[i] = arr.GetValue(this.data[i]);\n</code></pre>\n\n<p>I don't see why you use <code>GetValue</code> instead of <code>[]</code> here.</p>\n\n<hr>\n\n<pre><code>public Permutation Next()\n</code></pre>\n\n<p>It might be nicer to have a static method which returns an enumerable of all the permutations instead of having to call the <code>Next</code> method all the time. Though of course that depends on how it is used.</p>\n\n<hr>\n\n<pre><code>public Object[] ApplyTo(Array arr)\n{\n Object[] result = new Object[arr.Length];\n for (int i = 0; i < result.Length; ++i)\n {\n result[i] = arr.GetValue(this.data[i]);\n }\n\n return result;\n}\n</code></pre>\n\n<p>The only reason that comes to mind why it'd make sense to take <code>Array</code> rather than <code>Object[]</code> (or better yet: generics) here, would be to work with arrays of arbitrary dimensions. However the code will only work with one-dimensional arrays, so this overload seems completely superfluous to me. </p>\n\n<hr>\n\n<pre><code>public static int Factorial(int n)\n{\n int f = 1;\n while (n > 1) { f *= n; --n; }\n return f;\n}\n</code></pre>\n\n<p>The backwards-counting while-loop seems harder to understand than a plain forward-counting for-loop to me. Or you could define it using LINQ's <code>Aggregate</code> method (you did tag this \"functional programming\" after all).</p>\n\n<p>Also I'd put the main logic into a method <code>int Product(int from, int to)</code> which multiplies the numbers from <code>from</code> to <code>to</code> and then just call that as <code>Product(1, n)</code> to define <code>Factorial</code>.</p>\n\n<hr>\n\n<pre><code>public static int Combination(int n, int k)\n{\n return Factorial(n) / (Factorial(k) * Factorial(n - k));\n}\n</code></pre>\n\n<p>This seems to be a less optimized reimplementation of <code>Permutation.Choose</code>, I don't see why you'd need this method twice.</p>\n\n<p>That said you can optimize this version a bit by using the fact that <code>x! / y!</code> is the product of the numbers from <code>k+1</code> to <code>n</code> (using my suggested <code>Product</code> method):</p>\n\n<pre><code>return Product(k+1, n) * Factorial(n-k);\n</code></pre>\n\n<p>This way the method does slightly less work and can work with more numbers without overflowing, while still being as concise as before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T11:03:54.350",
"Id": "2374",
"Score": "0",
"body": "I'll try to guess what `ApplyTo` means. I believe it returns an array which will have the same items as original but in order determined by `this` permutation. You pass in `Red, Orange, Yellow, Green, LightBlue, Blue, Violet` and receive smth like `Yellow, Blue, Green, Orange, Red, Violet, LightBlue`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T11:07:27.607",
"Id": "2375",
"Score": "2",
"body": "Also regarding `static method to return an enumerable of all permutations` I would mention that probably it should be lazy and implemented with `yield return` in order to be more memory efficient"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T11:18:27.410",
"Id": "2376",
"Score": "0",
"body": "@Snowbear: Yes, it should, +1 for pointing that out. Regarding `ApplyTo` I can see what it does - I said \"I don't know how this is going to be used\" because I don't know whether he's only going to call it with arrays whose type actually is `Object[]`, in which case not using generics is okay, or (the more likely case) he's using it with more arrays of more specific types and then casting, in which case he should definitely use generics."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T01:11:19.377",
"Id": "2382",
"Score": "0",
"body": "Thanks for the detailed review. This code will be used to randomize running some automated test cases. I would agree I could use more Linq and generics and add more comments. I am new to C# and coding and this was my first try. Next time I will try to post less code for review."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T10:47:02.147",
"Id": "1358",
"ParentId": "1352",
"Score": "2"
}
},
{
"body": "<p>As far as I can see, order is always data.Length. </p>\n\n<pre><code> this.data = new int[n];\n this.order = this.data.Length;\n</code></pre>\n\n<p>So I would remove it, because there is only the chance to forget to update it somewhere. </p>\n\n<p>I would wish more documentation too: How is the class supposed to be used. From a functional approach I would expect more recursive methods, but it's unclear, how restrictive you're bound to some interface.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T15:31:51.603",
"Id": "1431",
"ParentId": "1352",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-19T20:07:13.287",
"Id": "1352",
"Score": "4",
"Tags": [
"c#",
"functional-programming",
"combinatorics"
],
"Title": "Generating permutations and combinations"
} | 1352 |
<p>The following block of code needs to be as fast as possible as it likely to be called many thousands of times in a run.</p>
<p>I am also conscious that my thinking style is leaning towards a more procedural style from time to time and hence I may not be taking full advantage of all the benefits that functional programming brings.</p>
<p>Any tips for</p>
<ol>
<li>making the code run faster, and</li>
<li>making it more functional</li>
</ol>
<p></p>
<pre><code>let qarray (tableName : string) (startAge : int) (startYear : int) =
let tableData = File.ReadAllLines tableName
// find which row the vertex is in
let vrow = Array.findIndex (fun (s:string) -> s.StartsWith vertexLiteral) tableData
let firstYear = int(tableData.[vrow].Split('\t').[1])
// filter out all the row prior to the column headers e.g. table description and comments
let filteredArray = Array.sub tableData (vrow+1) (tableData.Length-vrow-1)
// use the vertex info to read all lines beyond that, converting to doubles
let f (s:string) = s.Split('\t') |> Array.map double
let fullArray = Array.map f filteredArray
[| for i in 0 .. (120 - startAge - 1) -> fullArray.[startAge + i - 1].[System.Math.Min(startYear - firstYear + i + 1, fullArray.[0].Length)] |]
</code></pre>
| [] | [
{
"body": "<p>You should indent the body of the <code>qarray</code> function to make it more obvious where it starts and where it's end (I mean I know it ends at the end of the file in this case, but that's not immediately apparent at first glance).</p>\n\n<p>You should also rename your function <code>f</code> into something more descriptive.</p>\n\n<hr>\n\n<pre><code>let tableData = File.ReadAllLines tableName\n</code></pre>\n\n<p>If you're using .net 4.0, you can (and should) use <code>ReadLines</code> instead of <code>ReadAllLines</code> as <code>ReadAllLines</code> reads the whole file into memory before you can start to iterate, while <code>ReadLines</code> loads the file lazily which will be faster for large files.</p>\n\n<p>Note that since <code>ReadLines</code> returns a sequence, not an array, you can not access it using indices any longer. However this is a good thing as getting rid of the indices will lead to more functional code.</p>\n\n<hr>\n\n<pre><code>// find which row the vertex is in \nlet vrow = Array.findIndex (fun (s:string) -> s.StartsWith vertexLiteral) tableData\nlet firstYear = int(tableData.[vrow].Split('\\t').[1])\n\n// filter out all the row prior to the column headers e.g. table description and comments\nlet filteredArray = Array.sub tableData (vrow+1) (tableData.Length-vrow-1)\n</code></pre>\n\n<p>As I said, you can no longer use an index based approach here. The idiomatic way to get rid of certain elements at the beginning of a sequence is to use <code>skipWhile</code>. Since the first element we want is the one that starts with <code>vertexLiteral</code>, we skip elements while they do not start with <code>vertexLiteral</code>:</p>\n\n<pre><code>// Skip all rows up to the one the vertex is in\nlet relevantRows = tableData |> Seq.skipWhile (fun s -> not s.StartsWith vertexLiteral)\n</code></pre>\n\n<p>(Note that by using <code>|></code> to write <code>tableData</code> first I allowed F# to infer the type of <code>s</code> and thus didn't need a type annotation.)</p>\n\n<p>Now we can use <code>Seq.head</code> to get the first row of <code>relevantRows</code> (the one with the vertex) and <code>Seq.skip 1</code> to get the remaining rows. So the following lines become:</p>\n\n<pre><code>let firstYear = int((Seq.head relevantRows).Split('\\t').[1])\n\nlet filteredRows = Seq.skip 1 relevantRows\n</code></pre>\n\n<hr>\n\n<pre><code>// use the vertex info to read all lines beyond that, converting to doubles\nlet f (s:string) = s.Split('\\t') |> Array.map double\n\nlet fullArray = Array.map f filteredArray\n</code></pre>\n\n<p>Those lines are fine except that you now need to use <code>Seq.map</code> instead of <code>Array.map</code> (at least on the first line, the second one may stay <code>Array.map</code> as <code>Split</code> still returns an array, but there's no harm in using <code>Seq</code> instead), <code>f</code> needs a better name and <code>fullArray</code> needs to be renamed because it's not an array anymore.</p>\n\n<hr>\n\n<pre><code>[| for i in 0 .. (120 - startAge - 1) -> fullArray.[startAge + i - 1].[System.Math.Min(startYear - firstYear + i + 1, fullArray.[0].Length)] |]\n</code></pre>\n\n<p>Ok, here 120 is a magic number, which you did not explain (which you should fix by documenting its meaning), so I'm not sure whether you know that the table will have exactly 120 elements and you have the number in there to avoid a bounds violation or whether the table can contain more than 120 elements and you only want to take the first 120. I'm going to assume the latter is the case.</p>\n\n<p>Further it is not clear to me why you use <code>fullArray.[0].Length</code> instead of <code>fullArray.[startAge + i - 1]</code>. I'm going to assume that all rows have the same length and you chose <code>0</code> over <code>startAge + i - 1</code> for simplicity's sake.</p>\n\n<p>So what you're doing here is basically to skip the first <code>startAge - 2</code> elements then indexing into each remaining element using the minimum of its length and <code>startYear - firstYear + i + 1</code> as the index. This can be achieved nicely without an index based loop by using <code>Seq.skip</code> followed by <code>mapi</code> (<code>map</code> with an index), like this:</p>\n\n<pre><code>fullSequence |> Seq.skip (startAge - 2) |>\n Seq.mapi (fun i cols -> cols.[System.Math.Min(startYear - firstYear + i + 1, cols.Length)])\n</code></pre>\n\n<p>Since this is still a bit long, it might be worthwhile to factor out <code>fun i cols -> cols.[System.Math.Min(startYear - firstYear + i + 1, cols.Length)]</code> into a named function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T07:17:33.307",
"Id": "2385",
"Score": "0",
"body": "You're saying `Seq.Drop` two times here, isn't it a `Seq.Skip`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T12:40:32.440",
"Id": "2388",
"Score": "0",
"body": "@Snowbear: Yes, it is. Fixed. I must've written `drop` instead of `skip` a thousand times when writing it, but I've caught the others before posting. Thanks for noticing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-20T20:42:19.643",
"Id": "1363",
"ParentId": "1362",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-20T19:44:40.553",
"Id": "1362",
"Score": "4",
"Tags": [
"performance",
"functional-programming",
"csv",
"f#"
],
"Title": "Processing a tab-delimited file with vertexes and ages"
} | 1362 |
<p>I'm working on my graduate project and I had stumbled upon a somewhat dilemma, I've managed to solve it with some workarounds but I have my doubts that this is the most efficient way to deal with this problem.</p>
<p>I'm writing a class to deal with the Plesk API and making it as flexible as possible for easy use.</p>
<p>Here is the function for generating the XML that will be send out as request: </p>
<pre><code>private function emailCreatePacket($domain, $params){
// Create new XML document.
$xml = new DomDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
// Create packet
$packet = $xml->createElement('packet');
$packet->setAttribute('version', '1.4.2.0');
$xml->appendChild($packet);
$mail = $xml->createElement('mail');
$packet->appendChild($mail);
$create = $xml->createElement('create');
$mail->appendChild($create);
$filter = $xml->createElement('filter');
$create->appendChild($filter);
$domain_id = $xml->createElement('domain_id', $domain->id);
$filter->appendChild($domain_id);
$mailname = $xml->createElement('mailname');
$filter->appendChild($mailname);
foreach ($params as $key => $value) {
$node = $mailname;
if(strpos($key, ':') !== false){
$split = explode(':', $key);
$key = $split[1];
$node = ${$split[0]};
if(!isset(${$split[0]})){
${$split[0]} = $xml->createElement($split[0]);
$mailname->appendChild(${$split[0]});
}
$xmlelement = $xml->createElement($key, $value);
${$split[0]}->appendChild($xmlelement);
}else{
$xmlelement = $xml->createElement($key, $value);
$node->appendChild($xmlelement);
}
}
return $xml->saveXML();
}
</code></pre>
<p>Here's my public function:</p>
<pre><code>public function createEmail($host, $domain, $params){
$curl = $this->curlInit($host);
$packet = $this->emailCreatePacket($domain, $params);
echo $packet;
$response = $this->sendRequest($curl, $packet);
echo $response;
if($this->parseResponse($response)){
return true;
}
}
</code></pre>
<p>Here are the functions called:</p>
<pre><code>private function curlInit($host)
{
$security = new Security();
$password = $security->decode($host['host_pass']);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://{$host['host_address']}:{$host['host_port']}/{$host['host_path']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("HTTP_AUTH_LOGIN: {$host['host_user']}",
"HTTP_AUTH_PASSWD: {$password}",
"HTTP_PRETTY_PRINT: TRUE",
"Content-Type: text/xml")
);
return $curl;
}
private function sendRequest($curl, $packet){
curl_setopt($curl, CURLOPT_POSTFIELDS, $packet);
$result = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
$errorcode = curl_errno($curl);
curl_close($curl);
throw new Exception("Er is iets mis gegaan: <br /><br /> Foutcode: " . $errorcode . "<br /> Foutmelding: " . $error );
}
curl_close($curl);
return $result;
}
private function parseResponse($response){
$xml = new SimpleXMLElement($response);
$status = $xml->xpath('//status');
if($status[0] == "error"){
$errorcode = $xml->xpath('//errcode');
$errortext = $xml->xpath('//errtext');
throw new Exception("Er is iets mis gegaan: <br /><br /> Foutcode: ". $errorcode[0] . "<br /> Foutmelding: " . $errortext[0]);
}else{
return $response;
}
}
</code></pre>
<p>Here is the code I use to call my function:</p>
<pre><code><?php
/**
* @author Jeffro
* @copyright 2011
*/
require('init.php');
$security = new Security();
if($security->sslactive()){
try
{
$hosts = new Hosts();
$host = $hosts->getHost("192.168.1.60");
$pleskapi = new PleskApi();
$client = $pleskapi->getClientInfo($host, 'janbham');
$domain = $pleskapi->getDomainInfo($host, "lol.nl");
$params = array('name' => 'ohecht', 'mailbox:enabled' => 'true', 'mailbox:quota' => '100000000', 'alias' => 'aapjesrollen', 'password' => 'testmail', 'permissions:manage_drweb' => 'true');
$pleskapi->createEmail($host, $domain, $params);
}
catch (Exception $ex)
{
echo $ex->GetMessage();
}
}else{
?>
SSL needs to be active
<?php
}
?>
</code></pre>
<p>The problem was regarding the structure the API uses with it deeper nesting every time (which I solved now using ':' as a delimiter)</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T14:30:24.693",
"Id": "2441",
"Score": "0",
"body": "Just out of curiosity, in your execution script (that last bit), why did you close and open your script to output a one line string? Why not just `echo 'SSL needs to be active';`? BTW, this isn't a critique - I'm just curious."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T07:38:06.380",
"Id": "2478",
"Score": "0",
"body": "I've been flamed/bashed a lot on the subject of echo'ing stuff. Echo'ing HTML is generally bad. Not that it matters that much in this example because its just a test.php to test my functions."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T09:30:39.723",
"Id": "2486",
"Score": "0",
"body": "Really? `echo` just returns to stdout - I can't imagine why someone would get onto you about your output method (especially in a case like this). Now... If you're output is multiple lines, it is good practice to use an output buffer - but then you would `echo` the resulting `var`. I would like to hear someone's case against `echo`. Clearly it's there for a reason, and that reason is output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-08T12:01:13.707",
"Id": "144701",
"Score": "0",
"body": "why not nested array instead of `:`? Conceptually the `:` is used for attributes, and not for children. Because attributes values have not hierarchy. So I think it's better (not rule, just better) build `<mailbox quota=\"10000\">` if you use `:`, `<mailbox><quota>1000</quote></mailbox>` if you use nested array."
}
] | [
{
"body": "<p>Generally speaking, I like your code. I think it's well planned with few inefficiencies. I'm also impressed by your use of PHP's <code>DOMDocument</code> class. When creating XML via PHP, I usually opt for <code>foreach</code> loops and output buffering. I've been aware of this object class, but your example is the first I've ever seen it put to use. +1 for showing me something new! :D</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T12:08:03.897",
"Id": "1404",
"ParentId": "1368",
"Score": "2"
}
},
{
"body": "<ul>\n<li>In <code>createEmail</code> you only return <code>true</code> in one case; I'd just return\nthe value of <code>parseResponse</code> directly, then again, you don't seem to\nuse the return value.</li>\n<li>Being nitpicky, the style is a bit inconsistent, that includes\nspacing, quotes, but otherwise looks good. The <code>$params</code> creation\nshould be on multiple lines though, IMO 200 characters kind of\nstretches it.</li>\n<li>You could often leave out the last <code>else</code> block when you've already\nthrown an exception in the true case.</li>\n<li>What's with the random <code>echo</code> calls?</li>\n</ul>\n\n<p>Now the XML creation is, let's say, a bit verbose. <code>emailCreatePacket</code>\nshould use at least a helper function, or, if you have a recent enough\nversion of PHP I understand that you could also use a local anonymous\nfunction instead. So for starters, how about something like this:</p>\n\n<pre><code>private function addChild($xml, $parent, name) {\n $child = $xml->createElement(name);\n $parent->appendChild(child);\n return $child;\n}\n\nprivate function emailCreatePacket($domain, $params){\n $xml = new DomDocument('1.0', 'UTF-8');\n $xml->formatOutput = true;\n\n $packet = addChild($xml, $xml, 'packet');\n $packet->setAttribute('version', '1.4.2.0');\n\n $mail = addChild($xml, $packet, 'mail');\n\n $create = addChild($xml, $mail, 'create');\n ...\n}\n</code></pre>\n\n<p>You get the idea. Also check the PHP documentation, I think you'd be\nfaster with using SimpleXML here as well, unless I'm missing a reason\nwhy you're using the DOM instead. Thirdly, I would think about using a\nseparate PHP file to generate XML instead, after all, you're already\nbasically using a templating engine.</p>\n\n<p>The splitting of the parameters is probably fine, except I don't\nunderstand why you'd need that instead of passing nested arrays? Also\nthe current code there is limited to two levels, right, so for extra\npoints make that usable with arbitrarily nested parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-08T18:22:27.323",
"Id": "79953",
"ParentId": "1368",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-21T13:46:52.077",
"Id": "1368",
"Score": "7",
"Tags": [
"php",
"api",
"xml"
],
"Title": "Generating code with XML"
} | 1368 |
<p>While working with DirectShow, I came across the need to easily recognize different known 'sets' of GUIDs. E.g.: There are different GUIDs to indicate the possible time formats: <code>None, Byte, Field, Frame, MediaTime, Sample</code>. Working with enums instead of GUIDs would be a lot more useful in my opinion.</p>
<p>I decided to write the following abstract wrapper class which allows linking GUIDs to enums. You need to extend from it with the enum you want to expose as a type parameter.</p>
<pre><code>/// <summary>
/// An abstract class to represent a set of GUIDs as an enum.
/// </summary>
/// <typeparam name="T">An enum to use for the type to expose.</typeparam>
abstract class AbstractGuidEnum<T>
{
/// <summary>
/// The internal GUID.
/// </summary>
public Guid Guid
{
get; private set;
}
/// <summary>
/// The enum type for this GUID.
/// </summary>
public T Type
{
get;
private set;
}
/// <summary>
/// Specifies whether the GUID is known as a specific type or not.
/// </summary>
public bool IsKnownType
{
get; private set;
}
/// <summary>
/// List matching GUIDs with the enum types.
/// </summary>
private static Dictionary<Guid, T> m_typeList;
/// <summary>
/// Create a new GUID enum wrapping the given GUID.
/// </summary>
/// <param name="guid"></param>
protected AbstractGuidEnum( Guid guid )
{
Guid = guid;
if ( IsGuidKnownType( guid ) )
{
IsKnownType = true;
Type = GetType( guid );
}
else
{
IsKnownType = false;
}
}
/// <summary>
/// Create a new GUID enum for the specified type.
/// </summary>
/// <param name="type"></param>
protected AbstractGuidEnum( T type )
{
Type = type;
Guid = GetGuid( type );
}
/// <summary>
/// Call to make sure the list of types is initialized.
/// </summary>
private void InitializeTypes()
{
if ( m_typeList == null )
{
m_typeList = new Dictionary<Guid, T>();
FillTypeList( m_typeList );
}
}
public bool IsGuidKnownType( Guid guid )
{
InitializeTypes();
return m_typeList.ContainsKey( guid );
}
/// <summary>
/// Returns the type for a given GUID.
/// </summary>
/// <param name="type">The GUID to get the type for.</param>
/// <returns>The type for the given GUID.</returns>
public T GetType( Guid type )
{
InitializeTypes();
if ( !m_typeList.ContainsKey( type ) )
{
throw new ArgumentException("No type is defined for the given GUID.", "type");
}
return m_typeList[ type ];
}
/// <summary>
/// Return the guid for a given type.
/// </summary>
/// <param name="type">The Type to get the Guid for.</param>
/// <returns>The Guid for the given type.</returns>
/// <exception cref="InvalidCastException">
/// Thrown when no Guid exists for the given type.
/// </exception>
private Guid GetGuid( T type )
{
InitializeTypes();
try
{
return m_typeList.Keys.First( guid => m_typeList[ guid ].Equals( type ) );
}
catch ( InvalidOperationException )
{
throw new InvalidCastException( "No Guid exists for the given type." );
}
}
public override bool Equals( object obj )
{
if ( !(obj is AbstractGuidEnum<T>) )
{
return false;
}
AbstractGuidEnum<T> guidObj = obj as AbstractGuidEnum<T>;
return Guid.Equals( guidObj.Guid );
}
public override int GetHashCode()
{
unchecked
{
return Guid.GetHashCode();
}
}
/// <summary>
/// Fill up the list which matches GUIDs to the desired enum types.
/// </summary>
/// <param name="typeList"></param>
protected abstract void FillTypeList(Dictionary<Guid, T> typeList);
}
</code></pre>
<p>As an example, the time formats:</p>
<pre><code>/// <summary>
/// The possible time formats for seeking operations.
/// </summary>
public enum TimeFormat
{
None,
Byte,
Field,
Frame,
MediaTime,
Sample
}
/// <summary>
/// A wrapper class which represents the possible media types for DirectShow.
/// Since a MediaType is a Guid, a simple enum couldn't be used.
/// </summary>
class GuidTimeFormat : AbstractGuidEnum<TimeFormat>
{
/// <summary>
/// Create a new GuidTimeFormat wrapping the given GUID.
/// </summary>
/// <param name="guid">The GUID to wrap.</param>
public GuidTimeFormat( Guid guid ) : base( guid )
{
}
public GuidTimeFormat( TimeFormat timeFormat ) : base( timeFormat )
{
}
protected override void FillTypeList( Dictionary<Guid, TimeFormat> typeList )
{
typeList.Add( DirectShowLib.TimeFormat.None, TimeFormat.None );
typeList.Add( DirectShowLib.TimeFormat.Byte, TimeFormat.Byte );
typeList.Add( DirectShowLib.TimeFormat.Field, TimeFormat.Field );
typeList.Add( DirectShowLib.TimeFormat.Frame, TimeFormat.Frame );
typeList.Add( DirectShowLib.TimeFormat.MediaTime, TimeFormat.MediaTime );
typeList.Add( DirectShowLib.TimeFormat.Sample, TimeFormat.Sample );
}
}
</code></pre>
<p>Plain and simple, but is this the cleanest approach? Any improvements, or reasons why this would be unnecessary?</p>
<p>E.g.: Notice that some candidate static functions can't be made static because of <code>InitializeTypes</code> which relies on the overridable <code>FillTypeList</code> method.</p>
<hr>
<p>So far I agree with most of the comments made, I posted this code since I felt it might be 'inappropriately clever code'. One of the benefits, in a possible scenario is the following however:</p>
<pre><code>// Add the found type to the list.
MediaType type = new MediaType
{
MajorType = new GuidMediaMajorType(amType.majorType),
SubType = new GuidMediaSubType(amType.subType)
};
break;
</code></pre>
<p>The types are 'wrapped' in the guid type, which tries to link them up to the correct enum, <strong>when found</strong>. The alternative would be to map unknown types to an 'Unknown' enum value, but then the guid information is lost. This does seem to be the only benefit of this wrapper over a simple helper class with conversion functions. By writing this code I actually managed to find <a href="http://sourceforge.net/tracker/?func=detail&aid=3014857&group_id=136334&atid=735691">a copy/paste bug in DirectShowLib</a>, as duplicate GUIDs were declared. Ofcourse, I would have also found this using a simple dictionary approach.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T20:11:30.077",
"Id": "2397",
"Score": "0",
"body": "Do you have to use `Guid`? I can imagine easier ways to map `enum` into `Guid` if you do not it to be truly random."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T22:56:20.403",
"Id": "2399",
"Score": "0",
"body": "[DirectShow uses GUIDs](http://msdn.microsoft.com/en-us/library/dd443282%28v=vs.85%29.aspx) for all kinds of stuff, so yeah, I'm dependant on them."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T23:24:10.857",
"Id": "2400",
"Score": "0",
"body": "Are you going to use `TimeFormat` enum primarily in your code and `GuidTimeFormat` will be used only where you need to map enum into DirectShow guid? I have a strong feeling that this is made to complicated but until I get how are going to use it I can't fully express that feeling"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T00:02:43.497",
"Id": "2401",
"Score": "0",
"body": "The GUID wrappers are supposed to be used only in interop code, and passed around there and such, e.g. for easier debugging, as GUIDs themselves don't say much. They are used in multiple classes. The exposed API only exposes the enums. You're making me wonder whether simple statically initialized dictionaries aren't a better solution. Although that wouldn't support unknown types, e.g. for media types. The 'advantage' of this approach is that the wrapper class is used as an 'enum' value and passed as such."
}
] | [
{
"body": "<p>I would avoid casting the same thing more then once. You can simply use <code>as</code>, it will return null if the object is not of the correct type.</p>\n\n<pre><code>public override bool Equals( object obj )\n{\n AbstractGuidEnum<T> guidObj = obj as AbstractGuidEnum<T>;\n if ( guidObj == null )\n {\n return false;\n }\n\n return Guid.Equals( guidObj.Guid );\n}\n</code></pre>\n\n<p>If you are going to have an equals method, it might be good to implement <code>IEquatable</code> and <code>IEquatable<AbstractGuidEnum></code>.</p>\n\n<p>I don't see anywhere that AbstractGuidEnum.Type, Guid, and IsKnowType are set, other then the constructor. If that is the case, I would make them into properties with backing fields and make the backing fields readonly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T00:12:13.673",
"Id": "2402",
"Score": "1",
"body": "Very true on the equals, now it's actually a two liner, the `as` cast followed by: `return guid != null && Guid.Equals( guid.Guid );`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T00:31:31.737",
"Id": "2403",
"Score": "0",
"body": "You are also right about the readonly, it's a pity there isn't a concise way to specify this with automated properties yet, like e.g. dropping the set altogether, or writing `readonly set;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T23:59:12.487",
"Id": "1372",
"ParentId": "1371",
"Score": "6"
}
},
{
"body": "<p>I think your solution violates the <a href=\"http://en.wikipedia.org/wiki/Kiss_principle\" rel=\"nofollow\">Kiss_principle</a>. What benifit does your solution have over a simple but <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> violating</p>\n\n<pre><code>public TimeFormat GetType( Guid type )\n{\n switch (type) {\n case DirectShowLib.TimeFormat.None : return TimeFormat.None;\n ...\n\n\npublic Guid GetType( TimeFormat type )\n{\n switch (type) {\n case TimeFormat.None : return DirectShowLib.TimeFormat.None;\n ...\n</code></pre>\n\n<p>See also\n<a href=\"http://blogs.msdn.com/b/ericgu/archive/2006/05/31/611659.aspx\" rel=\"nofollow\">Seven Deadly Sins of Programming - Sin #6 - Inappropriately clever code</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T11:05:02.840",
"Id": "2407",
"Score": "0",
"body": "I don't like this exact solution, because you have to specify both directions of `Enum <-> Guid` mapping separately and in this manner it leaves a space for human errors. I would replace it with some run-time mapping via bidirectional dictionary. Though I partially agree that something made in too sophisticated way here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T12:16:17.180",
"Id": "2408",
"Score": "3",
"body": "A switch on Guid isn't possible. This most definitly calls for at least a dictionary."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T12:38:50.880",
"Id": "2409",
"Score": "0",
"body": "I updated with an example and explanation of one additional advantage over helper functions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T08:59:55.257",
"Id": "1378",
"ParentId": "1371",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-21T19:28:35.770",
"Id": "1371",
"Score": "9",
"Tags": [
"c#"
],
"Title": "Linking GUIDs to enums"
} | 1371 |
<p>Given the following problem:</p>
<pre><code>;3.3 Tabulate the function k = 2^n for n = 1..50.
;Do this for the fewest possible multiplications.[3]
</code></pre>
<p>I wrote this answer:</p>
<pre><code>(defun k (n) (ash 2 (1- n)))
(loop for n from 1 to 50 do
(format t "k(~a) = ~a ~%" n (k n)))
</code></pre>
<p>What do you think?</p>
| [] | [
{
"body": "<p>If you use <code>1</code> instead of <code>2</code> as the number to shift, you won't have to subtract one from <code>n</code>. I.e. you can just define <code>k</code> as <code>(ash 1 n)</code>.</p>\n\n<p>Other than that your code looks fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T21:26:28.060",
"Id": "1392",
"ParentId": "1374",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1392",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T06:32:47.253",
"Id": "1374",
"Score": "2",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Tabulate k = 2^n minimizing multiplication"
} | 1374 |
<p>Given the following problem:</p>
<blockquote>
<p>It is conjectured that for any \$n > 0\$, \$n^2 + 3n + 5\$ is never
divisible by 121. Test this conjecture for \$n = 1,2,...,9999,10000\$.</p>
</blockquote>
<p>I wrote the following solution:</p>
<pre><code>(defpackage :one-twenty-one-divisible (:use :cl))
(in-package :one-twenty-one-divisible)
(defun divisible (n) (= (mod n 121) 0))
(defun f_n (n) (+ (expt n 2) (* 3 n) 5))
(let ((divisible-result (loop for n from 1 to 10000 when (divisible (f_n n)) collect n)))
(format t "The conjecture that for 1 <= n <= 10,000 f(n) = n^2 + 3n + 5 is indivisible by 121 is ~:[false~;true~].~%" (null divisible-result))
(unless (null divisible-result) (format t "The following items were found to have f(n) that is divisible by 121: ~a ~%" divisible-result)))
</code></pre>
<p>What do you think?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-10T13:24:03.053",
"Id": "3062",
"Score": "0",
"body": "Are you asking if it is evenly divisible? It would have to be a zero of the function to be evenly divisible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T09:22:20.553",
"Id": "136238",
"Score": "0",
"body": "Since this is a code review: `f_n` is a really bad name for a function, no matter what it does. In Lisp in particular, because, unlike in languages with infix operators, where it is easy to confuse the minus sign if used as a part of identifier with its usage as an operator, there isn't such problem in Lisp, thus, underscore isn't normally used in identifiers."
}
] | [
{
"body": "<p>I don't know Lisp, but you can speed up the calculation by observing that n² + 3n + 5 is never divisible by 11 (and hence never divisible by 121), except when n mod 11 == 4. </p>\n\n<p>If you check the equation for the remaining candidates (11*k+4) in the \"full\" module 121 (e.g. using Lisp, but I did it in Excel), you get always an remainder of 33, so the conjecture is indeed true.</p>\n\n<p>I would consider this exercise as \"bad style\", as it encourages the \"brute force\" instead of the \"think\" approach. There are enough not-so-easy to solve conjectures (e.g. Goldbach's conjecture) where falling back to brute force actually makes sense.</p>\n\n<p><strong>[More Explanation]</strong></p>\n\n<p>Modular arithmetic is described <a href=\"http://en.wikipedia.org/wiki/Modular_arithmetic\">here</a>, but I will try to give a short introduction: Let's say we want to know the remainder of the polynom by division by 11 when n is of the form 11*k + 3. We <em>could</em> write</p>\n\n<pre><code>(11*k+3)² + 3*(11*k+3) + 5\n</code></pre>\n\n<p>But as we are only interested in remainders, not the numbers itself, we \"forget\" all multiples of 11 and write in modular arithmetics:</p>\n\n<pre><code>3² + 3*3 + 5 | mod 11\n9 + 9 + 5 | mod 11\n23 | mod 11\n1 | mod 11 \n</code></pre>\n\n<p>This says that when we have a number 11*k + 3, our polynom will always have a remainder of 1 when divided by 11. n=3 gives a polynom value of 23, which is 1 mod 11. n=256 gives 66309, which is again 1 mod 11. As 121 = 11², if a number is not divisible by 11, it isn't divisible by 121 either. So no number n = 11*k + 3 is ever divisible by 121. Testing all the cases from n = 11*k + 0 to n = 11*k + 10 I found, that only for 11*k + 4 the polynom is divisible by 11. Checking all the values 11*k + 4 in module 121 (that are 121*u + v with v = 4, 15, 26, 37, 48, 59, 70, 81, 92, 103, 114) I found that all leave a remainder of 33, proving the conjecture (let's say we take n = 121 + 15 = 136, we get a polynom value of 18909, and as expected, a remainder of 33 when dividing by 121).</p>\n\n<p>So there is nothing <em>wrong</em> with your code (and as I said I don't know Lisp), but in my opinion the \"better\" solution would be to say: It can be shown <strong>directly</strong> (even with paper and pencil) that the polynom is never divisible by 121, so no test is needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T13:22:33.773",
"Id": "2976",
"Score": "0",
"body": "can you explain a bit more? I'm not sure I understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-08T14:36:35.720",
"Id": "3015",
"Score": "1",
"body": "Oh, wow. It took me a while to understand your explanation, but when you get it, it's very clear. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-07T09:34:39.050",
"Id": "1712",
"ParentId": "1375",
"Score": "11"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/questions/1375/common-lisp-is-fn-n2-3n-5-not-ever-divisible-by-121/1712#1712\">Landei's answer</a> is great from a math standpoint, but I did have a tip from a Lisp standpoint. If you're just testing a conjecture, you might want to consider using the <a href=\"http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/sec_6-1-4-2.html\" rel=\"nofollow noreferrer\"><code>THEREIS</code></a> clause in your <code>LOOP</code>. This will break out of the loop as soon as it finds the first example that returns something other <code>NIL</code>, and it will return that value as the overall return value of the <code>LOOP</code>. This has two advantages; one is that it's more efficient in the case that there are a lot of positive results, and (more importantly, in most instances) it communicates your intent more clearly. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-01T21:19:46.577",
"Id": "3253",
"ParentId": "1375",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1712",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T06:56:15.970",
"Id": "1375",
"Score": "6",
"Tags": [
"mathematics",
"lisp",
"common-lisp"
],
"Title": "Determining if f(n) = n^2 + 3n + 5 is ever divisible by 121"
} | 1375 |
<p>I have successfully placed multiple jquery ui slider on a page and its transalation text too. you can check it live on:
<a href="http://outsourcingnepal.com/projects/jQuery%20slider/" rel="nofollow">http://outsourcingnepal.com/projects/jQuery%20slider/</a></p>
<p>I have my jquery code as :</p>
<pre><code>var arrLabel1 = new Array('Not Good', 'OK', 'Average', 'Above Average', 'Excellent', 'Outstanding');
$(function() {
$( ".slider_control" ).slider({
value:0,
min: 0,
max: 5,
step: 1,
slide: function( event, ui ) {
$( "#slider_" + $(this).attr('rel') ).val( ui.value );
$( "#label_" + $(this).attr('rel') ).text( arrLabel1[ ui.value ] );
}
}).each(function(index){
$( "#slider_" + (index + 1) ).val( $( this ).slider( "value" ) );
$( "#label_" + (index + 1) ).text( arrLabel1[ $(this).slider( "value" ) ] );
});
});
</code></pre>
<p>Now i would like to optimize it so that i can be independent of rel attribute.</p>
<p>MY HTML:</p>
<pre><code><ul class="slider-container">
<li class="ui_slider">
<div class="title">Overall: <span id="label_1"></span></div>
<input type="hidden" name="overall_review" id="slider_1" />
<div class="slider_control" rel="1"></div>
</li>
<li class="ui_slider">
<div class="title">Cleanliness: <span id="label_2"></span></div>
<input type="hidden" name="overall_review" id="slider_2" />
<div class="slider_control" rel="2"></div>
</li>
<li class="ui_slider">
<div class="title">Facilities: <span id="label_3"></span></div>
<input type="hidden" name="overall_review" id="slider_3" />
<div class="slider_control" rel="3"></div>
</li>
<li class="ui_slider">
<div class="title">Location: <span id="label_4"></span></div>
<input type="hidden" name="overall_review" id="slider_4" />
<div class="slider_control" rel="4"></div>
</li>
<li class="ui_slider">
<div class="title">Quality of Service: <span id="label_5"></span></div>
<input type="hidden" name="overall_review" id="slider_5" />
<div class="slider_control" rel="5"></div>
</li>
<li class="ui_slider">
<div class="title">Room: <span id="label_6"></span></div>
<input type="hidden" name="overall_review" id="slider_6" />
<div class="slider_control" rel="6"></div>
</li>
<li class="ui_slider">
<div class="title">Value of Money: <span id="label_7"></span></div>
<input type="hidden" name="overall_review" id="slider_7" />
<div class="slider_control" rel="7"></div>
</li>
</ul>
</code></pre>
| [] | [
{
"body": "<p>In my option your code has two problems:</p>\n\n<ol>\n<li><p>You unnecessarily fill your HTML with empty elements which you could just create in your script. Changing that would remove the necessity for the <code>rel</code> attribute.</p></li>\n<li><p>more importantly (even if there are people that may disagree), you have unnecessarily made your form dependent on JavaScript. It would be much better to have <code>select</code> elements in your HTML, which you can replace with sliders. That way even users without JavaScript can use your form unrestricted.</p></li>\n</ol>\n\n<p>I've written an example how I would do it:</p>\n\n<pre><code>$(\".ui_slider select\").each(function() {\n var select = $(this); // Cache a refernce to the current select\n var sliderDiv = $(\"<div></div>\"); // create a div for the slider\n var displayLabel = $(\"<span></span>\"); // create a span to display current selection\n\n if (select[0].selectedIndex < 0) // Make sure that an item is selected\n select[0].selectedIndex = 0;\n\n select\n .hide() // hide the select\n .before( // Insert display label before the select\n displayLabel\n .text(select.find(\"option:selected\").text()) // and set it's default text\n )\n .after( \n sliderDiv // Insert the silder div after the select\n .data(\"select\", select) // store a reference to the select\n .data(\"label\", displayLabel) // store a reference to the display label\n .slider({\n max: select.find(\"option\").length - 1, // set to number of items in select\n slide: function(event, ui) {\n var select = $(this).data(\"select\"); \n select[0].selectedIndex = ui.value; // update the select\n $(this).data(\"label\").text( // Update the display label\n select.find(\"option:selected\").text()\n );\n }\n })\n );\n});\n</code></pre>\n\n<p>HTML (repeat as needed):</p>\n\n<pre><code><div class=\"ui_slider\">\n <label for=\"overall\">Overall: </label>\n <select name=\"overall\" id=\"overall\">\n <option value=\"0\">Not Good</option>\n <option value=\"1\">OK</option>\n <option value=\"2\">Average</option>\n <option value=\"3\">Above Average</option>\n <option value=\"4\">Excellent</option>\n <option value=\"5\">Outstanding</option>\n </select>\n</div>\n</code></pre>\n\n<p>Working sample: <a href=\"http://jsfiddle.net/YfqCx/2/\" rel=\"nofollow\">http://jsfiddle.net/YfqCx/2/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T18:20:04.273",
"Id": "2417",
"Score": "0",
"body": "your suggestions are really good ones..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T16:05:32.423",
"Id": "1387",
"ParentId": "1376",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T08:01:36.423",
"Id": "1376",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Review on my multiple JQuery Slider on a page"
} | 1376 |
<p>I've written a plugin that takes a generic approach to creating sticky headers and would like to have the code reviewed. Is this acceptable JavaScript?</p>
<p><strong><a href="http://robertfall.github.com/Stuck-On-Top/" rel="nofollow">Demo Page</a></strong></p>
<p>It's my first plugin however and I'd like feedback about how to make it more user friendly and more readable before releasing it and putting it up on GitHub.</p>
<p>The header becomes stuck to the top of the page until it encounters the bottom of it's container, upon which it gets stuck to the bottom of the container and floats off the screen.</p>
<p>I had to create a placeholder to take the header's original place once it leaves the document flow and also apply fixed CSS settings to the header to keep it's appearance the same when it leaves the flow.</p>
<pre><code>(function ($) {
$.fn.stickySectionHeaders = function (options) {
var settings = $.extend({
stickyClass: 'header',
padding: 0
}, options);
return $(this).each(function () {
var container = $(this);
var header = $('.' + settings.stickyClass, container);
var originalCss = {
position: header.css('position'),
top: header.css('top'),
width: header.css('width')
};
var placeholder = undefined;
var originalWidth = header.outerWidth();
$(window).scroll(function () {
var containerTop = container.offset().top;
var headerOrigin = header.offset().top;
var headerHeight = header.outerHeight();
var containerHeight = container.outerHeight();
var containerTop = container.offset().top;
var containerSize = container.outerHeight();
var pageOffset = $(window).scrollTop() + settings.padding;
var containerBottom = containerHeight + containerTop;
if (pageOffset < containerTop && placeholder != undefined) {
if (placeholder != undefined) {
placeholder.remove();
placeholder = undefined;
header.css(originalCss);
}
}
else if (pageOffset > containerTop && pageOffset < (containerBottom - headerHeight)) {
if (placeholder == undefined) {
placeholder = $('<div/>')
.css('height', header.outerHeight() + 'px')
.css('width', header.width() + 'px');
header.before(placeholder);
header.css('position', 'fixed');
header.css('width', originalWidth + 'px');
}
header.css('top', settings.padding + 'px');
}
else if (pageOffset > (containerBottom - headerHeight)) {
header.css('top', (containerBottom - headerHeight) - pageOffset + settings.padding + 'px');
}
});
});
}
})(jQuery);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T16:10:02.420",
"Id": "2414",
"Score": "0",
"body": "A working example would be great, because currently I can't imagine what \"sticky headers\" are supposed to be..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T18:57:56.293",
"Id": "2418",
"Score": "0",
"body": "Added a link to the [demo](http://robertfall.github.com/Stuck-On-Top/)!"
}
] | [
{
"body": "<p>At the risk of nitpicking there's quite a fiew small/micro-optimizations that could be done:</p>\n\n<ul>\n<li><p>group multiple <code>var</code> declarations using commas</p>\n\n<p><code>var containerTop = container.offset().top, headerOrigin = header.offset().top;</code></p></li>\n<li><p>chain method calls to the same object</p>\n\n<p><code>header.before(placeholder).css('...')</code></p></li>\n<li><p>group multiple calls to css() passing an object as the parameter:</p>\n\n<p><code>header.css({ position: 'fixed', width: originalWidth + 'px'});</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T09:12:48.830",
"Id": "2485",
"Score": "0",
"body": "Thanks, this is exactly the sort of thing I was looking for!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T09:47:04.580",
"Id": "1403",
"ParentId": "1381",
"Score": "2"
}
},
{
"body": "<p>I used this with an element which was on the left of the container, which meant that the div put in unnecessary space on the right. \nI needed to adjust line 40 to the folloing:</p>\n\n<pre><code> placeholder = $('<div style=\"display:none;\"/>')\n</code></pre>\n\n<p>Not sure how you would do this automatically.</p>\n\n<p>Also, what is the purpose of</p>\n\n<pre><code> header.css('width', originalWidth + 'px');\n</code></pre>\n\n<p>Seems to work better without this for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-17T07:39:28.720",
"Id": "2989",
"ParentId": "1381",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "1403",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T12:55:21.630",
"Id": "1381",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "jQuery plugin to create sticky headers"
} | 1381 |
<p>I have been a programmer for 12 years, mainly ERP software and C development and
am looking to make a career/specialty change to Java. I've read it countless
times if you want to learn a new language you need to write code, then write
some more code and then finally write more code. So I've written some code!</p>
<p>I love Poker, so I have written a small Texas Hold'em program. Here is the overview of what it does:</p>
<ol>
<li>Asks the user for the number of players </li>
<li>Create a deck of cards </li>
<li>Shuffle </li>
<li>Cut the deck </li>
<li>Deal players hole cards </li>
<li>Burns a card </li>
<li>Deals flop </li>
<li>Burns a card </li>
<li>Deals turn </li>
<li>Burns a card </li>
<li>Deals river </li>
<li>Prints the deck to console to show random deck was used </li>
<li>Prints the 'board' </li>
<li>Prints burn cards </li>
<li>Printers players cards </li>
<li>Evaluates the value of each players hand (Royal flush, full house, etc...) </li>
</ol>
<p>There are 6 .java files (see below for links). I used an interface, created my own comparators, even implemented some try/catch blocks (although I'm still learning how to use these properly).</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TexasHoldEm {
public static void main(String[] args) throws Exception {
// variables
Deck holdemDeck = new Deck();
int numPlayers = 0;
int cardCounter = 0;
int burnCounter = 0;
int boardCounter = 0;
Board board = new Board();
// initializations
numPlayers = getNumberOfPlayers();
Player[] player = new Player[numPlayers];
/* 3 shuffles just like in real life. */
for(int i=0;i<3;i++){
holdemDeck.shuffle();
}
// Cut Deck
holdemDeck.cutDeck();
// Initialize players
for (int i=0;i<numPlayers;i++){
player[i] = new Player();
}
// Main processing
// Deal hole cards to players
for (int i=0;i<2;i++){
for (int j=0;j<numPlayers;j++){
player[j].setCard(holdemDeck.getCard(cardCounter++), i);
}
}
// Start dealing board
// Burn one card before flop
board.setBurnCard(holdemDeck.getCard(cardCounter++), burnCounter++);
// deal flop
for (int i=0; i<3;i++){
board.setBoardCard(holdemDeck.getCard(cardCounter++), boardCounter++);
}
// Burn one card before turn
board.setBurnCard(holdemDeck.getCard(cardCounter++), burnCounter++);
// deal turn
board.setBoardCard(holdemDeck.getCard(cardCounter++), boardCounter++);
// Burn one card before river
board.setBurnCard(holdemDeck.getCard(cardCounter++), burnCounter++);
// deal river
board.setBoardCard(holdemDeck.getCard(cardCounter++), boardCounter++);
//------------------------
// end dealing board
//------------------------
System.out.println("The hand is complete...\n");
// print deck
holdemDeck.printDeck();
//print board
board.printBoard();
// print player cards
System.out.println("The player cards are the following:\n");
for (int i=0;i<numPlayers;i++){
player[i].printPlayerCards(i);
}
// print burn cards
board.printBurnCards();
//------------------------
// Begin hand comparison
//------------------------
for (int i=0;i<numPlayers;i++){
HandEval handToEval = new HandEval();
// populate with player cards
for (int j=0;j<player[i].holeCardsSize();j++){
handToEval.addCard(player[i].getCard(j),j);
}
//populate with board cards
for (int j=player[i].holeCardsSize();j<(player[i].holeCardsSize()+board.boardSize());j++){
handToEval.addCard(board.getBoardCard(j-player[i].holeCardsSize()),j);
}
System.out.println("Player " + (i+1) + " hand value: " + handToEval.evaluateHand());
}
}
protected static int getNumberOfPlayers() throws Exception{
int intPlayers = 0;
String userInput = "";
// Get number of players from user.
System.out.println("Enter number of players (1-9):");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
userInput = br.readLine();
} catch (IOException ioe) {
System.out.println("Error: IO error trying to read input!");
System.exit(1);
}
// convert user input to an integer
try {
intPlayers = Integer.parseInt(userInput);
} catch (NumberFormatException nfe) {
System.out.println("Error: Input provided is not a valid Integer!");
System.exit(1);
}
if ((intPlayers<1) || (intPlayers>9)){
throw new Exception("Error: Number of players must be an integer between 1 and 9");
}
return intPlayers;
}
}
</code></pre>
<p><a href="http://pastebin.com/rDGwn9r7" rel="nofollow noreferrer">Player.java</a> </p>
<pre><code>public class Player {
private Card[] holeCards = new Card[2];
//constructor
public Player(){
}
public Player(Card card1, Card card2){
holeCards[0] = card1;
holeCards[1] = card2;
}
//methods
protected void setCard(Card card, int cardNum){
holeCards[cardNum] = card;
}
protected Card getCard(int cardNum){
return holeCards[cardNum];
}
protected int holeCardsSize(){
return holeCards.length;
}
protected void printPlayerCards(int playerNumber){
System.out.println("Player " + (playerNumber+1) + " hole cards:");
for (int i=0;i<2;i++){
System.out.println(holeCards[i].printCard());
}
System.out.println("\n");
}
}
</code></pre>
<p><a href="http://pastebin.com/eA9L2vXv" rel="nofollow noreferrer">HandEval.java</a> </p>
<pre><code>import java.util.Arrays;
public class HandEval {
private Card[] availableCards = new Card[7];
private final static short ONE = 1;
private final static short TWO = 2;
private final static short THREE = 3;
private final static short FOUR = 4;
// Constructor
public HandEval(){
}
//methods
protected void addCard(Card card, int i){
availableCards[i] = card;
}
protected Card getCard(int i){
return availableCards[i];
}
protected int numCards(){
return availableCards.length;
}
protected void sortByRank(){
Arrays.sort(availableCards, new rankComparator());
}
protected void sortBySuit(){
Arrays.sort(availableCards, new suitComparator());
}
protected void sortBySuitThenRank(){
Arrays.sort(availableCards, new suitComparator());
Arrays.sort(availableCards, new rankComparator());
}
protected void sortByRankThenSuit(){
Arrays.sort(availableCards, new rankComparator());
Arrays.sort(availableCards, new suitComparator());
}
protected String evaluateHand(){
String handResult = new String();
short[] rankCounter = new short[13];
short[] suitCounter = new short[4];
// initializations
for (int i=0;i<rankCounter.length;i++){
rankCounter[i] =0;
}
for (int i=4;i<suitCounter.length;i++){
suitCounter[i] = 0;
}
// Loop through sorted cards and total ranks
for(int i=0; i<availableCards.length;i++){
rankCounter[ availableCards[i].getRank() ]++;
suitCounter[ availableCards[i].getSuit() ]++;
}
//sort cards for evaluation
this.sortByRankThenSuit();
// hands are already sorted by rank and suit for royal and straight flush checks.
// check for royal flush
handResult = evaluateRoyal(rankCounter, suitCounter);
// check for straight flush
if (handResult == null || handResult.length() == 0){
handResult = evaluateStraightFlush(rankCounter, suitCounter);
}
// check for four of a kind
if (handResult == null || handResult.length() == 0){
handResult = evaluateFourOfAKind(rankCounter);
}
// check for full house
if (handResult == null || handResult.length() == 0){
handResult = evaluateFullHouse(rankCounter);
}
// check for flush
if (handResult == null || handResult.length() == 0){
handResult = evaluateFlush(rankCounter, suitCounter);
}
// check for straight
if (handResult == null || handResult.length() == 0){
// re-sort by rank, up to this point we had sorted by rank and suit
// but a straight is suit independent.
this.sortByRank();
handResult = evaluateStraight(rankCounter);
}
// check for three of a kind
if (handResult == null || handResult.length() == 0){
handResult = evaluateThreeOfAKind(rankCounter);
}
// check for two pair
if (handResult == null || handResult.length() == 0){
handResult = evaluateTwoPair(rankCounter);
}
// check for one pair
if (handResult == null || handResult.length() == 0){
handResult = evaluateOnePair(rankCounter);
}
// check for highCard
if (handResult == null || handResult.length() == 0){
handResult = evaluateHighCard(rankCounter);
}
return handResult;
}
private String evaluateRoyal(short[] rankCounter, short[] suitCounter){
String result = "";
// Check for Royal Flush (10 - Ace of the same suit).
// check if there are 5 of one suit, if not royal is impossible
if ((rankCounter[9] >= 1 && /* 10 */
rankCounter[10] >= 1 && /* Jack */
rankCounter[11] >= 1 && /* Queen */
rankCounter[12] >= 1 && /* King */
rankCounter[0] >= 1) /* Ace */
&& (suitCounter[0] > 4 || suitCounter[1] > 4 ||
suitCounter[2] > 4 || suitCounter[3] > 4)){
// min. requirements for a royal flush have been met,
// now loop through records for an ace and check subsequent cards.
// Loop through the aces first since they are the first card to
// appear in the sorted array of 7 cards.
royalSearch:
for (int i=0;i<3;i++){
// Check if first card is the ace.
// Ace must be in position 0, 1 or 2
if (availableCards[i].getRank() == 0){
// because the ace could be the first card in the array
// but the remaining 4 cards could start at position 1,
// 2 or 3 loop through checking each possibility.
for (int j=1;j<4-i;j++){
if ((availableCards[i+j].getRank() == 9 &&
availableCards[i+j+1].getRank() == 10 &&
availableCards[i+j+2].getRank() == 11 &&
availableCards[i+j+3].getRank() == 12)
&&
(availableCards[i].getSuit() == availableCards[i+j].getSuit() &&
availableCards[i].getSuit() == availableCards[i+j+1].getSuit() &&
availableCards[i].getSuit() == availableCards[i+j+2].getSuit() &&
availableCards[i].getSuit() == availableCards[i+j+3].getSuit())){
// Found royal flush, break and return.
result = "Royal Flush!! Suit: " + Card.suitAsString(availableCards[i].getSuit());
break royalSearch;
}
}
}
}
}
return result;
}
// Straight flush is 5 consecutive cards of the same suit.
private String evaluateStraightFlush(short[] rankCounter, short[] suitCounter){
String result = "";
if (suitCounter[0] > 4 || suitCounter[1] > 4 ||
suitCounter[2] > 4 || suitCounter[3] > 4){
// min. requirements for a straight flush have been met.
// Loop through available cards looking for 5 consecutive cards of the same suit,
// start in reverse to get the highest value straight flush
for (int i=availableCards.length-1;i>3;i--){
if ((availableCards[i].getRank()-ONE == availableCards[i-ONE].getRank() &&
availableCards[i].getRank()-TWO == availableCards[i-TWO].getRank() &&
availableCards[i].getRank()-THREE == availableCards[i-THREE].getRank() &&
availableCards[i].getRank()-FOUR == availableCards[i-FOUR].getRank())
&&
(availableCards[i].getSuit() == availableCards[i-ONE].getSuit() &&
availableCards[i].getSuit() == availableCards[i-TWO].getSuit() &&
availableCards[i].getSuit() == availableCards[i-THREE].getSuit() &&
availableCards[i].getSuit() == availableCards[i-FOUR].getSuit())){
// Found royal flush, break and return.
result = "Straight Flush!! " + Card.rankAsString(availableCards[i].getRank()) + " high of " + Card.suitAsString(availableCards[i].getSuit());
break;
}
}
}
return result;
}
// Four of a kind is 4 cards with the same rank: 2-2-2-2, 3-3-3-3, etc...
private String evaluateFourOfAKind(short[] rankCounter){
String result = "";
for (int i=0;i<rankCounter.length;i++){
if (rankCounter[i] == FOUR){
result = "Four of a Kind, " + Card.rankAsString(i) +"'s";
break;
}
}
return result;
}
// Full house is having 3 of a kind of one rank, and two of a kind of
// a second rank. EX: J-J-J-3-3
private String evaluateFullHouse(short[] rankCounter){
String result = "";
short threeOfKindRank = -1;
short twoOfKindRank = -1;
for (int i=rankCounter.length;i>0;i--){
if ((threeOfKindRank < (short)0) || (twoOfKindRank < (short)0)){
if ((rankCounter[i-ONE]) > 2){
threeOfKindRank = (short) (i-ONE);
}
else if ((rankCounter[i-ONE]) > 1){
twoOfKindRank = (short)(i-ONE);
}
}
else
{
break;
}
}
if ((threeOfKindRank >= (short)0) && (twoOfKindRank >= (short)0)){
result = "Full House: " + Card.rankAsString(threeOfKindRank) + "'s full of " + Card.rankAsString(twoOfKindRank) + "'s";
}
return result;
}
// Flush is 5 cards of the same suit.
private String evaluateFlush(short[] rankCounter, short[] suitCounter){
String result = "";
// verify at least 1 suit has 5 cards or more.
if (suitCounter[0] > 4 || suitCounter[1] > 4 ||
suitCounter[2] > 4 || suitCounter[3] > 4){
for (int i=availableCards.length-1;i>3;i--){
if (availableCards[i].getSuit() == availableCards[i-ONE].getSuit() &&
availableCards[i].getSuit() == availableCards[i-TWO].getSuit() &&
availableCards[i].getSuit() == availableCards[i-THREE].getSuit() &&
availableCards[i].getSuit() == availableCards[i-FOUR].getSuit()){
// Found royal flush, break and return.
result = "Flush!! " + Card.rankAsString(availableCards[i].getRank()) + " high of " + Card.suitAsString(availableCards[i].getSuit());
break;
}
}
}
return result;
}
// Straight is 5 consecutive cards, regardless of suit.
private String evaluateStraight(short[] rankCounter){
String result = "";
// loop through rank array to check for 5 consecutive
// index with a value greater than zero
for (int i=rankCounter.length;i>4;i--){
if ((rankCounter[i-1] > 0) &&
(rankCounter[i-2] > 0) &&
(rankCounter[i-3] > 0) &&
(rankCounter[i-4] > 0) &&
(rankCounter[i-5] > 0)){
result = "Straight " + Card.rankAsString(i-1) + " high";
break;
}
}
return result;
}
// Three of a kind is 3 cards of the same rank.
private String evaluateThreeOfAKind(short[] rankCounter){
String result = "";
// loop through rank array to check for 5 consecutive
// index with a value greater than zero
for (int i=rankCounter.length;i>0;i--){
if (rankCounter[i-1] > 2){
result = "Three of a Kind " + Card.rankAsString(i-1) + "'s";
break;
}
}
return result;
}
// Two pair is having 2 cards of the same rank, and two
// different cards of the same rank. EX: 3-3-7-7-A
private String evaluateTwoPair(short[] rankCounter){
String result = "";
short firstPairRank = -1;
short secondPairRank = -1;
for (int i=rankCounter.length;i>0;i--){
if ((firstPairRank < (short)0) || (secondPairRank < (short)0)){
if (((rankCounter[i-ONE]) > 1) && (firstPairRank < (short)0)){
firstPairRank = (short) (i-ONE);
}
else if ((rankCounter[i-ONE]) > 1){
secondPairRank = (short)(i-ONE);
}
}
else
{
// two pair found, break loop.
break;
}
}
// populate output
if ((firstPairRank >= (short)0) && (secondPairRank >= (short)0)){
if (secondPairRank == (short)0){
// Aces serve as top rank but are at the bottom of the rank array
// swap places so aces show first as highest pair
result = "Two Pair: " + Card.rankAsString(secondPairRank) + "'s and " + Card.rankAsString(firstPairRank) + "'s";
}
else
{
result = "Two Pair: " + Card.rankAsString(firstPairRank) + "'s and " + Card.rankAsString(secondPairRank) + "'s";
}
}
return result;
}
// One is is two cards of the same rank.
private String evaluateOnePair(short[] rankCounter){
String result = "";
for (int i=rankCounter.length;i>0;i--){
if((rankCounter[i-ONE]) > 1){
result = "One Pair: " + Card.rankAsString(i-ONE) + "'s";
break;
}
}
return result;
}
// high card is the highest card out of the 7 possible cards to be used.
private String evaluateHighCard(short[] rankCounter){
String result = "";
for (int i=rankCounter.length;i>0;i--){
if((rankCounter[i-ONE]) > 0){
result = "High Card: " + Card.rankAsString(i-ONE);
break;
}
}
return result;
}
}
</code></pre>
<p><a href="http://pastebin.com/fC7wwMcd" rel="nofollow noreferrer">Deck.java</a> </p>
<pre><code>import java.util.Random;
public class Deck{
private Card[] cards = new Card[52];
//Constructor
public Deck(){
int i = 0;
for (short j=0; j<4; j++){
for (short k=0; k<13;k++){
cards[i++] = new Card(k, j);
}
}
}
// Print entire deck in order
protected void printDeck(){
for(int i=0; i<cards.length;i++){
System.out.println(i+1 + ": " + cards[i].printCard());
}
System.out.println("\n");
}
// Find card in deck in a linear fashion
// Use this method if deck is shuffled/random
protected int findCard(Card card){
for (int i=0;i<52;i++){
if (Card.sameCard(cards[i], card)){
return i;
}
}
return -1;
}
//return specified card from deck
protected Card getCard(int cardNum){
return cards[cardNum];
}
protected void shuffle(){
int length = cards.length;
Random random = new Random();
//random.nextInt();
for (int i=0;i<length;i++){
int change = i + random.nextInt(length-i);
swapCards(i, change);
}
}
protected void cutDeck(){
Deck tempDeck = new Deck();
Random random = new Random();
int cutNum = random.nextInt(52);
for (int i=0;i<cutNum;i++){
tempDeck.cards[i] = this.cards[52-cutNum+i];
}
for (int j=0;j<52-cutNum;j++){
tempDeck.cards[j+cutNum] = this.cards[j];
}
this.cards = tempDeck.cards;
}
// Swap cards in array to 'shuffle' the deck.
private void swapCards(int i, int change){
Card temp = cards[i];
cards[i] = cards[change];
cards[change] = temp;
}
}
</code></pre>
<p><a href="http://pastebin.com/a8P7jweg" rel="nofollow noreferrer">Card.java</a> </p>
<pre><code>import java.util.*;
public class Card{
private short rank, suit;
private static String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
private static String[] suits = {"Diamonds", "Clubs", "Hearts", "Spades"};
//Constructor
public Card(short rank, short suit){
this.rank = rank;
this.suit = suit;
}
// Getter and Setters
public short getSuit(){
return suit;
}
public short getRank(){
return rank;
}
protected void setSuit(short suit){
this.suit = suit;
}
protected void setRank(short rank){
this.rank = rank;
}
// methods
public static String rankAsString(int __rank){
return ranks[__rank];
}
public static String suitAsString(int __suit){
return suits[__suit];
}
public @Override String toString(){
return rank + " of " + suit;
}
// Print card to string
protected String printCard(){
return ranks[rank] + " of " + suits[suit];
}
// Determine if two cards are the same (Ace of Diamonds == Ace of Diamonds)
public static boolean sameCard(Card card1, Card card2){
return (card1.rank == card2.rank && card1.suit == card2.suit);
}
}
class rankComparator implements Comparator<Object>{
public int compare(Object card1, Object card2) throws ClassCastException{
// verify two Card objects are passed in
if (!((card1 instanceof Card) && (card2 instanceof Card))){
throw new ClassCastException("A Card object was expeected. Parameter 1 class: " + card1.getClass()
+ " Parameter 2 class: " + card2.getClass());
}
short rank1 = ((Card)card1).getRank();
short rank2 = ((Card)card2).getRank();
return rank1 - rank2;
}
}
class suitComparator implements Comparator<Object>{
public int compare(Object card1, Object card2) throws ClassCastException{
// verify two Card objects are passed in
if (!((card1 instanceof Card) && (card2 instanceof Card))){
throw new ClassCastException("A Card object was expeected. Parameter 1 class: " + card1.getClass()
+ " Parameter 2 class: " + card2.getClass());
}
short suit1 = ((Card)card1).getSuit();
short suit2 = ((Card)card2).getSuit();
return suit1 - suit2;
}
}
</code></pre>
<p><a href="http://pastebin.com/Rh7wH8Ea" rel="nofollow noreferrer">Board.java</a> </p>
<pre><code>public class Board {
private Card[] board = new Card[5];
private Card[] burnCards = new Card[3];
//constructor
public Board(){
}
//methods
protected void setBoardCard(Card card, int cardNum){
this.board[cardNum] = card;
}
protected Card getBoardCard(int cardNum){
return this.board[cardNum];
}
protected void setBurnCard(Card card, int cardNum){
this.burnCards[cardNum] = card;
}
protected Card getBurnCard(int cardNum){
return this.burnCards[cardNum];
}
protected int boardSize(){
return board.length;
}
protected void printBoard(){
System.out.println("The board contains the following cards:");
for(int i =0; i<board.length;i++){
System.out.println(i+1 + ": " + getBoardCard(i).printCard());
}
System.out.println("\n");
}
protected void printBurnCards(){
System.out.println("The burn cards are:");
for(int i =0; i<burnCards.length;i++){
System.out.println(i+1 + ": " + getBurnCard(i).printCard());
}
System.out.println("\n");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T13:54:07.423",
"Id": "2411",
"Score": "1",
"body": "Please include the main part of the code that you want reviewed in the post as per the FAQ. Thanks"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T14:18:01.940",
"Id": "2412",
"Score": "0",
"body": "@Mark Loeser: Ok, I really want the whole program looked at, the post will be extremely lengthy so I thought posting the code to pastebin would have been a better route. I'll modify my post."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T14:42:45.497",
"Id": "2494",
"Score": "1",
"body": "BTW, I don't want to dissuade you to learn Java, but if your Hold'em example is a typical example for the kind of programming you plan to do, then you may be interested in a functional language. Take for example Scala, which basically is Java with functional features."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T16:22:56.707",
"Id": "2500",
"Score": "0",
"body": "@RoToRa: I want to learn java, I just couldn't think of a program to write to learn it. Doing tutorials from the internet gets old quick and didn't allow me to solve problems at the level I was interested in. My past experience is in C so that's probably why I wrote the program the way I did. I also wanted to have some code samples so when I interview I'll have something to show them because I won't have any on-the-job experience in the language yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T11:41:57.640",
"Id": "32977",
"Score": "0",
"body": "Poker is notoriously difficult to use with OOP. Blackjack works better with it. Also [this tutorial site](http://math.hws.edu/javanotes/) has a number of exercises for Java that are around the level of Poker as well as exercises that are the building blocks of the more complex exercises. You will also learn GUIs, IO, Threads, ADTs, and Generics, which are IMHO at a higher level than Poker. I think tis pretty good stuff :)"
}
] | [
{
"body": "<p>Let's start with the most basic, the <code>Card</code> class.</p>\n\n<blockquote>\n<pre><code>import java.util.*;\n</code></pre>\n</blockquote>\n\n<p>Except during development, it's custom to explicitly import only the classes you need instead of using wildcards.</p>\n\n<blockquote>\n<pre><code>public class Card{\n private short rank, suit;\n</code></pre>\n</blockquote>\n\n<p>It's is most certainly a valid choice to store rank and suit as <code>short</code>s, since it's most likely the fastest and most efficient way, but if you want to learn the specifics of Java you may want to look into enumerations.</p>\n\n<blockquote>\n<pre><code>protected void setSuit(short suit){\n this.suit = suit;\n}\n\nprotected void setRank(short rank){\n this.rank = rank;\n}\n</code></pre>\n</blockquote>\n\n<p>IMHO cards are a prime example for immutable objects. There is no reason to need to change the rank or the suit of a card, so I would drop the setters.</p>\n\n<blockquote>\n<pre><code>public static String rankAsString(int __rank){\n return ranks[__rank];\n}\n\npublic static String suitAsString(int __suit){\n return suits[__suit];\n}\n</code></pre>\n</blockquote>\n\n<p>It's very unusual to use underlines in variable names in Java, especially two as a prefix. I would simple name the parameters <code>rank</code> and <code>suit</code> especially since these are class (static) methods and not instance methods, so there is no confusion with the fields.</p>\n\n<p>It may be worth thinking about, if these actually need to be class methods and shouldn't be instance methods. If you have other classes which need to convert <code>short</code> into the corresponding names independently from the <code>Card</code> class, then it would be ok. But in your case I would say it's not the case, and one should try and hide the fact that suits and ranks are implemented as <code>short</code>s as much as possible.</p>\n\n<blockquote>\n<pre><code>public @Override String toString(){\n return rank + \" of \" + suit;\n}\n\n// Print card to string\nprotected String printCard(){\n return ranks[rank] + \" of \" + suits[suit];\n}\n</code></pre>\n</blockquote>\n\n<p>The Java community is split over the question, if the <code>toString()</code> method should be overridden purely for debugging reasons, or if it should be used in the \"business logic\". In this \"simple\" application I don't think you need to distinguish between the two uses, so I would drop <code>printCard()</code> and only use <code>toString()</code>.</p>\n\n<p>BTW, it's custom to have annotations before the method modifiers.</p>\n\n<blockquote>\n<pre><code>public static boolean sameCard(Card card1, Card card2){\n return (card1.rank == card2.rank && card1.suit == card2.suit);\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of implementing your own method it's probably a good idea to override <code>equals()</code> (or at least make this an instance method). If you make <code>Card</code> immutable as I suggested before, it simplifies the implementation to comparing the references, to see if they are the same, because you should only have one instance of each possible card. </p>\n\n<pre><code>@Override public boolean equals(Object that) {\n return this == that;\n}\n</code></pre>\n\n<p>(Although it may be safer to compare rank and suit as a fall back.)</p>\n\n<hr>\n\n<p><strong>EDIT 1:</strong></p>\n\n<p>First a quick digression about Enumerations. The Enums have an ordinal number and a <code>compareTo</code> method, allowing you to sort them. You also can assign them properties and create your own order based on those.</p>\n\n<p>The offical language guide has examples for suit and rank enumations and for extending enumerations with your own properties using planets as an example: <a href=\"http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html\">http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html</a></p>\n\n<p>When/if I get to the hand ranking (I haven't looked at it yet) I may be able to give some suggestions have to implement it with enums.</p>\n\n<hr>\n\n<p>Next are the <code>Comparator</code>s. I don't have much experience with them, so I can only give some general suggestions:</p>\n\n<ul>\n<li>Classes should always start with a capital letter in Java.</li>\n<li>You should extend them from <code>Comparator<Card></code> instead of <code>Comparator<Object></code>, since you only need to compare cards with each other and not with any other objects.</li>\n<li>While it is good extra practice, you may want to skip the suit comparator, because it's not really needed in Poker in general (and Texas Hold'em specifically). Suits never have an order in hand ranking usually only needed in some \"meta\" contexts (such as randomly determinating the position of the button), that currently don't apply to your program. However if you do keep it, then you should correct the order of the suits, because the official ranking is (from lowest to highest) \"Clubs\", \"Diamonds\", \"Hearts\" and \"Spades\".</li>\n</ul>\n\n<hr>\n\n<p>Next up, is the Board. First off, I'd like to say, that I'm nor sure if I'd use a Board class like this in a real world Poker application. However off the top of my head I can't think of a different way to do it and for practice this is perfectly fine.</p>\n\n<p>The only thing I would change is instead of explicitly setting each card by index with <code>setBoardCard(Card card, int cardNum)</code>, I would let the Board class track the index internally itself and just use <code>addBoardCard(Card card)</code>, because you shouldn't be able to \"go back\" and change the board cards (ditto for the burn cards). </p>\n\n<hr>\n\n<p><strong>EDIT 2:</strong></p>\n\n<p>Regarding sorting suits: Ok, that makes sense. I haven't looked at hand evaluation yet. However that is more a case of grouping that sorting, so maybe there is a different (better?) way to do that. I'll have to think about it.</p>\n\n<hr>\n\n<p>Tracking indexes: You certainly could use a <code>Collection</code> (or more specifically a <code>List</code>) to do this (and it would be more \"Java-like\", but in your case where you have a fixed maximum number of cards on the board the arrays are fine. I'd something like:</p>\n\n<pre><code>public class Board { //abbreviated\n\n private Card[] board = new Card[5];\n private Card[] burnCards = new Card[3];\n\n private int boardIndex = 0;\n private int burnCardIndex = 0;\n\n //methods\n protected void addBoardCard(Card card){\n this.board[boardIndex++] = card;\n }\n\n protected void addBurnCard(Card card){\n this.burnCards[burnCardIndex++] = card;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Next is <code>Deck</code>: </p>\n\n<p>First I'd suggest to create just one <code>Random</code> object statically instead of creating one for each call of <code>shuffle</code> and <code>cutDeck</code>.</p>\n\n<p>Really problematic is the creation of a new temporary <code>Deck</code> object for cutting the deck. This can go wrong very fast, because it contains an unnecessary second set of cards and if there is a bug you'll easily get duplicate cards. Instead just use a new array. Also you can use <a href=\"http://download.oracle.com/javase/6/docs/api/java/lang/System.html\">System.arraycopy</a> to simplify copying from one array to another.</p>\n\n<p><strong>EDIT 3</strong>:</p>\n\n<p>Creating a new <code>Deck</code> doesn't only create a new array, it creates a a <strong>filled</strong> array with new cards, which you don't need. Just an array is enough: </p>\n\n<pre><code>protected void cutDeck(){\n Card[] temp = new Card[52];\n Random random = new Random();\n int cutNum = random.nextInt(52);\n\n System.arraycopy(this.cards, 0, temp, 52-cutNum, cutNum);\n System.arraycopy(this.cards, cutNum, temp, 0, 52-cutNum);\n\n this.cards = temp;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT 4:</strong></p>\n\n<p>There is not much to say about <code>Player</code> except, I'd remove <code>setCard</code> and just use the constructor to assign the cards to the player in order to make the object immutable. Or at least implement an <code>addCard</code> method just like in <code>Board</code>.</p>\n\n<hr>\n\n<p>The main class:</p>\n\n<p>In <code>getNumberOfPlayers</code> your error handling it some what inconsistent. On the one hand you write to <code>System.out</code> (<code>System.err</code>would probably be better) and on the other hand you throw an exception.</p>\n\n<p>For the <code>IOException</code> I wouldn't catch it here, but outside of <code>getNumberOfPlayers</code>. In bigger projects it may make sense to \"wrap\" it in your own Exception class for this:</p>\n\n<pre><code>try { \n userInput = br.readLine(); \n} catch (IOException ioe) { \n throw new HoldemIOException(ioe);\n}\n</code></pre>\n\n<p>Both the caught <code>NumberFormatException</code> and invalid range should throw the same (or related) custom exceptions. Don't just throw a simple <code>Exception</code>, because it's meaningless to others that need to catch it. Example:</p>\n\n<pre><code>try {\n intPlayers = Integer.parseInt(userInput);\n} catch (NumberFormatException nfe) {\n throw new HoldemUserException(\"Error: Not an integer entered for number of players\", nfe);\n}\n\nif ((intPlayers<1) || (intPlayers>9)){\n throw new HoldemUserException(\"Error: Number of players must be an integer between 1 and 9\");\n}\n</code></pre>\n\n<p>Notice that in the causing <code>IOException</code> and <code>NumberFormatException</code>, are passed as an argument to the new exception in case they are needed further down the line.</p>\n\n<p>Both the <code>HoldemIOException</code> and <code>HoldemUserException</code> could be extended from a basic <code>HoldemException</code> which in turn extends <code>Exception</code>. A simple \"empty\" extention such as</p>\n\n<pre><code>class HoldemException extends Exception {}\n</code></pre>\n\n<p>for all three cases would be enough.</p>\n\n<p>Also you never should let an exception (especially a self thrown one) just drop out at the end completely unhandled. Catch all exceptions you know of at a reasonable place, in your case at the <code>getNumberOfPlayers</code>:</p>\n\n<pre><code>do {\n try {\n numPlayers = getNumberOfPlayers();\n } catch (HoldemUserException e) {\n System.out.println(e.getMessage());\n // \"Only\" a user error, keep trying\n } catch (HoldemIOException e) {\n System.err.println(\"Error: IO error trying to read input!\"); \n System.exit(1); \n }\n} while (numPlayers = 0);\n</code></pre>\n\n<p>I only added the <code>do while</code> loop, to show how to handle the two types of exception differently. It would be wise to add a proper way for the user to get out of the loop.</p>\n\n<hr>\n\n<p>Dealing the cards:</p>\n\n<p>Here we have another counter (<code>cardCounter</code>) to track to \"position\" of the deck. Again it would be better to have the <code>Deck</code> class track the dealt cards. You should consider implementing the Deck as an actual <a href=\"http://en.wikipedia.org/wiki/Stack_%28data_structure%29\">\"stack\"</a> or a <a href=\"http://en.wikipedia.org/wiki/Queue_%28data_structure%29\">\"queue\"</a> - it doesn't matter which, since you aren't adding any items. Java provides a <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/Queue.html\"><code>Queue</code></a> interface you could use.</p>\n\n<p>Thinking about it, you could also use the same interface for <code>Player</code> and <code>Board</code> (although you'd need to separate the burn cards into its own object in that case). That would simplify dealing to <code>player.add(deck.remove());</code>, <code>board.add(deck.remove());</code> and <code>burnCards.add(deck.remove())</code>.</p>\n\n<hr>\n\n<p><strong>EDIT 5:</strong></p>\n\n<p>Ok, most likely the final edit.</p>\n\n<p>I've started looking at the hand evaluation and I don't think I can write much about that. You've implemented it in a very procedural way based on your current Card objects and if your goal is to do this in a more Java way you'd probably need to re-write the Card object and create a proper \"Hand\" object first (most likely based on a <code>Set</code>) and then re-write the evaluation based on that.</p>\n\n<p>Poker hand evaluation is a very complex topic, especially when considering 5 cards out of 7. How this should be implemented will depend on if you want to focus on \"good Java practice\" or \"speed\". If you really interested in expanding this, then you probably should first read up on the topic - there are several questions on Stack Overflow about this, and probably countless articles on the web - and then repost a new question focusing on hand evaluation. I'll be happy to have a look at that some day - if I have the time.</p>\n\n<p>Just one specific thing: What are the constants ONE, TWO, THREE and FOUR for? Even for a procedural approach these seem to be completely out of place and should most likely be replaced by an appropriate loop where they are used.</p>\n\n<hr>\n\n<p>Finally, have fun and good luck on your further adventures in Java land!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T22:00:13.227",
"Id": "2421",
"Score": "0",
"body": "@RoToRa: Thanks, I'll try to post my responses as individual comments. RE: import I changed the java.util.* to java.util.Comparator"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T22:02:41.837",
"Id": "2422",
"Score": "0",
"body": "RE Enumeration: I originally did have the ranks and suits as enums, but when I started to think through how I would need to sort my cards by rank and suit I switched them to `short`'s I didnt know if the `enum` would cause sorting problems for the `HandEval.class`, but I knew for certain `short`'s would work and I didnt want to get so far along that it would take a significant amount of refactoring if I had to switch it later."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:12:09.910",
"Id": "2436",
"Score": "0",
"body": "RE: Sorting by suit. I found I needed a Comparator for both suit and rank because of Royal & Straight Flushes. For example if I had 7h-8h-8s-9h-9c-10h-Jh. I needed a way to sort these so I could check for a sequential 7 8 9 10 J of hearts, if I sorted by rank alone the evaluation would fail. One suit doesn't hold a higher precedence over another, just makes evalaution easier."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:13:08.393",
"Id": "2437",
"Score": "0",
"body": "Re Tracking indexes internally - do you have a standard way you do this? Is it will Collection<List>'s? I'd be interested in reading on if it you have a resource or a standard way you do that. Thanks again."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T13:58:54.130",
"Id": "2491",
"Score": "0",
"body": "Re: Internal indexing, I really like that idea. I'll try to implement that today, and use a unified Random object for both the shuffle and cut deck. I dont understand what you mean by just create another array for the cutDeck, creating a temp deck does create another array to use... ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T23:43:58.687",
"Id": "2509",
"Score": "0",
"body": "Re: cutDeck - That's why I love code reviews! I didn’t know this functionality even exists, but its exactly what I needed and much simpler. I got the cutDeck implemented and the internal index tracking today. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T00:51:35.417",
"Id": "2564",
"Score": "0",
"body": "Re: Exceptions - This is an area I have little to no exposure to yet (in fact Im reading the Oracle tutorial now to implement this correctly), what you see is stuff I managed to find on the internet and it sort of worked so I left it in there. But currently I dont know what I Would put into a HoldemException class to make it function correctly. This may take me a day or two to fully understand."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T20:38:12.537",
"Id": "2608",
"Score": "0",
"body": "Thanks for taking the time to review this code. Very helpful and got me pointed in better directions for my Java."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T17:08:19.827",
"Id": "1390",
"ParentId": "1382",
"Score": "38"
}
},
{
"body": "<p>Consider separating the TexasHoldem class with all its logic (amount of players, counters, ...) from how you initialize it.</p>\n\n<p>Your main would go in a <code>TexasHoldemProgram</code> class, which instantiates a <code>TexasHoldem</code> class, and sets e.g. the amount of players as input in main.</p>\n\n<p>This practice is called the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">Model View Controller</a> pattern. By separating the logic of the game from the interaction with it, you can later reuse the class with an entirely different GUI. You should probably apply this in other parts of the code as well, but I didn't look thoroughly through it all yet.</p>\n\n<p>The rest of your implementation looks pretty well structured, but I might update this answer if I find other things worth mentioning which aren't mentioned in the other answers. Good luck exploring Java!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T20:19:55.973",
"Id": "2462",
"Score": "0",
"body": "I sort of understand a MVC from a 60,000 ft level, but I'm not sure I understand how I would implement it here. Would I create another class who's sole purpose would be to create a TexasHoldem object? I'm actually very interested if you could explain this, once I get the logic part down I do want to implement a user interface for this program. So any groundwork I can lay now that will make it easier for me later would be appreciated."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T20:45:39.450",
"Id": "2464",
"Score": "0",
"body": "I notice from your code you do understand how to separate your code. MVC just goes a step further and separates model from the view from the 'controller'. I could write a broad answer here, but others have already done it before me (and better I might add). I suggest you familiarize yourself with design patterns in general, as MVC is a compound pattern. I highly recommend [Head First Design Patterns](http://oreilly.com/catalog/9780596007126). It's a really entertaining and useful read. If you already know the Strategy and Observer pattern, you can dive into MVC directly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:45:43.340",
"Id": "1408",
"ParentId": "1382",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1390",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T13:26:16.540",
"Id": "1382",
"Score": "24",
"Tags": [
"java",
"beginner",
"game",
"playing-cards"
],
"Title": "Texas Hold'em in Java"
} | 1382 |
<p>I wrote a simple PHP script which allows the user to upload a file to the server. It works, but I'm not very sure about security. Could you give me some hints about security mistakes?</p>
<p>In a nutshell: The user uploads a file from form.html, then a file is saved in uploads/ directory on the server, and a direct link to it is recorded in a database. Then that link is presented to the user, so he/she is able to download the file. The execution of that file is forbidden using .htaccess.</p>
<p><strong>form.html</strong></p>
<pre><code><div id="quickFileSubmit" style="margin-left: 20px; display: none">
<table>
<tr>
<td>
<form enctype="multipart/form-data" class="smallForm"
action="action.php?act=quickFileSubmit" method="post"
style="margin-top: 5px;">
<label style="font-size: 12px;">File:</label>
<input type="file" name="uploadfile" readonly="true" size="30"/>
<input type="submit" value="Submit" />
</form>
</td>
<td style="width: 100%;"></td>
</tr>
</table>
</div>
</code></pre>
<p><strong>action.php</strong></p>
<pre><code>//some actions
else if ($_REQUEST["act"] == "quickFileSubmit") {
$basename = getUploadBasename();
uploadFile();
header("location:index.php");
}
function uploadFile() {
if (strlen($_FILES['uploadfile']["name"]) > 0) {
$target_path = "uploads/";
$basename = basename( $_FILES['uploadfile']['name']);
$target_path = $target_path . $basename;
if (encode($basename) == $basename) {
if(move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target_path)) {
// here goes saving of file info
return $basename;
} else{
// upload failed.
echo "File upload failed.";
return null;
}
} else {
echo "Illegal characters in file name.";
return null;
}
}
}
</code></pre>
<p>Also, I have put .htaccess in the uploads dir:</p>
<p><strong>.htaccess</strong></p>
<pre><code>SetHandler default-handler
Options -Indexes
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T14:15:55.740",
"Id": "2528",
"Score": "1",
"body": "Most php functions return a sensible response or FALSE. I suggest you return FALSE instead of NULL."
}
] | [
{
"body": "<p>One thing that immediately stands out to me is whether <code>$_FILES['uploadfile']</code> actually exists for each upload request. Do an <code>isset</code> on it first to make sure a client doesn't send a post with fabricated input values - for example: some custom html form of their own making. If they do, you'll get 'function expects some value, boolean/null given' errors all over the place as is.</p>\n\n<p>Or better yet, to allow client flexibility if they choose to use some sort of API for your website, just cycle through <code>$_FILES</code> array to work on whatever files they submit to this script. Your choice though if you want to instead maintain strict input, but it wouldn't matter really as long as your script receives the file input of a field named \"uploadfile\" from any source.</p>\n\n<p>Also, for <code>$_FILES[$x][\"name\"]</code>, validate or sanitize it to ensure it contains only alphanumeric, underscore, dash, and dot characters. Yes OS's can work with more characters than that, but not every protocol or application can (text, browsers or email editors breaking long filenames or links on spaces, etc).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T02:44:58.700",
"Id": "1418",
"ParentId": "1384",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>It works, but I'm not very sure about security. Could you give me some hints about security mistakes?</p>\n</blockquote>\n\n<p>This is not the correct approach to security, as an attacker can easily gain code execution:</p>\n\n<ul>\n<li>An attacker can upload a .htaccess file, overwriting your .htaccess file that is supposed to prevent execution, thus gaining code execution.</li>\n<li><code>SetHandler default-handler</code> does not prevent code execution (at least not with my setup). </li>\n<li>Not all servers are configured to parse htaccess files (for performance and security reasons). PHP code should be secure under all - or at least all common - server configurations.</li>\n</ul>\n\n<p>What you should do is check the file extension as well as the actual file type. The functions that are generally recommended for this are <code>pathinfo</code> and <code>finfo_file</code> respectively. Ideally, you should use whitelists, not blacklists.</p>\n\n<p>It is a good idea to additionally forbid execution inside the upload directory, ideally by using server configuration as well as OS configuration, but this should not be your only line of defense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-04T19:04:25.980",
"Id": "99042",
"ParentId": "1384",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1418",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T15:25:48.460",
"Id": "1384",
"Score": "5",
"Tags": [
"php",
"security",
"network-file-transfer"
],
"Title": "Uploading a file to the server"
} | 1384 |
<p>Just as the question states and to be sure, am I missing anything on this? Something important/obvious that I overlooked? As is, I can save any functor, function pointer and member function pointer using this delegate class (copy ctor and assignment operator left out for brevity, as were the versions with parameters).</p>
<pre><code>template<class Type>
void Deleter(void* object){
Type* obj_ptr = static_cast<Type*>(object);
delete obj_ptr;
}
template<class Functor>
struct DelegateHelper{
typedef typename Functor::result_type result_type;
DelegateHelper(Functor func)
: func_(func)
{}
result_type operator()(){
return func_();
}
Functor func_;
};
template<class Obj, class R>
struct DelegateHelper<R (Obj::*)()>{
typedef R (Obj::*FuncPtr)();
DelegateHelper(Obj* obj_ptr, FuncPtr func)
: object_(obj_ptr)
, func_(func)
{}
R operator()(){
return (object_->*func_)();
}
Obj* object_;
FuncPtr func_;
};
template<class R>
struct DelegateHelper<R (*)()>{
typedef R (*FuncPtr)();
DelegateHelper(FuncPtr func)
: func_(func)
{}
R operator()(){
return (*func_)();
}
FuncPtr func_;
};
template<class Sig>
struct Delegate;
template<class R>
struct Delegate<R ()>{
typedef R (*SinkPtr)(void*);
Delegate()
: object_(0)
, func_(0)
, deleter_(0)
{}
template<class F>
Delegate(F func)
: object_(new DelegateHelper<F>(func))
, func_(&Sink<DelegateHelper<F> >)
, deleter_(&Deleter<DelegateHelper<F> >)
{}
template<class C, class F>
Delegate(C* obj, F func)
: object_(new DelegateHelper<F>(obj, func))
, func_(&Sink<DelegateHelper<F> >)
, deleter_(&Deleter<DelegateHelper<F> >)
{}
~Delegate(){
if(deleter_)
(*deleter_)(object_);
}
R operator()(){
return (*func_)(object_);
}
template<class Type>
static R Sink(void* obj_ptr){
Type* object = (Type*)obj_ptr;
return (*object)();
}
typedef void (*DeleteFunc)(void*);
void* object_;
SinkPtr func_;
DeleteFunc deleter_;
};
</code></pre>
<p>For the delegate in effect, <a href="http://ideone.com/PSi9j" rel="nofollow">see here on Ideone</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T22:43:14.233",
"Id": "2423",
"Score": "0",
"body": "Have you looked at 'Fastest possible delegates' in codeproject? It's just so you're not reinventing the wheel."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T23:23:42.377",
"Id": "2424",
"Score": "0",
"body": "@Victor: I did, and also at the 'Impossibly fast delegates' and actually stole the idea of void pointers and type erasure using function pointers and templates from the second one, but they all seem so bloated and big, like Boost.Function, which is just *huge*, and that's one reason why I asked, because this implementation is actually so small that it just got me wondering. It seems that I *must* have missed something."
}
] | [
{
"body": "<p>You are missing const and volatile qualified method pointer versions.</p>\n\n<p>Example:</p>\n\n<pre><code>template<class Obj, class R>\nstruct DelegateHelper<R (Obj::*)() const>{\n typedef R (Obj::*FuncPtr)() const;\n\n DelegateHelper(const Obj* obj_ptr, FuncPtr func)\n : object_(obj_ptr)\n , func_(func)\n {}\n\n R operator()(){\n return (object_->*func_)();\n }\n\n const Obj* object_;\n FuncPtr func_;\n};\n</code></pre>\n\n<p>Also, you may (probably) need specializations or internal delegates for handling of functions with void return values. Someone else may be able to fill in the details, but it seems some compilers are OK with</p>\n\n<pre><code>return function_returning_void();\n</code></pre>\n\n<p>And others are not.</p>\n\n<p>Another thing that makes the boost version and some others larger is being able to accept & or * arguments for the object value when calling methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T04:54:52.297",
"Id": "1570",
"ParentId": "1388",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-22T16:50:15.437",
"Id": "1388",
"Score": "4",
"Tags": [
"c++",
"delegates"
],
"Title": "Anything I'm missing on this delegate implementation?"
} | 1388 |
<p>Inside of a folder named <code>txt</code> I have 138 text files (totaling 349MB) full of email addresses. I have no idea (yet) how many addresses there are. They are separated from one another by line breaks. I created the following script to read all of these files into an array, dismiss the duplicates, then sort alphabetically and save in groups of 10K per csv file. It works correctly, but it has also been running for over 8 hours (dual core i3 w/ 4 gigabizzles of ram, sata 7200 hdd) which seems excessive to me. <code>Top</code> also tells me that my program's CPU usage is 100% and it's been like that the whole while it's been running. Give my script a looksie and advise me on where I've gone so terribly wrong.</p>
<pre><code>function writeFile($fileName, $fileData)
{
$writeFileOpen = fopen('csv/' . $fileName, 'w');
fwrite($writeFileOpen, $fileData) or die('Unable to write file: ' . $fileName);
fclose($writeFileOpen);
}
function openFiles()
{
$addressList = array();
$preventRepeat = array();
if ($handle = opendir('txt')) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$newList = explode("\n", trim(file_get_contents('txt/' . $file)));
foreach ($newList as $key => $val) {
$val = str_replace(array(',', '"'), '', $val);
if (in_array($val, $preventRepeat) || !strpos($val, '@') || !$val) {
unset($newList[$key]);
}
$preventRepeat[] = $val;
}
if (empty($addressList)) {
$addressList = $newList;
} else {
$addressList = array_merge($addressList, $newList);
}
unset($newList);
}
}
closedir($handle);
} else {
echo 'Unable to Read Directory';
}
$lineNum = 1;
$fileNum = 1;
$fileData = '"Email Address"' . "\n";
sort($addressList);
$lastKey = count($addressList) - 1;
foreach ($addressList as $key => $val) {
if ($lineNum > 10000) {
writeFile('emailList-' . $fileNum . '.csv', trim($fileData));
$lineNum = 1;
$fileNum++;
$fileData = '"Email Address"' . "\n";
} elseif ($key == $lastKey) {
writeFile('emailList-' . $fileNum . '.csv', trim($fileData));
echo 'Complete';
}
$fileData .= '"' . trim($val) . '"' . "\n";
$lineNum++;
}
}
openFiles();
</code></pre>
<p>PS. I wrote this script in haste to accomplish a task. I can understand if you wouldn't consider this script <em>distribution</em> worthy.</p>
<p>EDIT: So I arrived at work today to find my script at some point exceeded 536MB of memory and quit on fatal error. I had already increased my ini file's <code>memory_limit</code> parameter from 128MB to 512MB. This doesn't necessarily reflect an issue with the script itself. I just wanted to share my frustration with the task.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:28:16.157",
"Id": "2438",
"Score": "0",
"body": "You can probably make the script already twice as fast by utilizing both cores. Separate the processing across two processes, or use two threads. I find it strange that it indicates CPU usage of 100% at the moment. Shouldn't it just run on one core?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T14:18:22.840",
"Id": "2440",
"Score": "1",
"body": "PHP doesn't support multi-threading that I'm aware of. By 100% CPU usage, I'm guessing that it's taking up a whole core - not both. I'm able to run other processes without excessive clocking."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T14:42:19.000",
"Id": "2442",
"Score": "0",
"body": "Regarding to your edit: Don't you store all addresses twice? One in `$addressList` and once in `$preventRepeat`? Assuming all addresses are unique this would already take up 349MB * 2 of memory."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T20:46:57.550",
"Id": "2541",
"Score": "1",
"body": "How about a quick GNU sort: `time LC_ALL=C sort -u txt/* > email.sorted`. Bonus features: still fast if the files don't fit in ram (with in-memory compression and tempfiles), and multicore since 8.6."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T14:39:21.387",
"Id": "2552",
"Score": "0",
"body": "I just transitioned from Windows to Linux six (or so) months ago and am still getting acquainted with the ever-expansive bash and gnu tool set - will definitely check out sort's man page. What purpose does time serve in your example?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T13:13:38.840",
"Id": "2577",
"Score": "0",
"body": "`time` measures how long the rest of the command takes, and `LC_ALL=C` ignores your locale's sort order. Neither is necessary, but they make for a quick benchmark."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T03:16:00.627",
"Id": "2586",
"Score": "0",
"body": "That's definitely a simpler solution than what I originally came up with."
}
] | [
{
"body": "<p>It's been a long time since I've written PHP, but I think I can give you a few pointers anyhow.</p>\n\n<p>I believe the following line is problematic speed-wise:</p>\n\n<pre><code>if (in_array($val, $preventRepeat) || !strpos($val, '@') || !$val) {\n...\n</code></pre>\n\n<p>The <code>in_array</code> function does a sequential case sensitive lookup across all currently stored addresses. This call will become slower and slower the more addresses you store.</p>\n\n<p>The solution is to use <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">hash table</a> like lookup. I'm not entirely sure but I believe the PHP equivalent can be achieved by using the keys of the array instead of the values.</p>\n\n<pre><code>// Store a certain address.\n$addressList[$val] = true;\n</code></pre>\n\n<p>Checking whether a value is present for a given key indicates whether it has already been stored. Notice how <code>$preventRepeat</code> can be removed and everything is stored in <code>$addressList</code>. This removes the need of the <code>array_merge</code>, again resulting in more performance.</p>\n\n<p>Beware, this is speculation, so I'm hoping someone who is certain can verify this. :)</p>\n\n<p>Relating to my earlier comment:</p>\n\n<blockquote>\n <p>You can probably make the script\n already twice as fast by utilizing\n both cores. Separate the processing\n across two processes, or use two\n threads. I find it strange that it\n indicates CPU usage of 100% at the\n moment. Shouldn't it just run on one\n core?</p>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/209774/does-php-have-threading/209799#209799\">PHP doesn't seem to support multithreading</a>, so the only option would be to logically split the script to separate work into two different executions. If my previous comments don't improve the speed much, it's probably advisable to use a different language than PHP for these purposes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:01:26.440",
"Id": "2443",
"Score": "0",
"body": "Because I'm using PHP's `explode()` function to generate my arrays, I have no way to know or guarantee what position or key each specific value will take. Great point on having double sets of the same data, though. I removed my `$addressList` array and instead am storing those values in a temporary text file. I've also made sure to unset `$preventRepeat` before importing and array-ifying my temp file. I think my ultimate issue is that I'm trying to process way too much data at once (I'm guessing close to a billion addresses). I want them all in alphabetical order, though!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:16:33.887",
"Id": "2446",
"Score": "0",
"body": "PHP allows to use strings as keys in its [associative arrays](http://php.net/manual/en/language.types.array.php). What I intented with my answer is to store the addresses -so, `$val` in your code- as keys. Keys are unique, so you don't even have to check whether the key is already present, just set the value of the key to `true` or some other relevant value. Worry about sorting later. If I were you though, I would really prefer not processing a billion addresses in PHP."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:31:07.770",
"Id": "2449",
"Score": "0",
"body": "Ahh... so I should `if ($preventRepeat[$val]) { unset($newList[$key]); }` and then `$preventRepeat[$val] = TRUE;` instead of `in_array($val, $preventRepeat)` and `$preventRepeat[] = $val;`? That's brilliant!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:38:01.013",
"Id": "2450",
"Score": "0",
"body": "I believe `unset` isn't even required. I would just use one list of which you set the keys, and skip the merging. Be sure to try this out on just one small file before executing it on all of the entries. ;p"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:48:56.513",
"Id": "2452",
"Score": "1",
"body": "I'm picking up what you're putting down. Store all values in array as keys (which doubles as duplicate prevention), forget about making a temp file, and later reverse the keys out into array values for processing."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T16:08:00.027",
"Id": "2453",
"Score": "0",
"body": "Or use a sort on key. [ksort](http://php.net/manual/en/function.ksort.php) apparently."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T16:33:01.627",
"Id": "2456",
"Score": "0",
"body": "Thanks to your advice, my script works beautifully now. By comparison - extremely fast. Thank you so much."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T14:37:46.883",
"Id": "1410",
"ParentId": "1393",
"Score": "2"
}
},
{
"body": "<p>This will be much more efficient:</p>\n\n<pre><code>$result = array();\n\nif (($handle = opendir('./txt/')) !== false)\n{\n set_time_limit(0);\n ini_set('memory_limit', -1);\n\n while (($file = readdir($handle)) !== false)\n {\n if (($file != '.') && ($file != '..'))\n {\n if (is_resource($file = fopen('./txt/' . $file, 'rb')) === true)\n {\n while (($email = fgets($file)) !== false)\n {\n $email = trim(str_replace(array(',', '\"'), '', $email));\n\n if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false)\n {\n $result[strtolower($email)] = true;\n }\n }\n\n fclose($file);\n }\n }\n }\n\n closedir($handle);\n\n if (empty($result) !== true)\n {\n ksort($result);\n\n foreach (array_chunk($result, 10000, true) as $key => $value)\n {\n file_put_contents('./emailList-' . ($key + 1) . '.csv', implode(\"\\n\", array_keys($value)), LOCK_EX);\n }\n }\n\n echo 'Done!';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T20:14:38.587",
"Id": "2461",
"Score": "0",
"body": "+1 for using `filter_var()` (never occurred to me) - but why the identical comparison operator? Not-equal operators test against `bool` just fine without the extra overhead of type matching."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T01:08:40.490",
"Id": "2472",
"Score": "0",
"body": "@65Fbef05: Force of habit, ignore it. @Steven Jeuris: Thank you! =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T19:24:57.533",
"Id": "1414",
"ParentId": "1393",
"Score": "3"
}
},
{
"body": "<p>Definitely use the command line <code>sort</code> tool, and look in to <code>sed</code> and <code>grep</code> as well. You will find that it is generally easier to use fast, well-tested, pre-built Unix tools to perform any large text operations than to write a higher-level program to do the same.</p>\n\n<p>If you are just getting in to Unix, also check out:</p>\n\n<ul>\n<li>the <a href=\"http://www.imagemagick.org/\" rel=\"nofollow\">imagemagick</a> set of utilities which provide fantastic image processing</li>\n<li>the <code>file</code> tool (based on <code>libmagic</code>) which provides proper file type checking for uploaded files accepted from the public</li>\n</ul>\n\n<p>Also, just in case those emails are going to be used to distribute unsolicited information... don't spam people: it's bad karma.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-12T12:10:30.573",
"Id": "3129",
"Score": "0",
"body": "I appreciate the advice. I'm working my way through a LPIC-1 study guide in an attempt to quickly get a thorough overview (oxymoron, right?) of Linux features. Also, worry not about your e-mail inbox - I don't want to spam people. I won't go into detail, but I was using the addresses to \"test\" an account feature on a music/social networking site. This feature turned out to not be completely developed or broken. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-12T02:35:43.113",
"Id": "1799",
"ParentId": "1393",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1410",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-22T23:07:17.403",
"Id": "1393",
"Score": "4",
"Tags": [
"php",
"csv",
"parsing"
],
"Title": "73 Lines of Mayhem - Parse, Sort and Save to CSV in PHP CLI"
} | 1393 |
<p>I was trying to do a very common interview problem "Finding the max repeated word in a string " and could not find much resources in net for c/c++ implementation. So I coded it myself here. I have tried to do most of the coding from scratch for better understanding. Could you review my code and provide comments on my algorithm. Some people have suggested using hashtables for storing the count, but am not using hashtables here.</p>
<pre><code>#include<stdafx.h>
#include<stdlib.h>
#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
string word[10];
//splitting string into words
int parsestr(string str)
{
int index = 0;
int i = 0;
int maxlength = str.length();
int wordcnt = 0;
while(i < maxlength)
{
if(str[i] != ' ')
{
word[index] = word[index] + str[i];
}
else
{
index++; //new word
wordcnt = index;
}
i++;
}
return wordcnt;
}
//find the max word count out of the array and return the word corresponding to that index.
string maxrepeatedWord(int wordcntArr[],int count)
{
int max = 0;
int index = 0;
for(int i = 0; i <= count; i++)
{
if(wordcntArr[i] > max)
{
max = wordcntArr[i];
index = i;
}
}
return word[index];
}
void countwords(int count)
{
int wordcnt = 0;
int wordcntArr[10];
string maxrepeatedword;
for(int i = 0; i <= count; i++)
{
for(int j = 0; j <= count; j++)
{
if(word[i] == word[j])
{
wordcnt++;
//word[j] = "";
}
else
{}
}
cout << " word " << word[i] << " occurs " << wordcnt << " times " << endl;
wordcntArr[i] = wordcnt;
wordcnt = 0;
}
maxrepeatedword = maxrepeatedWord(wordcntArr,count);
cout << " Max Repeated Word is " << maxrepeatedword;
}
int main()
{
string str = "I am am am good good";
int wordcount = 0;
wordcount = parsestr(str);
countwords(wordcount);
}
</code></pre>
| [] | [
{
"body": "<p>Some general comments first:</p>\n\n<ol>\n<li><p>Comment, comment, comment. Although it seems pretty clear now, it doesn't hurt to make it really clear for the guy who has to maintain it when you've moved on.</p></li>\n<li><p>You might want to have separate functions for doing the counting of the words and for displaying the counts of the words.</p></li>\n</ol>\n\n<p>C++ Comments:</p>\n\n<ol start=\"3\">\n<li><p>You are using C++, so you might want to put this in a Class.</p></li>\n<li><p>The Standard Library is your friend. In particular, you might want to see if <a href=\"http://www.cplusplus.com/reference/stl/map/\" rel=\"nofollow noreferrer\"><code>std::map<...></code></a> could make your life a little easier when counting words.</p></li>\n<li><p>The use of <code>string word[10]</code> makes an assumption of how many different words there will be. It would be better to allow an arbitrary number of different words by using something like a <code>std::vector</code>. Alternatively, a different approach could be used (see #4).</p></li>\n<li><p><a href=\"http://www.cplusplus.com/reference/string/string/find/\" rel=\"nofollow noreferrer\"><code>string.find(..)</code></a> and <a href=\"http://www.cplusplus.com/reference/string/string/substr/\" rel=\"nofollow noreferrer\"><code>string.sub_string(..)</code></a> might prove helpful.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-23T17:57:38.183",
"Id": "1411",
"ParentId": "1394",
"Score": "2"
}
},
{
"body": "<p>Here's a long list of feedback. Sorry for the blunt tone, but I'm trying to be brief:</p>\n\n<ol>\n<li><p><code>parsestr</code> mutates a global variable but returns a value that's relevant to \nthat variable (the count). That's inconsistent. Either have it return both \nthe count and the array (or make things easier on yourself and use a \n<code>vector</code> that knows its size), or make the count global too.</p></li>\n<li><p>You don't handle punctuation characters. Is that a requirement? Should<br>\n\"a(b)\" be one word? Should \"a. a\" be two unique words?</p></li>\n<li><p>Do you need to split on characters other than space? What about <code>\\t</code> or \n<code>\\n</code>? Other Unicode whitespace characters?</p></li>\n<li><p>Your <code>while(i < maxlength)</code> loop could more simply be a <code>for</code> loop.</p></li>\n<li><p>Building up the word by incrementally contatenating characters onto a \n<code>string</code> is slow. It will periodically require dynamic allocation. A more \nefficient solution would be to remember the start index of the word. When \nyou reach the end, create a string from the substring <code>(start, end)</code> in one \nstep.</p>\n\n<p>Going further from there, there's no reason to even store those words\nseparately since that start, end pair is enough to reconstruct it as needed.</p></li>\n<li><p>Your program will mysteriously crash if you pass a sentence with more than\nten words. :( Since you're using dynamic allocation everywhere else (<code>string</code>\ndoes that under the hood) there's no reason to use a fixed array for words.\nAt the very least, you should have a constant for that size and check that\nyou don't overflow the array.</p></li>\n<li><p><code>index</code> isn't a helpful variable name. Call it <code>wordIndex</code>.</p></li>\n<li><p>Likewise, <code>wordcnt</code> would be better as <code>wordCount</code>.</p></li>\n<li><p><code>maxrepeatedWord</code> is a mixture of camelCase and all lowercase. Be consistent\n(and camelCase is generally better since it makes it easier for the reader\nto split it into words).</p></li>\n<li><p><code>wordcntArr</code> would be better as <code>wordCounts</code>. The fact that it's an array is\nself-evident.</p></li>\n<li><p><code>i <= count</code> should be just <code><</code>. Arrays are zero-based, so \n<code>wordcntArr[count]</code> is past the last valid element.</p></li>\n<li><p><code>index</code> -> <code>indexOfMax</code>.</p></li>\n<li><p>You're passing <code>count</code> into <code>countwords</code> even though that count is relevant \nto a global variable that it accesses directly. Why not just make the count \nglobal too?</p></li>\n<li><p>The <code>else {}</code> accomplishes nothing. Remove it.</p></li>\n<li><p>If you declare <code>wordcnt</code> inside the <code>for(int i...</code> loop, you won't have to\nreinitialize it each iteration.</p></li>\n<li><p><code>int wordcntArr[10]</code> again duplicates the magical literal <code>10</code>. Use a \nconstant or, better, a dynamically-sized container.</p></li>\n<li><p>You're redundantly recounting each word every time it occurs. With\n<code>\"I am am am good good\"</code>, you'll get a count array like <code>1 3 3 3 2 2</code>. \nIf you had a collection of <em>unique</em> words instead, your <span class=\"math-container\">\\$O(n^2)\\$</span> complexity\nwould go down to <span class=\"math-container\">\\$O(mn)\\$</span> where <span class=\"math-container\">\\$m\\$</span> is the number of unique words.</p>\n\n<p>A hash table would be a good way to create the set of unique words.</p></li>\n<li><p>Your test string assumes repeated words will be contiguous (as opposed to,\nsay <code>\"I am good am good am.\"</code>). Is that intentional? Desirable?</p></li>\n</ol>\n\n<p>At a high level, your algorithm is also not optimal. You've got <span class=\"math-container\">\\$O(n^2)\\$</span> performance, ignoring the dynamic allocation as you incrementally build up those strings. With that, it gets worse.</p>\n\n<p>I believe the canonical solution to this is (roughly):</p>\n\n<pre><code>create a map of words -> counts\nset wordStart to 0\niterate through the string\n if the current character is a word delimiter\n set word to the substring from wordStart to here\n set wordStart to here\n if map contains word\n increment the count for that word\n else\n add the word to the map with a count of 1\n end\n end\nend\n\nset maxWord to null\nset max to 0\niterate through the map\n if count for this word > max\n set maxWord to this word\n set max to count\n end\nend\n\nreturn maxWord\n</code></pre>\n\n<p>That gives you <span class=\"math-container\">\\$O(n)\\$</span>: you only walk the entire string once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-23T18:40:46.273",
"Id": "1413",
"ParentId": "1394",
"Score": "7"
}
},
{
"body": "<h1>Clarify the requirements</h1>\n\n<p>There are two aspects of the problem statement that are unclear (that's quite probably intentional, given that this is an interview question).</p>\n\n<ol>\n<li><p>What constitutes a \"word\" here? Splitting the string on spaces is one possibility, but means that a word bounded by punctuation will be considered different to the same word standing alone. We can't completely ignore punctuation, though - <code>cant</code> and <code>can't</code> are completely different words, for example.</p></li>\n<li><p>What if there isn't a single most frequent word? There might be a draw, or there might be no words in the input at all. What should we return in those cases? (My recommendation: always return a container (e.g. <code>std::vector</code>) of results, and let the caller choose what to do if it's length is not 1.)</p></li>\n</ol>\n\n<p>If you're not in a position to obtain answers to these questions, it's important to include comments indicating the assumptions you've made (i.e. your guesses at the answers).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:59:00.807",
"Id": "217314",
"ParentId": "1394",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T00:44:04.093",
"Id": "1394",
"Score": "5",
"Tags": [
"c++",
"array",
"interview-questions"
],
"Title": "Max repeated word in a string"
} | 1394 |
<p>Given the following problem (SICP Exercise 1.3):</p>
<blockquote>
<p>Define a procedure that takes three
numbers as arguments and returns the
sum of squares of the two largest
numbers.</p>
</blockquote>
<p>I wrote the following (somewhat clumsy) solution in Scheme. How can I make it better?</p>
<pre><code>(define (greatest-two a b c)
(cond ((> a b) (cond ((> b c) (list a b))
(else (list a c))))
((> a c) (cond ((> c b) (list a c))
(else (list a b))))
(else (list b c))))
(define (square x) (* x x))
(define (sum-of-squares a b) (+ (square a) (square b)))
(define (f a b c)
(apply sum-of-squares (greatest-two a b c)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T03:50:21.590",
"Id": "60463",
"Score": "0",
"body": "I posted [my solution](http://stackoverflow.com/questions/161666/sicp-exercise-1-3-request-for-comments/161675#161675) to this question some time ago. It doesn't involve any conditionals, because I'm cheap like that. ;-)"
}
] | [
{
"body": "<p>Scheme is a lot more functional than Common Lisp. The way you can apply that to this situation is by making more use of passing functions around (to the point that this problem is almost a one-liner). For the puzzle as written, I'd do something like</p>\n\n<pre><code>(define (big-squares a b c)\n (apply + (map (lambda (n) (* n n))\n (take (sort (list a b c) >) 2))))\n</code></pre>\n\n<p>If you wanted to decompose it properly into named functions</p>\n\n<pre><code>(define (square num) (expt num 2))\n(define (sum num-list) (apply + num-list))\n(define (two-biggest num-list) (take (sort num-list >) 2))\n\n(define (big-squares a b c) (sum (map square (two-biggest (list a b c)))))\n</code></pre>\n\n<p>If you wanted to go completely overboard, also toss in</p>\n\n<pre><code>(define (squares num-list) (map square num-list))\n</code></pre>\n\n<p>which would let you define <code>big-squares</code> as</p>\n\n<pre><code>(sum (squares (two-biggest (list a b c))))\n</code></pre>\n\n<p>(code above in <code>mzscheme</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:17:38.067",
"Id": "2430",
"Score": "0",
"body": "MzScheme is known these days as Racket. Just a heads-up. :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:28:39.760",
"Id": "2431",
"Score": "0",
"body": "@Chris - The PLT-Scheme project is known as Racket these days. I'm still running the command line version from the Debian repos, which *is* still `mzscheme`, even though the package it comes in is now called `plt-scheme`. :p"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:36:56.573",
"Id": "2432",
"Score": "1",
"body": "I encourage you to grab the latest package from `git://git.debian.org/collab-maint/racket.git` and build yourself some brand new Racket 5.1 packages. :-D"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:45:30.497",
"Id": "2433",
"Score": "0",
"body": "Wow, very elegant solution. I like this answer too :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T10:23:12.560",
"Id": "52791",
"Score": "0",
"body": "is there a `take` equivalent in `chez/petite` scheme?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:21:04.597",
"Id": "52800",
"Score": "1",
"body": "@ricardo - According to [this](http://www.scheme.com/csug8/objects.html#./objects:h2), in `chez` it's called `list-head`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T05:31:01.677",
"Id": "1399",
"ParentId": "1395",
"Score": "10"
}
},
{
"body": "<p>So either a is the minimum of the list in which case b and c or it's not and it's one of the numbers you want to keep. The other is the max of b and c. </p>\n\n<pre><code>(define (f a b c)\n (if (or (> a b) (> a c))\n (sum-of squares a (max b c))\n (sum-of-squares b c)))\n\n(define (square x) (* x x))\n(define (sum-of-squares a b) (+ (square a) (square b)))\n</code></pre>\n\n<p>Of you can take the sum of the squares of all of them and subtract the square of the min.</p>\n\n<pre><code>(define (f a b c)\n (- (fold + 0 (map square (list a b c))) (square (min a b c))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-09T05:39:34.227",
"Id": "116286",
"ParentId": "1395",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1399",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-23T02:08:16.997",
"Id": "1395",
"Score": "9",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Sum of squares of two largest of three numbers"
} | 1395 |
<p>Given the following task:</p>
<blockquote>
<p>Use Newton's method to compute the square root of a number. Newton's
method involves successive approximation. You start with a guess, and
then continue averaging successive guesses until you reach a
satisfactory level of precision.</p>
</blockquote>
<p>I wrote the following (rough) solution in Scheme. Can you help me make it better?</p>
<pre><code>(define (abs x) ((if (< x 0) - +) x))
(define (almost-equal x y delta)
(> delta (abs (- x y))))
(define (sqrt-prime x last-x)
(let ((next-x (/ (+ x last-x) 2)))
(if (almost-equal next-x x 0.000001) x
(sqrt-prime next-x x))))
(define (sqrt x) (sqrt-prime x 1))
</code></pre>
| [] | [
{
"body": "<p><code>abs</code> is mentioned in R6RS, so I'm inclined to believe that you can treat it as a primitive.</p>\n\n<hr>\n\n<p>The scheme convention is to end predicates with <code>?</code>, so that should really be <code>almost-equal?</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:24:49.797",
"Id": "1400",
"ParentId": "1396",
"Score": "3"
}
},
{
"body": "<p>The <code>sqrt-prime</code> function neither needs nor uses the <code>last-guess</code> argument. It can be safely eliminated:</p>\n\n<pre><code>(define (sqrt-prime guess x)\n (if (good-enough? guess x) guess\n (sqrt-prime (better-guess guess x) x)))\n</code></pre>\n\n<p>You may call the function thus:</p>\n\n<pre><code>(define (sqrt x) (sqrt-prime 1.0 x))\n</code></pre>\n\n<p>I feel that, other than this minor change, your program is succinct enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T02:02:43.547",
"Id": "2474",
"Score": "0",
"body": "Good point. I got some good feedback on (cuberoot ...) so I'm changing this quite a bit, but otherwise I'd definitely fix it - thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T18:04:26.470",
"Id": "1412",
"ParentId": "1396",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-23T02:40:31.550",
"Id": "1396",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"numerical-methods"
],
"Title": "Use Newton's Method to compute sqrt(x)"
} | 1396 |
<p>I've implemented a <code>let-with</code> macro that takes an association list, keyed by symbols, that enables code to bind their corresponding values to local variables.</p>
<p>It's designed to have a similar effect to JavaScript's <code>with</code>, but without <a href="http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/" rel="nofollow"><code>with</code>'s attendant problems</a> (by making you explicitly list the variables to bind).</p>
<pre class="lang-lisp prettyprint-override"><code>(define-syntax let-with
(syntax-rules ()
((let-with alist (key ...) expr ...)
(let ((key (cond ((assq 'key alist) => cdr))) ...) expr ...))))
</code></pre>
<p>I'd love to hear of any improvements to <code>let-with</code>'s interface and/or implementation.</p>
<p>Example usage:</p>
<pre class="lang-lisp prettyprint-override"><code>(define alist '((first . "Jane")
(last . "Doe")))
(let-with alist (first last)
(string-append first " " last)) ; "Jane Doe"
</code></pre>
<p>Keys that don't exist in the incoming alist receive an undefined value; they do not fail to get bound, unlike JavaScript's <code>with</code>.</p>
| [] | [
{
"body": "<p>JavaScript's <code>with</code> statement allows one to modify object members. This may not be possible for certain types of values (such as strings) using the <code>let-with</code> macro as defined above.</p>\n\n<hr>\n\n<p>One could generalize <code>let-with</code> to bind values from several association lists. It could have the form:</p>\n\n<pre><code>(let-with\n ((alist0 (key00 key01 key02...))\n (alist1 (key10 key11 key12...)))\n expr0\n expr1\n ...)\n</code></pre>\n\n<p>Aside from being more general, the above form closely resembles the <code>let</code> form. I prefer this over the simpler form, though I would understand if your taste and needs differ.</p>\n\n<p>Here's my implementation of the general form--it uses two auxiliary macros, one to generate two lists (alists and their corresponding keys) and the other to emit the actual code (which looks almost exactly like your definition above):</p>\n\n<pre><code>(define-syntax let-with\n (syntax-rules ()\n ((let-with bindings . body)\n (gen-let-with bindings () () body))))\n\n(define-syntax gen-let-with\n (syntax-rules ()\n ((gen-let-with () alists keys body)\n (emit-let-with-code alists keys body))\n ((gen-let-with ((alist (key)) . rest-bindings) alists keys body)\n (gen-let-with\n rest-bindings\n (alist . alists)\n (key . keys)\n body))\n ((gen-let-with ((alist (key . rest-keys)) . rest-bindings) alists keys body)\n (gen-let-with\n ((alist rest-keys) . rest-bindings)\n (alist . alists)\n (key . keys)\n body))))\n\n(define-syntax emit-let-with-code\n (syntax-rules ()\n ((emit-let-with-code (alist ...) (key ...) (expr ...))\n (let ((key (cond ((assq 'key alist) => cdr))) ...) expr ...))))\n</code></pre>\n\n<p>Perhaps there is a simpler definition. I haven't played with macros in a while. =)</p>\n\n<hr>\n\n<p>Here are some examples:</p>\n\n<pre><code>(define alist '((first . \"Jane\") (middle . \"Q\") (last . \"Doe\")))\n(define blist '((first . \"John\") (middle . \"R\") (last . \"Lee\")))\n(define clist '((first . \"Jose\") (middle . \"S\") (last . \"Paz\")))\n(define first '((title . \"Ms\") (suffix . \"Esq\")))\n\n(let-with\n ()\n \"Hello, world!\") ; => \"Hello, world!\"\n\n(let-with\n ((alist (first middle last)))\n (string-append first \" \" middle \". \" last)) ; => \"Jane Q. Doe\"\n\n(let-with\n ((alist (first))\n (blist (middle last)))\n (string-append first \" \" middle \". \" last)) ; => \"Jane R. Lee\"\n\n(let-with\n ((alist (first))\n (blist (middle))\n (clist (last)))\n (string-append first \" \" middle \". \" last)) ; => \"Jane R. Paz\"\n\n(let-with\n ((first (title))\n (alist (first))\n (blist (middle))\n (clist (last))\n (first (suffix)))\n (string-append first \" \" middle \". \" last)) ; => \"Jane R. Paz\"\n\n(let-with\n ((alist (first middle last)))\n (set! first \"Rose\")\n (string-append first \" \" middle \". \" last)) ; => \"Rose Q. Doe\"\n\n(let-with\n ((alist (first middle last)))\n (string-append first \" \" middle \". \" last)) ; => \"Jane Q. Doe\"\n</code></pre>\n\n<p>Since <code>let-with</code> expands into a single <code>let</code>, the third-to-last example works.</p>\n\n<p>The last two examples demonstrate the inability to modify a value in its corresponding association list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T12:27:20.750",
"Id": "3457",
"Score": "0",
"body": "Thanks for your answer---I haven't forgotten about you (I've read it the moment it was posted). I wanted to write a full response to that, with my ideas about how such an extended macro might be implemented, etc., but my free time is so very limited at the moment. :-("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T07:06:23.507",
"Id": "1967",
"ParentId": "1398",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T04:12:24.613",
"Id": "1398",
"Score": "4",
"Tags": [
"scheme",
"macros"
],
"Title": "Is this a good way to implement let-with?"
} | 1398 |
<p>Newton's method for finding cube roots states that for any given \$x\$ and a guess \$y\$, a better approximation is \$\dfrac{(\dfrac{x}{y^2} + 2y)}{3}\$.</p>
<p>What do you think of this code for finding a cube root in Scheme?</p>
<pre><code>(define (improveguess y x)
; y is a guess for cuberoot(x)
(/ (+ (/ x (expt y 2)) (* 2 y)) 3))
(define (cube x) (* x x x))
(define (goodenough? guess x)
(< (/ (abs (- (cube guess) x)) guess) 0.0001))
(define (cuberoot x) (cuberoot-iter 1.0 x))
(define (cuberoot-iter guess x)
(if (goodenough? guess x) guess
(cuberoot-iter (improveguess guess x) x)))
</code></pre>
| [] | [
{
"body": "<p>Your <code>improve-guess</code> is probably better written like this:</p>\n\n<pre><code>(/ (+ (/ x y y) y y) 3)\n</code></pre>\n\n<p>Or, if you define a <code>mean</code> function:</p>\n\n<pre><code>(define (mean . xs)\n (/ (apply + xs) (length xs)))\n</code></pre>\n\n<p>then you can make <code>improve-guess</code> even simpler:</p>\n\n<pre><code>(mean (/ x y y) y y)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:30:49.483",
"Id": "2439",
"Score": "0",
"body": "What does the '.' in '(define (mean . xs)' do?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T18:08:24.760",
"Id": "2457",
"Score": "1",
"body": "@jaresty - that's the scheme notation for a `&rest` argument."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T06:58:35.073",
"Id": "1402",
"ParentId": "1401",
"Score": "4"
}
},
{
"body": "<p>If you look at your code for this exercise as well as <a href=\"https://codereview.stackexchange.com/questions/1396/scheme-use-newtons-method-to-compute-sqrtx\">the one about approximating the square root</a> and <a href=\"https://codereview.stackexchange.com/questions/1324/common-lisp-find-epsi\">the one about finding epsi</a>, you'll notice a common pattern:</p>\n\n<p>You have a function which performs a single step and a predicate which tells you when you're done. You then apply the stepping function until the predicate is met. When you encounter a common pattern like this, the best thing to do is usually to abstract it. So let's define an <code>apply-until</code> function which takes a stepping function, a predicate and an initial value and applies the function to the value until the predicate is met:</p>\n\n<pre><code>(define (apply-until step done? x)\n (if (done? x) x\n (apply-until (step x) step done?)))\n</code></pre>\n\n<p>You can now define your <code>cuberoot</code> function using <code>apply-until</code> instead of <code>cuberoot-iter</code>:</p>\n\n<pre><code>(define (cuberoot x)\n (apply-until (lambda (y) (improve-guess y x)) (lambda (guess) (goodenough? guess)) 1.0))\n</code></pre>\n\n<p>You can also move your helper functions as local functions into the <code>cuberoot</code> function. This way they don't need to take <code>x</code> as an argument (as they will close over it) and can thus be passed directly to <code>apply-until</code> without using <code>lambda</code>:</p>\n\n<pre><code>(define (cuberoot x)\n (define (improveguess y)\n ; y is a guess for cuberoot(x)\n (/ (+ (/ x (expt y 2)) (* 2 y)) 3))\n\n (define (goodenough? guess)\n (< (/ (abs (- (cube guess) x)) guess) 0.0001))\n\n (apply-until improveguess goodenough? 1.0))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T00:55:04.610",
"Id": "2471",
"Score": "0",
"body": "To hoist the constant \"variables\" in `apply-until` so that you don't have to pass them in over and over, I'd implement using a named `let`:\n\n `(define (apply-until done? next x)\n (let loop ((x x))\n (if (done? x) x\n (loop (next x)))))`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T04:26:51.190",
"Id": "2475",
"Score": "1",
"body": "Is there a reason to use \"let\" rather than a nested \"define,\" Chris?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T07:14:59.670",
"Id": "2477",
"Score": "0",
"body": "I mean, I guess I don't understand the syntax of (let ...) in scheme - what does (let loop ...) do?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T00:10:32.153",
"Id": "2510",
"Score": "0",
"body": "I found the answer to my question at http://people.csail.mit.edu/jaffer/r5rs_6.html#SEC36 under the heading \"4.2.4 Iteration\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T21:06:19.463",
"Id": "1416",
"ParentId": "1401",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1416",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-23T06:41:00.277",
"Id": "1401",
"Score": "6",
"Tags": [
"mathematics",
"lisp",
"scheme"
],
"Title": "Cube root (Newton's method)"
} | 1401 |
<p>Here's my function for getting the length of a file, in characters:</p>
<pre><code>unsigned int GetFileLength(std::string FileName)
{
std::ifstream InFile(FileName.c_str());
unsigned int FileLength = 0;
while (InFile.get() != EOF) FileLength++;
InFile.close();
return FileLength;
}
</code></pre>
<p>How can this be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-21T20:18:48.920",
"Id": "266271",
"Score": "0",
"body": "of course you are assuming this is an ASCII file. 1 byte == 1 char. Lets hope there are no foreigners around with their pesky unicode junk :-). Also note the returning uint is a little optimistic in todays world, files get bigger than 4gb"
}
] | [
{
"body": "<p>Is accuracy important? I believe you could try to get the filesize and divide this by the amount of bytes the formatting uses. This could give a good estimate of the amount of characters in the file.</p>\n\n<p>I say estimate because I might be forgetting about possible headers and such, although I believe a simple text file doesn't have that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T16:12:35.263",
"Id": "2454",
"Score": "0",
"body": "It does need to be accurate."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T16:27:29.493",
"Id": "2455",
"Score": "0",
"body": "Well, considering you can get the exact file size (so not size on disk), as e.g. in the answer of Mark, it should be accurate. Mark's answer assumes single byte encoding. If this is the case, consider it your answer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T18:29:27.577",
"Id": "2460",
"Score": "0",
"body": "The file is opened in binary mode. Encoding doesn't matter."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T20:31:35.490",
"Id": "2463",
"Score": "2",
"body": "@Mark Loeser: He wants to get the amount of 'characters' in the file as far as I understand, not the amount of bytes (although that might be the same, yes)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T20:48:46.763",
"Id": "2465",
"Score": "0",
"body": "You are right, my mistake. It was pretty early when I looked at this, so yea...I missed the \"characters\" part :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T13:22:01.637",
"Id": "1406",
"ParentId": "1405",
"Score": "1"
}
},
{
"body": "<p>Just seek to the end of the file and grab the value:</p>\n\n<pre><code>ifstream is;\nis.open (FileName.c_str(), ios::binary );\nis.seekg (0, ios::end);\nlength = is.tellg();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-23T13:38:02.027",
"Id": "1407",
"ParentId": "1405",
"Score": "7"
}
},
{
"body": "<p>I dislike seeking, so here's my non-seeking approach.</p>\n\n<pre><code>#include <sys/stat.h>\n#include <cerrno>\n#include <cstring>\n#include <stdexcept>\n#include <string>\n\noff_t GetFileLength(std::string const& filename)\n{\n struct stat st;\n if (stat(filename.c_str(), &st) == -1)\n throw std::runtime_error(std::strerror(errno));\n return st.st_size;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T14:38:15.373",
"Id": "2493",
"Score": "0",
"body": "+1 for simplicity, though something in the back of my head says that stat is not portable."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T03:23:52.390",
"Id": "2516",
"Score": "2",
"body": "Well, `stat` is defined in POSIX. If that's not portable, I don't know what is. :-P"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T14:29:26.130",
"Id": "2529",
"Score": "0",
"body": "@Chris--you're absolutely right! It's not ANSI C, but it's definitely POSIX. And I believe even Windows supports stat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T10:13:40.053",
"Id": "210974",
"Score": "0",
"body": "https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T02:35:50.537",
"Id": "1417",
"ParentId": "1405",
"Score": "6"
}
},
{
"body": "<p>Try <code>std::ios::ate</code></p>\n\n<pre><code>#include <fstream>\n#include <string>\n\nsize_t getFileSize( std::string fileName ) {\n std::ifstream file( fileName, std::ios::binary | std::ios::ate );\n size_t fileSize = file.tellg();\n file.close();\n\n return fileSize;\n}\n</code></pre>\n\n<p><code>std::ios::ate</code> opens the file with the pointer(s) at the end. <code>file.eof()</code> would return <code>true</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-21T16:42:34.060",
"Id": "142041",
"ParentId": "1405",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1407",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-23T13:10:57.700",
"Id": "1405",
"Score": "8",
"Tags": [
"c++",
"file"
],
"Title": "Getting the length of a file in characters"
} | 1405 |
<p>I wrote the following JPA method that queries a database to return a distinct list of a String field (called mtfcc) of a Location object. I then took the list of strings to query for the associated name for that MTFCC.</p>
<p>Could I just modify the first query to get the results, without having to use the for loop to get the associated name field?</p>
<pre><code>@Override
public Map<String, String> getAvailableBorderTypes() {
// create empty map to store results in. If we don't find results, an empty hashmap will be returned
Map<String, String> results = new HashMap<String, String>();
EntityManager em = entityManagerFactory.createEntityManager();
// get the distinct mtfcc's
String jpaQuery = "SELECT DISTINCT location.mtfcc FROM Location location";
// get the distinct mtfcc codes
List<String> mtfccList = (List<String>) em.createQuery(jpaQuery).getResultList();
// cycle through the mtfcc list and get the name to associate with it
for (String mtfcc: mtfccList) {
String nameQuery = "SELECT DISTINCT location.name FROM Location location WHERE location.mtfcc = ?1";
String name = (String) em.createQuery(nameQuery).setParameter(1, mtfcc).getSingleResult();
results.put(mtfcc, name);
}
return results;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:05:13.053",
"Id": "2444",
"Score": "0",
"body": "I don't know about JPA and which queries it supports, but wouldn't it already be faster to do `SELECT location FROM Location location` and do the distinct programmatically? Not saying this is the best solution, but right now you are querying all locations twice."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:09:34.623",
"Id": "2445",
"Score": "0",
"body": "It's a performance issue. Location could potentially have hundreds of thousands of rows in the database."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:18:21.077",
"Id": "2447",
"Score": "0",
"body": "So I'm guessing JPA allows you to use indexes? Otherwise it would be a memory issue, and not as much a performance issue."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:28:22.517",
"Id": "2448",
"Score": "3",
"body": "Again, I might be entirely wrong here, but what about `SELECT DISTINCT location.mtfcc, location.name FROM Location location`. :) Perhaps consider phrasing this as a question on distinct on Stack Overflow if you don't get any knowledgeable responses here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T15:43:46.997",
"Id": "2451",
"Score": "2",
"body": "I've considered it, but I'm having a major brain fart in my query-fu here trying to decide it it would work. I think it would, so I'll just have to try it once the code is runnable."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T22:57:00.830",
"Id": "2469",
"Score": "0",
"body": "@Steven: The query would work, but JPA has a difficult time working with specific columns. It really was designed for entities stored as a whole row. I've found a possible solution, but haven't been able to prove it yet. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-13T06:46:27.883",
"Id": "333015",
"Score": "0",
"body": "Refer https://stackoverflow.com/questions/7595328/jpa-2-0-native-query-results-as-map/46190527#46190527"
}
] | [
{
"body": "<p>Ok, I've got a possible simplification for you. The goal I had was to get to using one query:</p>\n\n<pre><code>SELECT DISTINCT location.mftcc, location.name FROM Location location\n</code></pre>\n\n<p>It turns out that <code>Query.getResultList()</code> behaves funny: It returns a <code>List</code> of <code>Object[]</code>! Each entry in the list represents a row returned from the database, where the entries in the Object[] are each field specified in the SELECT. Also, to furthur complicate matters, each field is returned as the JPA type. So, you have to treat the whole array as an <code>Object[]</code> and cast the individual elements.</p>\n\n<p>Here's the code to get it to work:</p>\n\n<pre><code>public Map<String, String> getAvailableBorderTypes() {\n // create empty map to store results in. If we don't find results, an empty hashmap will be returned\n Map<String, String> results = new HashMap<String, String>();\n\n EntityManager em = entityManagerFactory.createEntityManager();\n\n // Construct and run query\n String jpaQuery = \"SELECT DISTINCT location.mftcc, location.name FROM Location location\";\n List<Object[]> resultList = em.createQuery(jpaQuery).getResultList();\n\n // Place results in map\n for (Object[] borderTypes: resultList) {\n results.put((String)borderTypes[0], (String)borderTypes[1]);\n }\n\n return results;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:09:48.093",
"Id": "2533",
"Score": "0",
"body": "JPA (the Java API, anyway) is also pretty undocumented. I had to use reflection just to find out the return type. Fun exercise!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:08:01.030",
"Id": "1457",
"ParentId": "1409",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "1457",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-23T14:32:07.183",
"Id": "1409",
"Score": "11",
"Tags": [
"java"
],
"Title": "JPA Query to Return a Map"
} | 1409 |
<p>In Python, <code>itertools.combinations</code> yields combinations of elements in a sequence sorted by lexicographical order. In the course of solving certain math problems, I found it useful to write a function, <code>combinations_by_subset</code>, that yields these combinations sorted by subset order (for lack of a better name).</p>
<p>For example, to list all 3-length combinations of the string 'abcde':</p>
<pre><code>>>> [''.join(c) for c in itertools.combinations('abcde', 3)]
['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']
>>> [''.join(c) for c in combinations_by_subset('abcde', 3)]
['abc', 'abd', 'acd', 'bcd', 'abe', 'ace', 'bce', 'ade', 'bde', 'cde']
</code></pre>
<p>Formally, for a sequence of length \$n\$, we have \$\binom{n}{r}\$ combinations of length \$r\$, where \$\binom{n}{r} = \frac{n!}{r! (n - r)!}\$</p>
<p>The function <code>combinations_by_subset</code> yields combinations in such an order that the first \$\binom{k}{r}\$ of them are the r-length combinations of the first k elements of the sequence.</p>
<p>In our example above, the first \$\binom{3}{3} = 1\$ combination is the 3-length combination of 'abc' (which is just 'abc'); the first \$\binom{4}{3} = 4\$ combinations are the 3-length combinations of 'abcd' (which are 'abc', 'abd', 'acd', 'bcd'); etc.</p>
<p>My first implementation is a simple generator function:</p>
<pre><code>def combinations_by_subset(seq, r):
if r:
for i in xrange(r - 1, len(seq)):
for cl in (list(c) for c in combinations_by_subset(seq[:i], r - 1)):
cl.append(seq[i])
yield tuple(cl)
else:
yield tuple()
</code></pre>
<p>For fun, I decided to write a second implementation as a generator expression and came up with the following:</p>
<pre><code>def combinations_by_subset(seq, r):
return (tuple(itertools.chain(c, (seq[i], ))) for i in xrange(r - 1, len(seq)) for c in combinations_by_subset(seq[:i], r - 1)) if r else (() for i in xrange(1))
</code></pre>
<p>My questions are:</p>
<ol>
<li>Which function definition is preferable? (I prefer the generator function over the generator expression because of legibility.)</li>
<li>Are there any improvements one could make to the above algorithm/implementation?</li>
<li>Can you suggest a better name for this function?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-10T22:24:12.120",
"Id": "239403",
"Score": "0",
"body": "I think this ordering can be very useful and should be added to standard `itertools` library as an option."
}
] | [
{
"body": "<p>I should preface with the fact that I don't know python. It's likely that I've made a very clear error in my following edit. Generally though, I prefer your second function to your first. If python allows, I would break it up a bit for readability. Why do I like it? It doesn't need the <code>yield</code> keyword and it's less nested.</p>\n\n<pre><code># I like using verbs for functions, perhaps combine_by_subset()\n# or generate_subset_list() ?\ndef combinations_by_subset(seq, r):\n return (\n\n # I don't know what chain does - I'm making a wild guess that\n # the extra parentheses and comma are unnecessary\n # Could this be reduced to just itertools.chain(c, seq[i]) ?\n\n tuple(itertools.chain(c, (seq[i], )))\n for i in xrange(r - 1, len(seq))\n for c in combinations_by_subset(seq[:i], r - 1)\n\n ) if r\n\n else ( () for i in xrange(1) )\n</code></pre>\n\n<p>I'm just waiting for this answer to get flagged as not being helpful. Serves me right for putting my two cents in when I don't even know the language. ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T14:32:03.777",
"Id": "133937",
"Score": "0",
"body": "I would say the yield method is preferable because without yield you probably need to build an array (or some other data structure) in memory containing the entire data set, which may take up a lot of memory, or require a considerable amount of CPU power/time to generate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T10:14:33.340",
"Id": "1425",
"ParentId": "1419",
"Score": "0"
}
},
{
"body": "<p>Rather converting from tuple to list and back again, construct a new tuple by adding to it.</p>\n\n<pre><code>def combinations_by_subset(seq, r):\n if r:\n for i in xrange(r - 1, len(seq)):\n for cl in combinations_by_subset(seq[:i], r - 1):\n yield cl + (seq[i],)\n else:\n yield tuple()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T14:34:07.493",
"Id": "1429",
"ParentId": "1419",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "1429",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-24T04:08:29.953",
"Id": "1419",
"Score": "5",
"Tags": [
"python",
"algorithm",
"generator",
"combinatorics"
],
"Title": "Python generator function that yields combinations of elements in a sequence sorted by subset order"
} | 1419 |
<p>I just found out about the existence of this forum and it's exactly what I needed. I just asked <a href="https://stackoverflow.com/questions/5386795/how-to-safely-save-data-to-an-existing-file-with-c">this</a> question on Stack Overflow and after reading the answers I came up with a code (not the one I posted there but the one I'm posting here).</p>
<p>First, this is my messed up code:</p>
<pre><code>string tempFile = Path.GetTempFileName();
using (Stream tempFileStream = File.Open(tempFile, FileMode.Truncate))
{
SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project));
xmlFormatter.Serialize(tempFileStream, Project);
}
if (File.Exists(fileName)) File.Delete(fileName);
File.Move(tempFile, fileName);
if (File.Exists(tempFile)) File.Delete(tempFile);
</code></pre>
<p>When saving to an existing file that is in my Dropbox, it will, sometimes, delete the original file and fail to move the temporary file to the original location in <code>File.Move(tempFile, fileName);</code>. So here is my new code that I think it should never, unless the OS became self-conscious and evil, delete the original file without saving the new one. The worst it can happens is that the original will be renamed and will stay like that and I will have to let the user know (see the <code>MessageBox</code> at the bottom):</p>
<pre><code>private string GetTempFileName(string dir)
{
string name = null;
int attempts = 0;
do
{
name = "temp_" + Player.Math.RandomDigits(10) + ".hsp";
attempts++;
if (attempts > 10) throw new Exception("Could not create temporary file.");
}
while (File.Exists(Path.Combine(dir, name)));
return name;
}
private void TryToDelete(string path)
{
try { File.Delete(path); }
catch { }
}
private void SaveProject(string fileName)
{
bool originalRenamed = false;
string tempNewFile = null;
string oldFileTempName = null;
Exception exception = null;
try
{
tempNewFile = GetTempFileName(Path.GetDirectoryName(fileName));
using (Stream tempNewFileStream = File.Open(tempNewFile, FileMode.CreateNew))
{
SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project));
xmlFormatter.Serialize(tempNewFileStream, Project);
}
if (File.Exists(fileName))
{
oldFileTempName = GetTempFileName(Path.GetDirectoryName(fileName));
File.Move(fileName, oldFileTempName);
originalRenamed = true;
}
File.Move(tempNewFile, fileName);
originalRenamed = false;
CurrentProjectPath = fileName;
}
catch (Exception ex)
{
exception = ex;
}
finally
{
if (tempNewFile != null) TryToDelete(tempNewFile);
if (originalRenamed)
{
try
{
File.Move(oldFileTempName, fileName);
originalRenamed = false;
}
catch { }
}
if (exception != null) MessageBox.Show(exception.Message);
if (originalRenamed)
{
MessageBox.Show("'" + fileName + "'" +
" have been corrupted or deleted in this operation.\n" +
"A backup copy have been created at '" + oldFileTempName + "'");
}
else if (oldFileTempName != null) TryToDelete(oldFileTempName);
}
}
</code></pre>
<p><code>Player.Math.RandomDigits</code> is just a function that returns a string with random digits. Do you think my code is safe as I think it is or am I missing something? It's hard for me to test every possible exception.</p>
| [] | [
{
"body": "<ul>\n<li><p>I don't like discarding all exceptions from File.Delete(). I think it's fine to discard a DirectoryNotFoundException here, but I think the others should be allowed to propagate up and be shown to the user. I find that hiding the fact that the user does not have write access or that another process has the file locked generally tends to cause more confusing errors later on.</p></li>\n<li><p><strike>You serialise the new content inside the big try-catch. If the serialisation fails then you tell the user that the file has been corrupted or deleted and they should restore from the backup provided, even though you have not reached the point where the backup is made.</strike></p></li>\n<li><p>The idea of having one big try-catch and then using flags to identify what stage you were up-to makes me a little uneasy. You can replace the <code>originalRenamed</code> flag with a try-catch around <code>File.Move(tempNewFile, fileName)</code> since this is the only call made while the flag is set to true.</p>\n\n<pre><code>try\n{\n // ...\n\n try\n {\n File.Move(tempNewFile, fileName);\n }\n catch\n {\n if (!string.IsNullOrEmpty(oldFileTempName) && File.Exists(oldFileTempName))\n {\n File.Move(oldFileTempName, fileName);\n }\n\n MessageBox.Show(\"...\");\n\n throw;\n }\n\n // ...\n\n if (!string.IsNullOrEmpty(oldFileTempName) && File.Exists(oldFileTempName))\n {\n TryToDelete(oldFileTempName);\n }\n}\ncatch(Exception ex)\n{\n MessageBox.Show(ex.Message);\n}\n</code></pre>\n\n<p>This may be inconvenient if you want the message boxes to appear in the specific order but I don't think it should be too much of an issue.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T18:03:09.210",
"Id": "2501",
"Score": "0",
"body": "Wait, if serialization fails I won't tell the user that the file have been corrupted because the `originalRenamed` flag won't be set. Also, the reason I use a flag instead of putting the `File.Move(tempNewFile, fileName)` into a try-catch is because I don't wan't to show the file corrupted message if I didn't previously call `File.Move(fileName, oldFileTempName);`, instead, just delete the tempNewFile and show the IOException. Does it make sense?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T18:13:35.317",
"Id": "2502",
"Score": "0",
"body": "But I do agree with the discarding all the File.Delete exceptions issue."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T01:53:28.503",
"Id": "2513",
"Score": "0",
"body": "Yes, you are right about the second point. Though I still maintain however, that it would be better to have a more localised try-catch block than using flags. In the example I provided, it checks if the backup exists so that the \"corrupted message\" will not be shown if no backup was made."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T07:40:46.533",
"Id": "1423",
"ParentId": "1420",
"Score": "4"
}
},
{
"body": "<p>Using <a href=\"http://msdn.microsoft.com/en-us/library/9d9h163f.aspx\" rel=\"noreferrer\">File.Replace()</a> still seems the best option to me. As you mentioned on SO, the following might give a problem:</p>\n\n<blockquote>\n <p>If the sourceFileName and\n destinationFileName are on different\n volumes, this method will raise an\n exception. If the\n destinationBackupFileName is on a\n different volume from the source file,\n the backup file will be deleted.</p>\n</blockquote>\n\n<p>To prevent this exception from being thrown, can't you first check whether you can serialize the temp file directly to the desired volume? If this isn't possible, further processing will fail as well, so you can already show a message that the volume isn't writeable.</p>\n\n<p>Afterwards, call the <code>Replace</code> function, creating a backup file. When it fails, handle appropriately and check in which state your files are, indicate to the user when something is 'corrupt' (so point to the backup file). In the <code>finally</code> check whether the backup file exists and remove.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T18:29:46.877",
"Id": "2503",
"Score": "0",
"body": "This sounds good. The only problem is the \"chech in which state your files are\" part. What if something fails when checking that? `File.Exists` is known to be unreliable. My code, though, knows exactly on which state the files are (only thing it doesn't really know is whether the temporary files have been deleted or not, but that's not as relevant as knowing whether the original file have been renamed or not)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T19:25:56.823",
"Id": "2504",
"Score": "0",
"body": "@jsoldi: I don't know of any unreliabilities of `File.Exists`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T19:33:19.950",
"Id": "2505",
"Score": "0",
"body": "I've seen it myself. Sometimes it will return false when the file does exist. Something to do with files virtualization."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T13:16:33.673",
"Id": "1427",
"ParentId": "1420",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "1423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-03-24T04:22:39.120",
"Id": "1420",
"Score": "11",
"Tags": [
"c#"
],
"Title": "Overwriting an existing file in C#"
} | 1420 |
<p>The following code has one of the most confusing lines I've ever wrote. I can imagine ten other way to write it but I do not know which else could be any better.</p>
<p>Note:</p>
<p><code>Db()</code> is very similar to <code>PDO()</code>, it just extends it adding few features I'm not using here.</p>
<p><code>Post::addExtra()</code> add abstract datas elaborating database data.</p>
<p>For example he created a <code>$data[13] = $data['from db1'] .' with '. $data['from db2']</code>. These because they are going to be passed to the template.</p>
<pre><code>$db = new Db();
$s = new Session();
# Default statement and parameters
$stmt =
"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
ORDER BY PostTime DESC
LIMIT 0, 30";
$par = array();
# We change the statement if the tab is selected
if ($tab = get('tab')) {
switch ($tab) {
case 'admin':
$stmt =
"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
WHERE p.PostUID = 1
ORDER BY PostTime DESC
LIMIT 0, 30";
break;
case 'trusted':
if ($s->isLogged()) {
$stmt =
"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
WHERE p.PostUID IN (
SELECT TrustedUID
FROM Trust
WHERE TrusterUID = :uid
)
ORDER BY PostTime DESC
LIMIT 0, 30";
$par = array('uid' => $s->getUID());
} else {
$stmt = '';
}
break;
case 'favorite':
if ($s->isLogged()) {
$stmt =
"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
WHERE p.PostPID IN (
SELECT FavoritePID
FROM Favorites
WHERE FavoriteUID = :uid
)
ORDER BY PostTime DESC
LIMIT 0, 30";
$par = array('uid' => $s->getUID());
} else {
$stmt = '';
}
break;
case 'top':
$weekAgo = time() - week;
$monthAgo = time() - month;
$stmt =
"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
WHERE p.PostTime > $monthAgo
LIMIT 0, 3
UNION
SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,
(
SELECT COUNT(*)
FROM Flags as f
JOIN Posts as p1
ON p1.PostPID = f.FlagPID
WHERE p1.PostPID = p.PostPID
) as PostFlags
FROM Posts AS p
JOIN Users AS u
ON p.PostUID = u.UserUID
WHERE p.PostTime > $weekAgo
ORDER BY PostFlags DESC
LIMIT 0, 30";
break;
case 'recent':
default:
break;
}
}
# Loading posts
try {
$sql = $db->prepare($stmt);
$sql->execute($par);
$posts['Data'] = $sql->fetchAll();
} catch (PDOException $e) {
throw new MyEx($e->getMessage());
}
if (count($posts['Data']) > 0) {
foreach ($posts['Data'] as &$post) {
$post = Post::addExtra($post);
}
}
</code></pre>
| [] | [
{
"body": "<p>It appears that the only difference between these queries lies in the where clause. If this is the case, you can clean up the code a bit by removing redundant SQL, like so:</p>\n\n<pre>\n$stmt = \n\"SELECT p.PostPID, p.PostUID, p.PostText, p.PostTime, u.UserUID, u.UserName, u.UserImage, u.UserRep,\n (\n SELECT COUNT(*)\n FROM Flags as f \n JOIN Posts as p1\n ON p1.PostPID = f.FlagPID\n WHERE p1.PostPID = p.PostPID\n ) as PostFlags\n FROM Posts AS p\n JOIN Users AS u\n ON p.PostUID = u.UserUID\";\n\nif ($tab = get('tab')) {\n switch ($tab) {\n\n//...Snip...\n case 'trusted':\n if ($s->isLogged()) {\n $stmt = $stmt . \n \"WHERE p.PostUID IN (\n SELECT TrustedUID\n FROM Trust\n WHERE TrusterUID = :uid\n )\";\n $par = array('uid' => $s->getUID());\n } else {\n $stmt = '';\n }\n break;\n//...Snip...\n\n }\n} \n\n$stmt . \"ORDER BY PostFlags DESC LIMIT 0, 30\";\n</pre>\n\n<p>It improves readability a bit, as only the parts that change from query to query are present. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T22:03:49.647",
"Id": "1438",
"ParentId": "1426",
"Score": "2"
}
},
{
"body": "<p>General SQL-related advice: I would factor most of these queries into a single view; you can then add WHERE parameters when selecting from the view. You can also remove the few instances of variable expansion inside the queries, and replace them with named parameters throughout (you have <code>:uid</code> already).</p>\n\n<p>For example:</p>\n\n<pre><code>CREATE OR REPLACE VIEW PostsAnnotated AS\nSELECT p.PostPID, p.PostUID, p.PostText, p.PostTime,\n u.UserUID, u.UserName, u.UserImage, u.UserRep,\n (\n SELECT COUNT(*)\n FROM Flags as f \n JOIN Posts as p1\n ON p1.PostPID = f.FlagPID\n WHERE p1.PostPID = p.PostPID\n ) as PostFlags\n FROM Posts AS p\n JOIN Users AS u\n ON p.PostUID = u.UserUID\n ORDER BY PostTime DESC;\n\nSELECT FROM PostsAnnotated WHERE PostUID = 1 LIMIT 30;\nSELECT FROM PostsAnnotated WHERE PostUID IN (\n SELECT TrustedUID\n FROM Trust\n WHERE TrusterUID = :uid)\nLIMIT 30;\n</code></pre>\n\n<p>As far as the code around addExtra: I wouldn't set $posts['Data'] to overwrite it immediately. Instead I would loop on the sql results and append to $posts['Data'] (IIRC the syntax is <code>$posts['Data'][] = $next_elem</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T18:51:14.370",
"Id": "2559",
"Score": "0",
"body": "I didn't totally got the first part of your answer. Could you explain it a little bit more?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T09:10:57.757",
"Id": "2574",
"Score": "0",
"body": "@Charlie does the SQL example help?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T09:27:35.073",
"Id": "2575",
"Score": "0",
"body": "I think i got it: The first part of the sql will be common to every query of the tab. Then I'll have to expand it with custom sql for every tab (such as `SELECT FROM PostsAnnotated WHERE PostUID = 1 LIMIT 30;`)?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T20:16:22.430",
"Id": "1461",
"ParentId": "1426",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-24T13:15:14.900",
"Id": "1426",
"Score": "5",
"Tags": [
"php",
"mysql"
],
"Title": "Gathering data from database"
} | 1426 |
<p>I have the following left join LINQ query that is returning the results that I expect, but it does not "feel" right. I need <strong>ALL</strong> records from the <code>UserProfile</code> table.</p>
<p>Then the <code>LastWinnerDate</code> is a single record from the winner table (possible multiple records) indicating the <code>DateTime</code> the last record was entered in that table for the user.</p>
<ul>
<li><code>WinnerCount</code> is the number of records for the user in the <code>winner</code> table (possible multiple records).</li>
<li><code>Video1</code> is basically a <code>bool</code> indicating there is, or is not a record for the user in the <code>winner</code> table matching on a third table <code>Objective</code> (should be 1 or 0 rows).</li>
<li><code>Quiz1</code> is same as <code>Video1</code> matching another record from <code>Objective</code> Table (should be 1 or 0 rows).</li>
<li><code>Video</code> and <code>Quiz</code> is repeated 12 times because they're used for a report, which is to be displayed to a user listing all user records and indicate if they have met the objectives.</li>
</ul>
<p></p>
<pre><code>var objectiveIds = new List<int>();
objectiveIds.AddRange(GetObjectiveIds(objectiveName, false));
var q =
from up in MetaData.UserProfile
select new RankingDTO
{
UserId = up.UserID,
FirstName = up.FirstName,
LastName = up.LastName,
LastWinnerDate = (
from winner in MetaData.Winner
where objectiveIds.Contains(winner.ObjectiveID)
where winner.Active
where winner.UserID == up.UserID
orderby winner.CreatedOn descending
select winner.CreatedOn).First(),
WinnerCount = (
from winner in MetaData.Winner
where objectiveIds.Contains(winner.ObjectiveID)
where winner.Active
where winner.UserID == up.UserID
orderby winner.CreatedOn descending
select winner).Count(),
Video1 = (
from winner in MetaData.Winner
join o in MetaData.Objective on winner.ObjectiveID equals o.ObjectiveID
where o.ObjectiveNm == Constants.Promotions.SecVideo1
where winner.Active
where winner.UserID == up.UserID
select winner).Count(),
Quiz1 = (
from winner2 in MetaData.Winner
join o2 in MetaData.Objective on winner2.ObjectiveID equals o2.ObjectiveID
where o2.ObjectiveNm == Constants.Promotions.SecQuiz1
where winner2.Active
where winner2.UserID == up.UserID
select winner2).Count(),
};
</code></pre>
| [] | [
{
"body": "<p>What LINQ is this? Entities? ESQL, linq to sql? linq to objects?</p>\n\n<p>If Linq to SQL then:</p>\n\n<p>Try this and see what the resulting SQL is then decide based on the sql, or profile the sql itself on your db?</p>\n\n<pre><code> /// <summary>\n /// From BReusable\n /// </summary>\n /// <param name=\"dc\"></param>\n /// <remarks>http://www.davidhayden.com/blog/dave/archive/2007/08/17/DataContextLogLoggingLINQToSQLOutputConsoleDebuggerOuputWindow.aspx</remarks>\n public static void SendQueriesToConsole(this DataContext dc)\n {\n dc.Log = Console.Out;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T00:23:36.167",
"Id": "1565",
"ParentId": "1428",
"Score": "1"
}
},
{
"body": "<p>It doesn't feel right, because you have a lot of repetitive code.</p>\n\n<p>Notice how each property selector's where statement contains</p>\n\n<pre><code> where objectiveIds.Contains(winner.ObjectiveID)\n where winner.Active\n where winner.UserID == up.UserID\n</code></pre>\n\n<p>That means you can refactor this where condition to a join in the containing query.</p>\n\n<p>Also, you specify an <code>order by</code> clause, when you are only using the values to get the <code>Count()</code>. This does nothing but take up space and time.</p>\n\n<p>I think <strong>this query</strong> might be more along the line of what you are trying to achieve:</p>\n\n<pre><code> var rankingDtos = \n from user in MetaData.UserProfile\n let userWinners = from winner in MetaData.Winner\n let objectives = from objective in MetaData.Objective\n where winner.ObjectiveID == objective.ObjectiveID\n select objective\n where winner.UserID == user.UserID && winner.Active\n orderby winner.CreatedOn descending\n select new\n {\n Winner = winner,\n Objectives = objectives\n }\n select new RankingDTO\n {\n UserId = user.UserID,\n FirstName = user.FirstName,\n LastName = user.LastName,\n LastWinnerDate = userWinners.First().Winner.CreatedOn,\n WinnerCount = userWinners.Count(x => objectiveIds.Contains(x.Winner.ObjectiveID)),\n Video1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecVideo1)),\n Quiz1 = userWinners.Count(x => x.Objectives.Any(o => o.ObjectiveNm == Constants.Promotions.SecQuiz1))\n };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-01T19:41:14.567",
"Id": "1613",
"ParentId": "1428",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-24T14:23:25.310",
"Id": "1428",
"Score": "10",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Left join query of user profiles"
} | 1428 |
<p>The following working function seems a bit hacky to me as it has been pieced together from a handful of (probably poorly written) online tutorials, and I want to know if there is a better (or more standard) way to approach this.</p>
<pre><code>/***
* GET HTTP Operation
*
* @param request Request URI
* @return Element Root Element of XML Response
*/
protected Element get(String request) {
HttpURLConnection connection = null;
Element rootElement;
try {
URL url = new URL(this.baseUrl + request);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = this.username + ":" + this.password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
connection.setRequestProperty("Content-type", "application/xml");
connection.setRequestProperty("Accept", "application/xml");
InputStream responseStream = connection.getInputStream();
//--- Parse XML response InputStream into DOM
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(responseStream);
rootElement = doc.getDocumentElement();
} catch(Exception e) {
System.out.print(e.toString());
rootElement = null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
return rootElement;
}
</code></pre>
<p>I am a Java novice and am especially unclear on proper <code>try</code>/<code>catch</code> usage.</p>
<p>I am creating a Java Wrapper for an REST API and this is a small piece of that puzzle. You can <a href="https://github.com/jondavidjohn/java-basecamp-api-wrapper" rel="nofollow">click here</a> to see a bigger picture of the project as a whole.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T07:12:12.903",
"Id": "75149",
"Score": "0",
"body": "Have a look at http://stackoverflow.com/questions/221442/rest-clients-for-java"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T15:37:34.533",
"Id": "75150",
"Score": "1",
"body": "Why not use something standard that is already built like [Jersey](http://jersey.java.net/)?"
}
] | [
{
"body": "<p>Adding another answer since I'm actually looking at the code now...</p>\n\n<p>You are swallowing every exception that gets thrown. The calling code has no idea whether it tried to hit a page that didn't exist, its request was malformed, etc. If you don't want to expose the exceptions (probably a good idea so your client code doesn't have to worry), then you might want to set some sort of error flag as part of your class that can be probed for the cause of not getting back the XML, or throw your own custom exceptions.</p>\n\n<p>I'm assuming in your other methods you do similar sorts of set up for the connection (the accepts, etc)...I'd recommend moving that out into its own setup method. If you need to specialize based on the type of request, then pass in the type and you can at least consolidate all of that into one place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T16:09:32.007",
"Id": "2497",
"Score": "0",
"body": "ok, so form a single 'request' method and pass the verb in as an ENUM type. I completely get what you are saying about the try/catch being too broad, in a request like this are there key lines you would expect to see an exception thrown?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T16:10:54.690",
"Id": "2498",
"Score": "0",
"body": "would you just handle the need to send request data with a third argument, and just pass it null if it is a request that does not need request data? GET for instance."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T16:13:29.400",
"Id": "2499",
"Score": "0",
"body": "@jondavidjon: I'd keep the get/put/delete/post, and have those deal with the underlying `request` method like you said. I'd expect anything that was not under my control to throw (ill-formed URL, connection failing to the remote host, bad xml, etc)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T15:59:25.637",
"Id": "1433",
"ParentId": "1430",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1433",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-24T15:13:47.267",
"Id": "1430",
"Score": "6",
"Tags": [
"java",
"beginner",
"api",
"http"
],
"Title": "Interfacing with RESTful web services"
} | 1430 |
<p>The program finds the non repeated number in a <code>int</code> array. I am using a <code>count</code> for the duplicates and making a <code>Numcounts[]</code> to store the count values. I am assuming the array is sorted. Then I can check the <code>Numcounts[]</code> for <code>1</code>, and that would be the non-repeating number. The complexity is \$O(n^2)\$.</p>
<p>Can you tell me how to do the same thing using hashmaps? I haven't used hashmaps and I know the complexity can be reduced to \$O(n))\$ using them.</p>
<pre><code>#include<stdafx.h>
#include<stdio.h>
int main()
{
int n=6;
int * Numcounts = new int[n];
int count = 0;
int a[6] = {1,1,1,2,2,3}; // sort the array before proceeding.Because in the else part count is set to zero.
//If the array is unsorted then count will be reset in middle and will not retain the previous count.
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]==a[j])
{
count = count+1;
Numcounts[i] = count;
}
else{
count = 0;
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>A hashmap is a structure that maps a key (the hash) to a value.<br>\nIn your example you'd want the key to be the number and the value to be the count of each number.\nIf you are using a compiler that that supports C++0x, you can add </p>\n\n<pre><code>#include <unordered_map>\n</code></pre>\n\n<p>and then modify the body of your main loop to something like:</p>\n\n<pre><code>std::unordered_map<int, int> hashMap;\nfor(int i=0;i<n;i++)\n{\n int number = a[i];\n\n // check if this number is already in the map\n if(hashMap.find(number) != hashMap.end())\n {\n // it's already in there so increment the count\n hashMap[number] += 1;\n }\n else\n {\n // it's not in there yet so add it and set the count to 1\n hashMap.insert(number, 1);\n }\n}\n</code></pre>\n\n<p>I wrote this code down from memory so it might not even compile, although it should be straightforward to fix.</p>\n\n<p>As you can see we only run through the array once so you now have the O(n) complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T19:58:49.320",
"Id": "2506",
"Score": "1",
"body": "Even if you call your variable `hashMap`, `std::map` is a treemap and **not** a hashmap, making your code `O(n log n)`. The current C++ standard does not include a hashmap, but C++0x does under the name `unordered_map`. So if your compiler is recent enough, you can use `std::unordered_map`. Otherwise you can use boost."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T21:42:51.133",
"Id": "2508",
"Score": "0",
"body": "I didn't know that about std::map, thanks for the clarification."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T15:59:23.073",
"Id": "2531",
"Score": "0",
"body": "Now that you do know, it would be a good idea to correct the information in your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T19:51:18.013",
"Id": "1435",
"ParentId": "1434",
"Score": "3"
}
},
{
"body": "<p>If the array is sorted you do not need hashmaps to achieve O(n). If you have a random/unsorted array you can use hashmaps to achieve the purpose, see Paulo's answer for that. Note that sorting requires O(n log(n)).</p>\n\n<p>If you want to know how often each integer is in the original collection you will also need hashmaps, but if you only want to know <em>a</em> nonduplicate number in a sorted array the following code will work:</p>\n\n<pre><code>// N is the number of ints in sorted\nint nonduplicate(int sorted[], const int N){\n //To prevent segfaulting when N=1\n if(N==1){ return sorted[0]; };\n\n for(int i=0;i < N-1;i++){\n if(sorted[i] == sorted[i+1]){\n // Next number in collection is the same so the current number is not unique\n // Set i to the first location of the next different number\n do{\n i++;\n }while(i < N-1 && sorted[i] == sorted[i+1]);\n }else{\n // The next number is different so the current is unique\n return sorted[i];\n }\n }\n // Is the last number unique?\n if(sorted[N-1] != sorted[N-2]){\n return sorted[N-1];\n }\n // No unique numbers\n return -1; // Or some other value you reserve for it\n}\n</code></pre>\n\n<p>Note that this code is faster because it doesn't have the overhead of a hashmap and may stop before traversing the whole array, but does have the same big-O limit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T20:38:22.803",
"Id": "2507",
"Score": "0",
"body": "@paul : Thanks much.I had to change this part of insert and it worked. hashMap.insert(std::pair<int,int>(number,1)); I like the way how hashmaps take care of indexing and stuff automatically, instead of having the programmer worry abt that. I am not very good at working with indexing (:-)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T20:13:21.837",
"Id": "1436",
"ParentId": "1434",
"Score": "7"
}
},
{
"body": "<p>Since you are using C++ and not C, there are a few things that you could clean up.</p>\n\n<p>First of all, your code leaks memory: you are <code>new</code>ing memory but you are not <code>delete</code>ing. In order to avoid this manual memory management, you should use the <code>std::vector</code> class template instead of <code>new[]</code>.</p>\n\n<p>Furthermore, <code>stdio.h</code> is a legacy C header. Use <code>cstdio</code> in C++. But in fact, your code doesn’t need that header anyway.</p>\n\n<p>A hash map implementation is available in the <code>std::tr1</code> namespace. If your compiler supports this (modern compilers do), the following code works:</p>\n\n<pre><code>#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nint main() {\n std::unordered_map<int, unsigned> occurrences;\n int a[6] = { 1, 1, 1, 2, 2, 3 };\n unsigned const size = sizeof a / sizeof a[0];\n\n // First pass: count occurrences.\n for (unsigned i = 0; i < size; ++i)\n ++occurrences[a[i]];\n\n // Second pass: search singleton.\n for (unsigned i = 0; i < size; ++i)\n if (occurrences[a[i]] == 1)\n std::cout << a[i] << \" only occurred once.\" << std::endl;\n}\n</code></pre>\n\n<p>(To enable TR1 support on GCC, pass the <code>std=c++0x</code> flag to the compiler.)</p>\n\n<p>Point of interest: the first pass works because the values inside the unordered map (= hash map) are initialised with the default value, 0. We are using this fact to increment the values directly without bothering to check whether the value existed in the map beforehand. This makes the code more concise and is actually also more efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T16:38:38.840",
"Id": "36617",
"Score": "0",
"body": "how about `for(auto i : a)` if you have range based for loops, or if not: `for(auto i = std::begin(a); i != std::end(a); ++i)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T16:40:39.913",
"Id": "36618",
"Score": "0",
"body": "Why are you using `unsigned`? It's implied to be `unsigned int` right? Most correct would be `size_t` since that's the maximum occurrence count you could conceivably have without going out of memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T16:51:34.693",
"Id": "36619",
"Score": "0",
"body": "@Dave I’m using `unsigned` because negative counts simply don’t make sense. I only use `std::size_t` when explicitly referring to sizes or offsets of container classes, not when counting natural entities. It wouldn’t be *wrong* here to use either, per se."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T17:18:32.020",
"Id": "36622",
"Score": "0",
"body": "I meant why are you using `unsigned` instead of `unsigned int`? In this case it represents the count in an array, which does fit the bill for what `size_t` is for. It's the type of the count of an array. If you used `std::array` instead of `int[]` you could use `std::array::size_type` but that's guaranteed to be `size_t`... just like real arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-11T19:12:56.710",
"Id": "36640",
"Score": "0",
"body": "@Dave When I wrote this answer I was working on a project where the convention was to use `unsigned` instead of `unsigned int`. Since either is valid it doesn’t really matter. I now use `unsigned int` again in my own code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:34:17.537",
"Id": "61543",
"Score": "0",
"body": "I agree with @Dave, use std::array and a range based for loop if possible and you can let the compiler worry about the bounds checking for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T23:46:57.840",
"Id": "61545",
"Score": "0",
"body": "@YoungJohn That answer predates proper C++11 supporting compilers. Nowadays – yes, of course! In fact, [I’ve **completely** banished non-range `for` loops from my code](https://github.com/klmr/cpp11-range)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T16:21:19.080",
"Id": "1455",
"ParentId": "1434",
"Score": "4"
}
},
{
"body": "<p>Actually, you could do it in \\$O(N)\\$ using XOR to bitshift things.</p>\n\n<p>This will do it will less overhead and much faster (in java, since that is what I know):</p>\n\n<pre><code>public static void main(String... args) {\n int[] x = new int[] { 5,7,4,9,5,7,4 };\n int result = 0;\n for (int i=0;i<x.length;i++) {\n result ^= x[i];\n }\n System.out.println(\"result:\"+result);\n}\n</code></pre>\n\n<p>Good article on this here: <a href=\"http://kaipakartik.amplify.com/\" rel=\"nofollow noreferrer\">http://kaipakartik.amplify.com/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-19T04:58:20.517",
"Id": "141162",
"Score": "2",
"body": "This only works if elements are repeating only twice. In other cases it fails (Coz It is XOR operator). The link is Also broken now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-26T02:13:13.737",
"Id": "317184",
"Score": "0",
"body": "FYI, the link is broken now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-22T17:54:29.870",
"Id": "3062",
"ParentId": "1434",
"Score": "3"
}
},
{
"body": "<p>This can easily be done in \\$O(n)\\$: run through the array and find the largest value. Create a vector of this size initialized to zeros. Run through the array and increment the element in the vector indexed by each value by one. Finally, run through the vector and find the element equal to one; the offset of this element in the vector is your answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-07T17:39:17.483",
"Id": "190151",
"Score": "0",
"body": "Using an array is a bad idea. It would be O(_n_) time, but also O(_m_) space, where _m_ is the maximum value. The maximum could be 4 billion. Numbers could also be negative."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-07T16:59:20.597",
"Id": "104053",
"ParentId": "1434",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-24T19:23:03.027",
"Id": "1434",
"Score": "7",
"Tags": [
"c++",
"array"
],
"Title": "Find the non repeating number in the integer array"
} | 1434 |
<p>I have this for loop for creating a list of variables:</p>
<pre><code>vars <- c( 'beta.o', 'sd.y')
for (x in c('ghs', 'site', 'trt')) {
if(model.parms[[x]] == 1) {
data <- data[, which(names(data) != x)]
} else {
data <- data
if(x!='ghs') {
vars <- c(vars, paste('sd.', x, sep = ''))
}
m <- min(model.parms[[x]], 5)
for (i in 1:m) {
if(i == 1 && x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
if (i > 1) {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
}
}
}
</code></pre>
<p>It has been bothering me terribly, and I have failed the last two times I have tried to replace it, although conceptually it should be able to be written in a few lines. Any advice?</p>
| [] | [
{
"body": "<p>This bit:</p>\n\n<pre><code>for (i in 1:m) {\n if(i == 1 && x == 'site') {\n vars <- c(vars, 'beta.site[1]')\n }\n if (i > 1) {\n vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))\n }\n}\n</code></pre>\n\n<p>Says handle the first pass differently from all the others. So I would replace it with this:</p>\n\n<pre><code>if (x == 'site') {\n vars <- c(vars, 'beta.site[1]')\n}\nfor (i in 2:m) {\n vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T22:14:03.747",
"Id": "1439",
"ParentId": "1437",
"Score": "3"
}
},
{
"body": "<p>The big mistake in your code is you are dynamically growing your vectors. For example, compare</p>\n\n<pre><code>x = NULL \nfor(i in 1:100000)\n x = c(x, i)\n</code></pre>\n\n<p>with </p>\n\n<pre><code>x = numeric(100000)\nfor(i in 1:100000) \n x[i] = i \n</code></pre>\n\n<p>The other key point is that <code>paste</code> function can be vectorised. So, </p>\n\n<pre><code>for (i in 1:m) {\n if(i == 1 && x == 'site') {\n vars <- c(vars, 'beta.site[1]')\n }\n if (i > 1) {\n vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))\n }\n }\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code>if(x == 'site') {\n vars <- c(vars, 'beta.site[1]')\n }\nvars = c(vars, paste('beta.', x, '[', i, ']', sep=''))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-15T10:00:21.623",
"Id": "8991",
"ParentId": "1437",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-24T21:13:38.340",
"Id": "1437",
"Score": "2",
"Tags": [
"r"
],
"Title": "How to simplify nested conditional for loop in R?"
} | 1437 |
<blockquote>
<p>A function f is defined
by the rule that f(n) = n if n < 3 and
f(n) = f(n-1) + 2f(n-2) + 3f(n-3) if
n>=3. Write a recursive and an
iterative process for computing f(n).</p>
</blockquote>
<p>I wrote the following:</p>
<pre><code>(define (f_r n)
; recursive
(cond ((< n 3) n)
(else (+ (f_r (- n 1))
(* 2 (f_r (- n 2)))
(* 3 (f_r (- n 3)))))))
(define (f_i n)
;iterative
(f_i-prime 1 0 0 n))
(define (f_i-prime n n-1 n-2 count)
(cond ((= count 0) n)
((f_i-prime (+ n n-1 n-2)
(+ n n-1)
n-1
(- count 1)))))
</code></pre>
<p>What do you think?</p>
<p><strong>EDIT 1:</strong> Since my first iterative solution was erroneous, here is a corrected version:</p>
<pre><code>(define (f_i n)
;iterative
(f_i-prime 2 1 0 n))
(define (f_i-prime f_x+2 f_x+1 f_x n-x)
(cond ((= n-x 0) f_x)
((f_i-prime (+ f_x+2 (* 2 f_x+1) (* 3 f_x) )
f_x+2
f_x+1
(- n-x 1)))))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T02:41:09.400",
"Id": "2514",
"Score": "0",
"body": "Do you mind if I ask where you're getting these puzzles from? Based on the frequency with which one-letter function names/variables are defined, I'm assuming it's either a math book or a set of Haskell exercises. Have you considered something [a bit](http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992) more [Lisp](http://www.paulgraham.com/onlisptext.html)/[Scheme](http://mitpress.mit.edu/sicp/) oriented, if your goal is learning those languages specifically? This is ok for getting a grasp on theory, but I hope you're not planning on coding similarly out in the wild."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T03:21:42.767",
"Id": "2515",
"Score": "0",
"body": "@Inaimathi: The questions appear to come from SICP, which is quite Scheme-orientated if you ask me!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T03:45:57.873",
"Id": "2517",
"Score": "0",
"body": "That's a bit embarrassing; SICP is actually one of the ones I linked. To be fair, I skipped a bunch of it since I already watched [the lectures](http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/) by the time I started in on the book, but I honestly don't remember them putting in many single-letter function names."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T05:48:16.903",
"Id": "2546",
"Score": "0",
"body": "Thanks, guys - indeed I am using SICP right now. Do you mind if I ask you to elaborate on what you think could be improved about my coding style here?"
}
] | [
{
"body": "<p>Your iterative definition will not produce correct results for most values of n.</p>\n\n<p>When rewriting a pure recursive function as an iterative one, one needs to keep as many accumulators as there are base cases. In the iterative step, compute the next value, store it in the first accumulator, rotate the values of all remaining accumulators and decrement the loop variable.</p>\n\n<p>Here's an implementation in your style:</p>\n\n<pre><code>(define (f_i n)\n ;iterative\n ;initial values of accumulators are f(2) = 2, f(1) = 1 and f(0) = 0; loop variable is n.\n (f_i-prime 2 1 0 n))\n\n(define (f_i-prime f-x+2 f-x+1 f-x n-x)\n (cond ((= n-x 0) f-x) ; if n-x = 0, then n = x, so return f(x) = f(n).\n ((f_i-prime (+ f-x+2 (* 2 f-x+1) (* 3 f-x)) ; iterative step -- compute next value of f(x + 2);\n f-x+2 ; ... rotate all other accumulators;\n f-x+1\n (- n-x 1))))) ; ... and decrement loop variable.\n</code></pre>\n\n<p>One may incorporate the helper function within the main function using letrec as follows (this version differs slightly from the previous one in that the loop variable counts up from 0 to n):</p>\n\n<pre><code>(define (f-iterative n)\n (letrec\n ((f-aux\n (lambda (x f-x+2 f-x+1 f-x)\n (cond\n ((= x n) f-x)\n ((f-aux (+ x 1) (+ f-x+2 (* 2 f-x+1) (* 3 f-x)) f-x+2 f-x+1))))))\n (f-aux 0 2 1 0)))\n</code></pre>\n\n<p>One may also use the do expression to write the iterative version as follows:</p>\n\n<pre><code>(define (f-iterative n)\n (do\n ((x 0 (+ x 1))\n (f-x+2 2 (+ f-x+2 (* 2 f-x+1) (* 3 f-x)))\n (f-x+1 1 f-x+2)\n (f-x 0 f-x+1))\n ((= x n) f-x)))\n</code></pre>\n\n<p>As to your recursive definition, you may wish to <a href=\"http://community.schemewiki.org/?memoization\" rel=\"nofollow\">memoize</a> the results in order to decrease your algorithm's complexity, which is currently in O(3 ^ n). <a href=\"http://community.schemewiki.org/?memoization\" rel=\"nofollow\">Memoization</a> will improve that to linear complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T06:04:56.683",
"Id": "2547",
"Score": "0",
"body": "Thanks for your help! I'm not familiar with _letrec_ and _do_. Can you show me where to look up their usage?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T02:59:04.720",
"Id": "2570",
"Score": "0",
"body": "@jaresty: Check out chapters [four](http://www.scheme.com/tspl3/binding.html) and [five](http://www.scheme.com/tspl3/control.html) from the book The Scheme Programming Language by Dybvig."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T09:44:26.760",
"Id": "1446",
"ParentId": "1440",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1446",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T01:24:45.397",
"Id": "1440",
"Score": "1",
"Tags": [
"recursion",
"lisp",
"scheme",
"iteration"
],
"Title": "Both an Iterative and a Recursive f(x)"
} | 1440 |
<blockquote>
<pre><code> 1
1 1
1 2 1
1 3 3 1
</code></pre>
</blockquote>
<p>What do you think of this solution for computing Pascal's triangle?</p>
<pre><code>(define (pascal row column)
(cond ((or (= row column) (= 1 column)) 1)
(else (+ (pascal (- row 1) (- column 1))
(pascal (- row 1) column)))))
</code></pre>
| [] | [
{
"body": "<p>You may use <a href=\"http://community.schemewiki.org/?memoization\" rel=\"nofollow\">memoization</a> to reduce your algorithm's complexity from O(2 ^ n) to O(n ^ 2).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T09:52:38.283",
"Id": "1447",
"ParentId": "1441",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T02:33:49.953",
"Id": "1441",
"Score": "3",
"Tags": [
"lisp",
"scheme"
],
"Title": "Pascal's triangle"
} | 1441 |
<p>I've always seen the <code>IPrincipal</code> and <code>IIdentity</code> interfaces separately, but I haven't seen any compelling reason for it, so I have my own interface that combines the two:</p>
<pre><code>public interface IUser : System.Security.Principal.IIdentity, System.Security.Principal.IPrincipal {
string Role { get; set; }
}
</code></pre>
<p>Then I implement the interface as:</p>
<pre><code>public class User : IUser {
public string Role { get; set; }
public System.Security.Principal.IIdentity Identity {
get { return this; }
}
public string AuthenticationType {
get { throw new System.NotImplementedException(); }
}
public bool IsAuthenticated {
get { throw new System.NotImplementedException(); }
}
public string Name {
get { throw new System.NotImplementedException(); }
}
public bool IsInRole(string role) {
throw new System.NotImplementedException();
}
}
</code></pre>
<p>Does this <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow">smell</a>? Do I have a security issue here?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T11:35:07.237",
"Id": "2519",
"Score": "0",
"body": "I doubt this is `code review`. It looks more like a design question."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T12:28:51.053",
"Id": "2520",
"Score": "0",
"body": "@Snowbear: Why wouldn't it be? Design is often discussed here anyhow."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T12:46:04.303",
"Id": "2521",
"Score": "3",
"body": "Well... it's code that I wanted reviewed... I figured Code Review was the perfect place. :]"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T14:02:35.467",
"Id": "2526",
"Score": "1",
"body": "I mean that the only thing worth discussing I see here is `IUser: IPrincipal, IIdentity` (we can also review `NotImplementedException` throwing - I prefer `NotSupportedException` - but I doubt this is what you want to discuss). And the question `should I implement both interfaces in one place?` should not be here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:14:02.990",
"Id": "2536",
"Score": "0",
"body": "Specific code design is on-topic here. Abstract is not."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T13:22:05.890",
"Id": "2578",
"Score": "0",
"body": "My production code doesn't throw the exceptions. I just created a quick example to the makeup of the class."
}
] | [
{
"body": "<p>These interfaces are meant to <a href=\"http://msdn.microsoft.com/en-us/library/ftx85f8x.aspx\" rel=\"nofollow\">work with the user’s identity information</a>.</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.aspx\" rel=\"nofollow\"><code>IIdentity</code></a>: An identity object represents the user on whose behalf the code is running.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.aspx\" rel=\"nofollow\"><code>IPrincipal</code></a>: A principal object represents the security context of the user on whose behalf the code is running, including that user's identity (<code>IIdentity</code>) and any roles to which they belong.</li>\n</ul>\n\n<p>Just from looking at the documentation, your implementation looks weird. You are permanently linking the identity of a user to a fixed role. As far as I understand it, <a href=\"http://msdn.microsoft.com/en-us/library/dc8ztsad.aspx\" rel=\"nofollow\">a user might operate on different roles at different times</a>. This provides for better encapsulation. The main 'design' problem I see is your identity now contains an identity, which contains an identity, with inside, ... an identity, and there ... you get the point.</p>\n\n<p>Futhermore, perhaps the default implementations of <code>IIdentity</code> and <code>IPrincipal</code> can already help you? Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.aspx\" rel=\"nofollow\">generic implementations</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T13:51:25.767",
"Id": "2524",
"Score": "0",
"body": "The stub code above doesn't show it, but my implementation does support a user being in multiple roles; `Roles` is a better name for the property. \n\nIn my implementation, I have a `User` class that is tied directly to the database. I have a struct named `UserInfo` that implements the `IUser` interface and is constructed from the `User` object. The `UserInfo` is stored in the session (this is a web app), and is assigned to `Request.User` during `Request.BeginRequest`.\n\nI guess I don't understand why I wouldn't want a class to represent both the user and their current security context."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T14:00:25.520",
"Id": "2525",
"Score": "0",
"body": "@Andy: Fair, but isn't that exactly what `IPrincipal` does, and why IPrincipal contains an `IIdentity`?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T14:12:04.373",
"Id": "2527",
"Score": "1",
"body": "@Andy: If you really do want it in one class, I suggest only implementing IPrincipal, and initializing the identity in your class instead of passing it as a parameter."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T22:36:53.987",
"Id": "2562",
"Score": "0",
"body": "As @Steven Jeuris notes, IPrincipal has a IIdentity. There might be a set of cases where something might both 'is a' and 'has a' IIdentity (duality of identities, perhaps for handling delegation or something of similar fashion and even then I might handle that scenario a bit differently), but I don't think that structure and behavior is what you are aiming for here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T13:26:16.600",
"Id": "1451",
"ParentId": "1442",
"Score": "2"
}
},
{
"body": "<p>While there are circumstances where you need to decouple the Principal from the Identity, in many applications this is not the case, and the distinction will only complicate the code. The way security is best handled in an application depends very much on the individual needs of the particular app. </p>\n\n<p>Martin Fowler's article <a href=\"http://martinfowler.com/apsupp/roles.pdf\" rel=\"nofollow noreferrer\">Dealing with Roles</a> provides an in depth analysis on to the different patterns that can be used to implement role-based security, and the indications of necessity for each pattern. </p>\n\n<p>In general, you can't make an assumption that a solution that separates the principal from the identity is the optimal solution for all applications. I have encountered many scenarios where it was unnecessary and added nothing but additional classes. In that case, it is better to merge the two interfaces. </p>\n\n<p>Furthermore, these are <strong>interfaces</strong> not <strong>classes</strong>. An <strong>interface denotes a \"has a\"</strong> relationship between the instance and the definition, where as a <strong>class denotes an \"is a\"</strong> relationship. An instance of a <code>User</code> in the OP's example is an object that has both an Identity and a Principal (Security Context). You can always break things down to further levels of complexity, but <strong>if the application functionality doesn't indicate a reasonable need to separate the class, then Why would you do it?</strong> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T00:18:27.477",
"Id": "2803",
"Score": "0",
"body": "_\"interface denotes a \"has a\" relationship\"_? Here I was thinking interfaces define a 'can/is' relationship, and composition defines a 'has a' relationship. I do agree with your other points, hence my reply in a comment on my answer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T01:56:54.450",
"Id": "2805",
"Score": "0",
"body": "@Steven, a \"can do\" relationship, is applicable to an interface. I suppose that a class that implements and interface has a \"has a\" relationship to the interface's properties and a \"can do\" relationship to the interface's methods. Composition seems to me like part of the implementation as opposed to part of the definition. Check out the answer in this SO post http://stackoverflow.com/questions/56867/interface-vs-base-class"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T02:32:38.673",
"Id": "2806",
"Score": "0",
"body": "@smartcaveman: I'm talking about [Class Diagram](http://en.wikipedia.org/wiki/Class_diagram) definitions here ... Stating that _\"interfaces denotes 'has a'\"_ is very confusing and seems incorrect to me. Apparently interfaces should be interpreted as 'realizes'. Isn't it the other way around, composition is part of the definition as opposed to part of the implementation?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T02:44:33.660",
"Id": "2807",
"Score": "0",
"body": "P.s.: Definition disagreements or not, the problem stated in my answer remains. In your words: An instance of `User` has both an `Identity` and a `Principal`, and `Principal` has an `Identity`. As stated in my comment on my answer, I believe only implementing `IPrincipal` is the only logical design when you want to bundle the two together."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T02:48:33.200",
"Id": "2808",
"Score": "0",
"body": "@Steven, I think you are confusing associations and [inheritance](http://en.wikipedia.org/wiki/Inheritance_in_object-oriented_programming). In the OP's example, the User is an object that has an identity (`IIdentity`) and a security context (`IPrincipal`). The `IPrincipal` also has an Identity as a property. This could be implemented by composition (as in your suggestion) or by polymorphism (as in the OP's code)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T02:50:09.937",
"Id": "2809",
"Score": "0",
"body": "@Steven, If you think there is only one logical design, I think reviewing the Fowler article I linked to would be tremendously helpful for you."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T03:02:34.933",
"Id": "2810",
"Score": "0",
"body": "@smartcaveman: I'm not arguing the possibilities of different designs, but the design is already given no? As defined by the interfaces. By design, IPrincipal has an IIdentity. Implementing both is just confusing IMHO, and not following the given design."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T03:08:08.230",
"Id": "2811",
"Score": "1",
"body": "@Steven, (1) The class design is not already made. The interface design is. If they were meant to always be separate classes, then they would be abstract classes instead of interfaces. (2) By design, `IPrincipal` has an `IIdentity` property. That does not necessarily mean that the Principal is different than the Identity. There is nothing wrong with an `IPrincipal` implementation that also implements `IIdentity`, and the implementation of `IIdentity IPrincipal.Identity{get{return this;}}`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T03:09:47.760",
"Id": "2813",
"Score": "0",
"body": "Also, notice how there is no setter on the `IPrincipal` interface? This means that the `IPrincipal` implementation is responsible for determining how the `IIdentity` object is resolved. If there were a setter, then you would have a solid case for always favoring composition over polymorphism....but there isn't.... so, you don't."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-04-01T20:27:15.203",
"Id": "1616",
"ParentId": "1442",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "1616",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T05:12:48.417",
"Id": "1442",
"Score": "11",
"Tags": [
"c#",
"security"
],
"Title": "IIdentity and IPrincipal Interfaces"
} | 1442 |
<p>From SICP's 1.24: (<a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html" rel="nofollow">Exponentiation</a>) </p>
<p>(you may need to click through and read ~1 page to understand)</p>
<blockquote>
<p>Exercise 1.16. Design a procedure
that evolves an iterative
exponentiation process that uses
successive squaring and uses a
logarithmic number of steps, as does
fast-expt. (Hint: Using the
observation that (<em>b</em><sup><em>n</em>/2</sup>)<sup>2</sup> = (<em>b</em><sup>2</sup>)<sup><em>n</em>/2</sup>,
keep, along with the exponent <em>n</em> and
the base <em>b</em>, an additional state
variable <em>a</em>, and define the state
transformation in such a way that the
product <em>a b<sup>n</sup></em> is unchanged from state
to state. At the beginning of the
process <em>a</em> is taken to be 1, and the
answer is given by the value of <em>a</em> at
the end of the process. In general,
the technique of defining an invariant
quantity that remains unchanged from
state to state is a powerful way to
think about the design of iterative
algorithms.)</p>
</blockquote>
<p>I wrote the following solution:</p>
<pre><code>(define (even n) (= (remainder n 2) 0))
(define (fast-expt b n)
(fast-expt-iter b b n))
(define (fast-expt-iter a b n)
(cond ((= n 1) a)
((even n) (fast-expt-iter (* a b) b (/ n 2)))
(else (fast-expt-iter (* a b) b (- n 1)))))
</code></pre>
<p>Do you think my solution is correct? Moreover, what do you think about my code?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-19T02:59:17.320",
"Id": "20605",
"Score": "1",
"body": "`even?` is a Scheme builtin, so you should not define your own version. :-) Also, your bottom version isn't iterative."
}
] | [
{
"body": "<p>Your implementation will not produce correct results in general because your recursive definitions are erroneous.</p>\n\n<p>One should note that in case n = 0, result is 1. In case of even n (or n = 2 i), one may write b ^ n = (b * b) ^ i. In case of odd n (or n = 2 i + 1), one may write b ^ n = b * (b * b) ^ i. Here's an implementation (using if's instead of cond and folding the two recursive steps into one):</p>\n\n<pre><code>(define (fast-expt b n)\n (if (= n 0) 1\n (* (if (= (remainder n 2) 0) 1 b) (fast-expt (* b b) (quotient n 2)))))\n</code></pre>\n\n<p>To make this definition iterative, use the accumulator, a, that is initially 1. When n is even (n = 2 i), square b but keep a unchanged. This maintains the property b ^ n = a * (b ^ 2) ^ i. When n is odd (n = 2 i + 1), square b and multiply a by b. This maintains the property b ^ n = (a * b) * (b ^ 2) ^ i. Thus, we have:</p>\n\n<pre><code>(define (fast-expt b n)\n (fast-expt-iter 1 b n))\n\n(define (fast-expt-iter a b n)\n (if (= n 0) a\n (fast-expt-iter (* a (if (= (remainder n 2) 0) 1 b)) (* b b) (quotient n 2))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T03:59:45.317",
"Id": "2587",
"Score": "0",
"body": "This doesn't work for (fast-expt 2 2) - it returns 2, which should be 4, shouldn't it?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T05:35:07.650",
"Id": "2589",
"Score": "0",
"body": "@jaresty: You're absolutely right. I screwed up my recursive definition. =) I'm editing my answer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T07:03:36.930",
"Id": "2590",
"Score": "0",
"body": "Hmm... I'm a bit confused. The problem asked for an \"iterative solution,\" but I feel like the solution we arrived at is somehow more recursive than iterative. What do you think?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T07:34:10.480",
"Id": "2592",
"Score": "0",
"body": "@jaresty: Agreed. I forgot to include the iterative version. Edited it into the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T10:24:52.123",
"Id": "1448",
"ParentId": "1443",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1448",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T06:22:50.580",
"Id": "1443",
"Score": "3",
"Tags": [
"lisp",
"scheme"
],
"Title": "Iterative exponentiation process"
} | 1443 |
<p>Given the following task:</p>
<blockquote>
<p><strong>Exercise 1.17</strong></p>
<p>The exponentiation
algorithms in this section are based
on performing exponentiation by means
of repeated multiplication. In a
similar way, one can perform integer
multiplication by means of repeated
addition. The following multiplication
procedure (in which it is assumed that
our language can only add, not
multiply) is analogous to the expt
procedure:</p>
<pre><code>(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))
</code></pre>
<p>This algorithm takes a number of steps
that is linear in b. Now suppose we
include, together with addition,
operations double, which doubles an
integer, and halve, which divides an
(even) integer by 2. Using these,
design a multiplication procedure
analogous to fast-expt that uses a
logarithmic number of steps.</p>
</blockquote>
<p>I wrote this solution:</p>
<pre><code>(define (double a) (* a 2))
(define (halve a) (/ a 2))
(define (even n) (= (remainder n 2) 0))
(define (times a b)
(cond ((= 1 b) a)
((even b) (times (double a) (halve b)))
(else (times (+ a a) (- b 1)))))
</code></pre>
<p>What do you think?</p>
| [] | [
{
"body": "<p>Your implementation will not produce correct results in general.</p>\n\n<p>In the base case of b = 0, result should be 0. In the case of even b, result is double a times half b (which you have done correctly). In the case of odd b, result should be a + (double a times half (b - 1)).</p>\n\n<pre><code>(define (times a b)\n (cond ((= 0 b) 0)\n ((even b) (times (double a) (halve b)))\n (else (+ a (times (double a) (halve (- b 1)))))))\n</code></pre>\n\n<p>To make this definition iterative, add an accumulator, like so:</p>\n\n<pre><code>(define (times a b)\n (times-iter 0 a b))\n\n(define (times-iter acc a b)\n (cond ((= 0 b) acc)\n ((even b) (times-iter acc (double a) (halve b)))\n (else (times-iter (+ a acc) (double a) (halve (- b 1))))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T07:24:12.123",
"Id": "2591",
"Score": "0",
"body": "How would you write this as an iterative solution, as per exercise 1.18 on http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T07:39:40.400",
"Id": "2593",
"Score": "0",
"body": "@jaresty: Edited my answer to include an iterative solution."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T09:48:49.347",
"Id": "2595",
"Score": "0",
"body": "Can you explain the difference between recursive and iterative?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T18:53:30.623",
"Id": "2607",
"Score": "0",
"body": "@jaresty: Recursion is the process of solving a problem by restating it in terms of a smaller example of the same problem. This is usually done by calling a procedure from within itself, with arguments that tend toward the base cases, and passing back the results of the call in order to build a solution. Iteration is the process of rerunning a collection of statements with changing variables until a terminating condition is met. Iteration may be implemented in a number of ways: as a loop or, in the case of Scheme, as a tail-call optimized recursion."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T10:38:33.707",
"Id": "1449",
"ParentId": "1444",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T06:41:28.990",
"Id": "1444",
"Score": "1",
"Tags": [
"lisp",
"scheme"
],
"Title": "Multiplication in terms of addition"
} | 1444 |
<p>Just thinking if using code like this</p>
<pre><code><?php
abstract class helper
{
private static $_cycles = array();
public static function isOdd($v)
{
return (0 == ($v % 2)) ? false: true;
}
public static function isEven($v)
{
return !self::isOdd($v);
}
public static function cycle($odd, $even)
{
$trace = debug_backtrace();
$trace = $trace[0];
$cycle = crc32(serialize($trace));
if (!isset(self::$_cycles[$cycle]))
{
self::$_cycles[$cycle] = 1;
}
return (self::isOdd(self::$_cycles[$cycle]++)) ? $odd : $even;
}
}
</code></pre>
<p>for featues like this</p>
<pre><code><?php foreach ($data as $record): ?>
<p class="<?php echo helper::cycle('oddCss', 'evenCss'); ?>"><?php echo $record; ?></p>
<?php endforeach; ?>
</code></pre>
<p>is not overcoded</p>
<p>PS<br>
Easy of usage (by html/css coders) is more important then performance in this particular case</p>
<p>UPDATE:<br>
As @Geoffrey mentioned i didn't tell before that same 'oddCss', 'evenCss' pair may be used several times on one page (so basically within one request)</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:12:46.983",
"Id": "2535",
"Score": "0",
"body": "I'm guessing that the second code block is what the HTML/CSS people will need to write?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:26:36.490",
"Id": "2538",
"Score": "0",
"body": "@Michael that's right"
}
] | [
{
"body": "<p>Since this is a code review site, let me point out that the following is an abomination:</p>\n\n<pre><code>return (0 == ($v % 2)) ? false: true;\n</code></pre>\n\n<p>The constants are redundant. Much simpler:</p>\n\n<pre><code>return (0 != ($v % 2));\n</code></pre>\n\n<p>(The parentheses are also redundant but that’s unrelated.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:11:32.990",
"Id": "2534",
"Score": "1",
"body": "I like the parentheses, though. I think it clarifies the statement quite a bit."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T09:07:12.937",
"Id": "2550",
"Score": "3",
"body": "The original returned true for even, false for odd. The above reverses those. Try `return (bool) ($v % 2)` or if you don't like the case, `return ($v % 2 == 1)`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T09:35:34.490",
"Id": "2551",
"Score": "0",
"body": "@David Good call. I should have paid better attention."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T16:43:18.110",
"Id": "1456",
"ParentId": "1452",
"Score": "5"
}
},
{
"body": "<p>This is clearly over-engineered. The <code>isOdd</code> and <code>isEven</code> method are useless since they're just the result of <code>fmod($i, 2)</code></p>\n\n<p>I'm guessing you're using the crc part to keep track of specific cycles for $odd/$even, couples, but this is not needed. Instead, you can just hash the arguments and keep a counter for that hash.</p>\n\n<p>Last, I think static are an heresy, and I'd much like an instanciated helper.</p>\n\n<p>I would have written something like that, assuming <code>$odd</code> and <code>$even</code> are always strings (not tested):</p>\n\n<pre><code><?php\n\nclass helper\n{\n private $cycles = array();\n\n function cycle($odd, $even)\n {\n $hash = md5($odd.$even);\n\n if (!isset($this->cycles[$hash]))\n {\n $this->cycles[$hash] = 0;\n }\n\n return fmod($this->cycles[$hash]++, 2) ? $odd : $even;\n }\n}\n\n$helper = new helper();\n\n$helper->cycle('foo', 'bar');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:25:35.460",
"Id": "2537",
"Score": "0",
"body": "your solution fails when i need 2 or more cycles with the same $odd $even values on the same page"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:30:17.020",
"Id": "2539",
"Score": "0",
"body": "oh I see. you should have told that in your question :-) Anyway, with that in mind, I don't see another solution right now (but my other remarks still apply :p)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:34:30.490",
"Id": "2540",
"Score": "0",
"body": "Yea, my bad. Thanks for pointing that out (updated) and thanks for the tips also"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:15:37.560",
"Id": "1458",
"ParentId": "1452",
"Score": "1"
}
},
{
"body": "<p>Something a bit simpler (without logging):</p>\n\n<pre><code>class Cycler {\n $evenFlag = true;\n\n /* Returns the next value in an even/odd series */\n function next($odd, $even) {\n $evenFlag = !evenFlag;\n\n return $evenFlag? $even: $odd;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><?php Cycler cycler = new Cycler(); ?>\n<?php foreach ($data as $record): ?> \n <p class=\"<?php echo cycler.next('oddCss', 'evenCss'); ?>\"><?php echo $record; ?></p>\n<?php endforeach; ?>\n</code></pre>\n\n<p>You could also add a <code>reset()</code> if you wanted to use the <code>Cycler</code> multiple times.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T21:30:15.177",
"Id": "2543",
"Score": "0",
"body": "Just remember that when sth is simple for programmers (e.g. .next() .reset() methods) its not always easy for html/css coders"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T00:18:37.280",
"Id": "2545",
"Score": "0",
"body": "That is perhaps true for reset. I don't think next is too much of a challenge. However it isn't the most descriptive - maybe flip or switch? ideas..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T18:44:21.387",
"Id": "1459",
"ParentId": "1452",
"Score": "3"
}
},
{
"body": "<p>Well, using debug_backtrace for it (clearly not the fastest function in the town) is a huge overkill. What about passing id? Advantage, besides of performance, is that you can use the same counter in different places.</p>\n\n<p>Code:</p>\n\n<pre><code><?php\n\nabstract class helper\n{\n\n protected static $_cycles = array();\n\n public static function cycle($cycle_id, $odd, $even)\n {\n\n self::$_cycles[$cycle_id] = isset(self::$_cycles[$cycle_id]) ? !self::$_cycles[$cycle_id] : true;\n\n return self::$_cycles[$cycle_id] ? $odd : $even;\n }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><?php foreach ($data as $record): ?>\n <p class=\"<?php echo helper::cycle('mycycle', 'oddCss', 'evenCss'); ?>\"><?php echo $record; ?></p>\n<?php endforeach; ?>\n// Data from another source, but continuous display\n<?php foreach ($data2 as $record): ?>\n <p class=\"<?php echo helper::cycle('mycycle', 'oddCss', 'evenCss'); ?>\"><?php echo $record; ?></p>\n<?php endforeach; ?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T21:32:49.760",
"Id": "2544",
"Score": "0",
"body": "This solution is perfect and its quite similar to my first attempt which was passing array idx (`foreach ($data as $k => $v)`) and checking only odd/even. Passing simple $cycle_id is real compromise between backend and frontend programmers. Thanks for fresh look and great idea about this question!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T20:46:17.430",
"Id": "1463",
"ParentId": "1452",
"Score": "3"
}
},
{
"body": "<p>I think CodeIgniter has something like this (yup, the <a href=\"http://codeigniter.com/user_guide/helpers/string_helper.html\" rel=\"nofollow\"><code>alternator()</code></a> helper):</p>\n\n<pre><code>function Cycle()\n{\n static $i = 0;\n\n if (func_num_args() > 0)\n {\n return func_get_arg($i++ % func_num_args());\n }\n\n return $i = 0;\n}\n</code></pre>\n\n<p>Works for a variable number of arguments, which might be useful in certain scenarios.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T05:36:12.730",
"Id": "1469",
"ParentId": "1452",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "1463",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T15:06:29.313",
"Id": "1452",
"Score": "6",
"Tags": [
"php",
"functional-programming"
],
"Title": "Is this good approach to use debug functions for implementing features?"
} | 1452 |
<p>I am relatively new to JavaScript and JQuery. I wanted a Datepicker that has the following functionality:</p>
<ol>
<li>Weekends are not selectable </li>
<li>Non working days (bank holidays etc.) are not selectable </li>
<li>The first selectable day must be x number of full working days in the future, taking into account bank holidays and weekends </li>
</ol>
<p>I looked at few examples and came up with this (the date format is dd/mm):</p>
<pre><code>$(function() {
var holidays= [[3,1], [22,4], [25,4], [29,4], [2,5], [30,5], [29,8], [26,12], [27,12]];
var workingDayOffset = 10, selectedDate = new Date();
function nonWorkingDays(date) {
for (var j = 0; j < holidays.length; j++) {
if (date.getMonth() == holidays[j][1] - 1 && date.getDate() == holidays[j][0]) {
return [false, ''];
}
}
return [true, ''];
}
function beforeCurrentDate(date) {
if(date.getDate() === selectedDate.getDate() && date.getMonth() === selectedDate.getMonth() && date.getFullYear() === selectedDate.getFullYear())
{
return [true, ''];
}
return [date < selectedDate,''];
}
function nonAvailableDays(date) {
var noWeekend = $.datepicker.noWeekends(date), before = beforeCurrentDate(date), holiday = nonWorkingDays(date);
return [noWeekend[0] && before[0] && holiday[0], ''];
}
for(var i = 0; i < workingDayOffset; i++) {
selectedDate.setDate(selectedDate.getDate() + 1);
if(!nonAvailableDays(selectedDate)[0])
{
i--;
}
}
Date.prototype.formatDDMMYY=function(){
var dd = this.getDate(), mm = this.getMonth()+1, yyyy = this.getFullYear();
if(dd<10){
dd = '0' + dd;
}
if(mm<10){
mm = '0'+ mm;
}
return String(dd + "\/" + mm + "\/" + yyyy);
};
$( "#datepicker" ).val(selectedDate.formatDDMMYY());
$( "#datepicker" ).datepicker({ beforeShowDay: nonAvailableDays, dateFormat: 'dd/mm/yy', showOn: 'button', buttonText: "select", defaultDate: selectedDate,gotoCurrent: true}) ;
});
</code></pre>
<p>I am looking for a general critique of the code, but also there are a couple of things that I thought would be easier / cleaner:</p>
<ol>
<li><p>In beforeCurrentDate I wanted to do a check that the date was less than selectedDate, in terms of the whole date, not including the time component. Using <code>date > selectedDate</code> would return <code>false</code> even if the date component was the same, due to the time part. I thought about setting the time on the selected date, but then GMT offset came into play. It seemed to me that it should be easier, in the end I added a fudge that check just the date components for a match.</p></li>
<li><p>I am not sure adding <code>Date.prototype.formatDDMMYY</code> is the right way to go. Again, this felt like it should be more straight forward.</p></li>
</ol>
<p>I am interested to hear your thoughts on this.</p>
| [] | [
{
"body": "<p>for <strong>1)</strong></p>\n\n<pre><code>var today = new Date();\ntoday.setTime(0); // resets the time. (midnight)\n</code></pre>\n\n<p>I believe this will fix the date comparison issue</p>\n\n<p>for <strong>2)</strong></p>\n\n<p>It just sucks that there isn't a built-in for this sort of thing. I would suggest not putting it on the Date prototype just in case it conflicts with some other date function/library down the road. Its seems to be only a matter of preference though.</p>\n\n<p><em>(if you Google: <code>JavaScript format date</code> you'll see many other examples of formatting the date or <a href=\"https://stackoverflow.com/q/1056728/684890\">https://stackoverflow.com/q/1056728/684890</a> where there are a few alternatives suggested in case you want some more functionality. )</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-27T03:33:31.357",
"Id": "3139",
"ParentId": "1454",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "3139",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T15:30:33.643",
"Id": "1454",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "JQuery UI Datepicker with beforeShowDay function"
} | 1454 |
<p>I created a few forms for faculty members to nominate colleagues for awards. Many of the nominations require documentation to be submitted in order to validate the nomination. I created one form then modified it to fit the needs of many different award forms. I created it rather hastily and would like input as to how I may trim the fat and make the code more efficient.</p>
<p>One of the forms can be found <a href="http://pastebin.com/EuWERS4B" rel="nofollow">here</a>. Here's the code relevant to file uploading (starting at line 376 of the paste):</p>
<pre><code><!---Set file upload destination path to nominationUploads/firstname_lastname--->
<cfset destination = expandPath("./nominationUploads/#fname#_#lname#/")>
<!---If the destination directory does not exist, create it. This will be unique for each nominee.--->
<cfif not directoryExists(destination)>
<cfdirectory action="create" directory="#destination#">
</cfif>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="nominationLetter"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientNominationLetter = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameNomination = "nominationLetter"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameNomination)#">
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="curriculumVita"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientCurriculumVita = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameCurriculumVita = "curriculumVita"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameCurriculumVita)#">
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation = "recommendation"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation)#">
<cfif Len(form.recommendation2)>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation2"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation2 = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation2 = "recommendation2"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation2)#">
</cfif>
<cfif Len(form.recommendation3)>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation3"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation3 = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation3 = "recommendation3"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation3)#">
</cfif>
<cfif Len(form.recommendation4)>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation4"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation4 = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation4 = "recommendation4"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation4)#">
</cfif>
<cfif Len(form.recommendation5)>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation5"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation5 = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation5 = "recommendation5"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation5)#">
</cfif>
<cfif Len(form.recommendation6)>
<!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->
<cffile action="upload"
filefield="recommendation6"
accept="application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document"
destination="#destination#"
nameconflict="makeunique">
<!--- Create variable to reference the original document name and extension uploaded from client.--->
<cfset clientRecommendation6 = #file.ClientFile#>
<!---Create variable to reference renamed document. Retain orignal file extension.--->
<cfset renameRecommendation6 = "recommendation6"&"."&#cffile.clientFileExt#>
<!---Rename uploaded document using variable. Save renamed document to original destination.--->
<cffile action="rename"
source="#destination##File.ServerFile#"
destination="#destination##Trim(renameRecommendation6)#">
</cfif>
</cfif>
</code></pre>
| [] | [
{
"body": "<p>Considering that you're doing this:</p>\n\n<pre><code> <!---Upload document to the destination. Accept only MSWord, PDF, RTF and plain text files.--->\n <cffile action=\"upload\"\n filefield=\"recommendation4\"\n accept=\"application/msword, application/pdf, application/rtf, text/plain, application/vnd.ms-word.document.12, application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n destination=\"#destination#\"\n nameconflict=\"makeunique\">\n\n <!--- Create variable to reference the original document name and extension uploaded from client.--->\n <cfset clientRecommendation4 = #file.ClientFile#>\n <!---Create variable to reference renamed document. Retain orignal file extension.--->\n <cfset renameRecommendation4 = \"recommendation4\"&\".\"&#cffile.clientFileExt#>\n\n <!---Rename uploaded document using variable. Save renamed document to original destination.--->\n <cffile action=\"rename\"\n source=\"#destination##File.ServerFile#\"\n destination=\"#destination##Trim(renameRecommendation4)#\">\n</code></pre>\n\n<p>over and over and over again. I'd create a custom function to handle these steps for you. Any place you have something that needs to be dynamic, create an Argument for that value. Then you could replace the above code with something like this:</p>\n\n<pre><code>uploadDocument(destination = field = \"recommendation1\");\nuploadDocument(field = \"recommendation2\");\nuploadDocument(field = \"recommendation3\");\nuploadDocument(field = \"recommendation4\");\n</code></pre>\n\n<p>Then if you ever need to change how your file uploads are handled, you can just change the one function to make that happen.</p>\n\n<p>Good rule of thumb: any time you copy and paste a block of code, and then replace one or two strings, make it a function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-09T19:03:59.000",
"Id": "4437",
"Score": "0",
"body": "Excuse my ignorance, but would your suggestion by considered a user defined function? I have never accomplished this before so I am trying to figure out where to start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T17:04:49.100",
"Id": "4476",
"Score": "0",
"body": "The official documentation on `<cffunction>` is confusing. This page gives a simplified intro: http://www.communitymx.com/content/article.cfm?cid=AD0AD43C1BF789E6"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T20:20:46.780",
"Id": "1527",
"ParentId": "1460",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T18:23:00.543",
"Id": "1460",
"Score": "4",
"Tags": [
"form",
"network-file-transfer",
"coldfusion",
"cfml"
],
"Title": "Uploading multiple files for faculty nomination system"
} | 1460 |
<p>As much as I try, I cannot seem to get this Coffeescript code to look beautiful (I'd like to think it is possible). I have tried both Javascript and Coffeescript. Just to be clear, this code works fine, but it is hard to read, for reasons that I am unable to pinpoint.</p>
<p><strong>How can it be refactored, reorganized, and what changes to coding style can be made to make it more appealing to read?</strong></p>
<pre><code>define [
"plugins/ui/ui",
"./js/highlight"
], (ui, highlight) ->
editor = {}
jQuery ($) ->
# A widget to view source code.
$.widget 'core.editor',
_create: ->
$editor = $(this.element)
$editor
.addClass('editor')
.append($('<ul spellcheck="false" contenteditable> <li></li> </ul>'))
# Move the gutter along with the editable area.
this.lines().bind 'scroll', (event) ->
$this = $(this)
$this.siblings(".gutter").css(top: $this.scrollTop() * -1)
# Highlight the sourceview using the given language.
# The language's JSON rule file is loaded.
highlight: (language) ->
this.language = language
require ["text!plugins/editor/js/#{ language }.json"], (json) =>
this._rules = JSON.parse(json)
return
# Update the `left` of the `<ul>` based on the gutter width.
# Each time the number of digits in the gutter changes, it becomes wider or
# narrower, and the editor needs the shift accordingly.
updateGutterWidth: () ->
# The `8` is the gutter's left padding.
this.lines().css(left: this.gutter().width() + 8)
# Add or remove line numbers if the number of lines has changed.
# `change` is a modification the the line count (In case the character was not yet
# typed).
updateLineNumbers: (change = 0) ->
$gutter = this.gutter()
count = this.lines().children("li").length
current = $gutter.children("span").length
count += change
# Add lines
if (count > current)
for i in [current..(count - 1)]
ele = document.createElement("span")
ele.innerText = "#{ i + 1 }"
$gutter[0].appendChild(ele)
# Remove lines
else if (current > count)
for j in [count..(current - 1)]
$gutter.children("span:last-child").remove()
this.updateGutterWidth() if current != count
return
# Set whether or not the gutter should be visible.
lineNumbers: (bool) ->
if bool == true and !this.number
$(this.element)
.prepend('<div class="gutter"></div>')
this.lines()
.css(left: 20)
this.updateLineNumbers()
else if bool == false and this.number
this.gutter().remove()
$(this.element)
.css(left: 1)
this.number = bool
# Return the gutter (a jQuery object).
gutter: () ->
this._gutter ?= $(this.element).children("div.gutter")
return this._gutter
# Return a jQuery `<ul>`. Each `<li>` is a line of the source viewer.
lines: ->
return $(this.element).children('ul')
# A hash of syntax highlighting rules.
rules: ->
return this._rules
# Re-highlight the text.
$(".editor > ul").live 'keyup', (event) ->
# 13: Enter
# 37, 38, 39, 40: Arrow Keys
# 33, 34: Page up / down
# 16, 17, 18, 91: Shift, Ctrl, Alt, Meta
# 35, 36: Home / end
if !(event.which in [13, 37, 38, 39, 40, 33, 34, 16, 17, 18, 91, 35, 36]) and !event.altKey and !event.ctrlKey
# Prevent an annoying error when backspacing to the beginning of a line.
selection = window.getSelection()
# Store the cursor position before highlighting.
cursorPos = selection.getRangeAt(0)
if cursorPos.getClientRects()[0]
clickx = cursorPos.getClientRects()[0].left
clicky = cursorPos.getClientRects()[0].top
# Highlight
$li = $(selection.focusNode).closest("li")
rules = $li.closest(".editor").editor('rules')
highlight.highlight($li, rules)
# Restore cursor position.
cursorPos = document.caretRangeFromPoint(clickx, clicky)
window.getSelection().addRange(cursorPos)
# Line numbering update.
$(".editor > ul").live 'keydown', (event) ->
# Redo line numbering for Enter, Backspace, Delete.
if (event.which in [13, 8, 46])
$this = $(this)
newline = switch event.which
when 13 then 1
when 8 then -1
else 0
$this.parent().editor('updateLineNumbers', newline)
# Correction
setTimeout(() ->
$this.parent().editor('updateLineNumbers', 0)
, 300)
# ##################### MAIN ##########################
$(".frame").frame('tabs').last().tab("content")
.append("<div id='sourceview'></div>")
$("#sourceview")
.css
position: 'absolute'
left: 1
right: 1
top: 1
bottom: 1
.editor()
.editor('theme', 'plugins/editor/themes/idlefingers.css')
.editor("highlight", "javascript")
.editor("lineNumbers", true)
return editor
</code></pre>
| [] | [
{
"body": "<p>Here are some simple suggestions:</p>\n\n<ol>\n<li>Put some spaces in between lines of code. Some whitespace will make things easier to read</li>\n<li>I noticed you are using two spaces for indentation. In general, four spaces (or a tab) makes for more readable code</li>\n<li>Don't break lines on chained methods unless you have a ton of them. For example, $(this.element).css(left: 1) can all go on one line no problem. If you have more than 2 or 3, placing each chained method on a new line is a good idea.</li>\n<li>Easy on the comments. Commenting your code is good, but too much writing and it inhibits the readability of your code. If you have to write a lot of stuff, put it in your documentation instad. For example, you shouldn't include the key bindings of all those numbers.</li>\n<li><p>Rather than pass a long string as an argument to a function, store it in a local variable on the preceding line, then pass the variable. Instead of:</p>\n\n<p>$(this).html('bigass html string');</p>\n\n<p>do this:</p>\n\n<p>htmlStr = 'bigass html str\";</p>\n\n<p>$(this).html(htmlStr);</p></li>\n<li><p>Take advantage of coffeescript's array syntax</p>\n\n<p>keys = [<br>\n 13 <br>\n 37, 38, 39, 40<br>\n 33, 34<br>\n 16, 17, 18, 91<br>\n 35, 36<br>\n]</p></li>\n<li>Use @property, which coffeescript makes available as shorthand for this.property</li>\n<li>Try programming with classes, and keeping as much of your jQuery event bindings in a separate area of your code. That way you can keep all of the $'s and other jQuery junk out of the code that actually makes your app work. Organizing your code into a structured class hierarchy will introduce some much-needed modularity to your coding. Breaking up chunks of commonly used code into reusable modules will make things easier to read and encourage best practices.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T07:11:38.553",
"Id": "1875",
"ParentId": "1462",
"Score": "8"
}
},
{
"body": "<p>One more thing. I almost always rewrite my own version of setTimeout and setInterval when using CoffeeScript, so I can use a cleaner syntax when callbacks are the last argument.</p>\n\n<pre>\n<code>\nafter = (ms, cb) -> setTimeout cb, ms\nevery = (ms, cb) -> setInterval cb, ms\n\n\n// that way, instead of this\nsetTimeout(() ->\n doSomething()\n doMore()\n), 100)\n\n\n// you can use this\nafter 100, () ->\n doSomething()\n doMore()\n\n</code>\n</pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T09:59:42.440",
"Id": "2279",
"ParentId": "1462",
"Score": "12"
}
},
{
"body": "<p>Yeah, coffeescript doesn't really improve method chaining, of which jQuery is so fond. A couple of tricks. First, remember how powerful destructuring is</p>\n\n<p>e.g.</p>\n\n<pre><code> if cursorPos.getClientRects()[0]\n clickx = cursorPos.getClientRects()[0].left\n clicky = cursorPos.getClientRects()[0].top\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>if r = cursorPos.getClientRects()[0]\n {left, top} = r\n</code></pre>\n\n<p>also bear in mind</p>\n\n<pre><code> @gutter\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code> this.gutter\n</code></pre>\n\n<p>and</p>\n\n<pre><code> highlight: (language) ->\n this.language = language\n</code></pre>\n\n<p>could be written</p>\n\n<pre><code> highlight: (@language) ->\n</code></pre>\n\n<p>Finally, consider the use of closures for something you keep doing, unless performance is <em>really</em> critical.</p>\n\n<p>e.g.</p>\n\n<pre><code>$this.parent().editor('updateLineNumbers', newline)\nsetTimeout(() ->\n $this.parent().editor('updateLineNumbers', 0)\n , 300)\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>updateLineNumbers = (p) -> $this.parent().editor 'updateLineNumbers', p\nupdateLineNumbers newLine\nafter 300, () -> updateLineNumbers 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-07T18:47:21.663",
"Id": "3333",
"ParentId": "1462",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "3333",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T20:40:59.300",
"Id": "1462",
"Score": "11",
"Tags": [
"javascript",
"jquery",
"jquery-ui",
"coffeescript"
],
"Title": "Coffeescript beautification and refactoring"
} | 1462 |
<p>This code comes from a <a href="http://wordpress.org/support/topic/plugin-vote-it-up-show-top-voted-post-in-index-page" rel="nofollow">Wordpress plugin's forum</a> called Vote it Up.
It sort posts by vote. A lotof people say that there is more code than is needed.
So I was wondering if someone have any idea about how to clean it a bit.</p>
<p><strong>votingfunctions.php:</strong></p>
<pre><code>function ShowPostByVotes() {
global $wpdb, $voteiu_databasetable;
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
//Set a limit to reduce time taken for script to run
$upperlimit = get_option('voteiu_limit');
if ($upperlimit == '') {
$upperlimit = 100;
}
$lowerlimit = 0;
$votesarray = array();
$querystr = "
SELECT *
FROM $wpdb->posts
WHERE post_status = 'publish'
AND post_type = 'post'
ORDER BY post_date DESC
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
//Use wordpress posts table
//For posts to be available for vote editing, they must be published posts.
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME) or die(mysql_error());
//Sorts by date instead of ID for more accurate representation
$posttablecontents = mysql_query("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT ".$lowerlimit.", ".$upperlimit."") or die(mysql_error());
$returnarray = array();
while ($row = mysql_fetch_array($posttablecontents)) {
$post_id = $row['ID'];
$vote_array = GetVotes($post_id, "array");
array_push($votesarray, array(GetVotes($post_id)));
}
array_multisort($votesarray, SORT_DESC, $pageposts);
$output = $pageposts;
return $output;
}
</code></pre>
<p><strong>index.php:</strong></p>
<p>
<pre><code>$pageposts = ShowPostByVotes();
?>
<?php if ($pageposts): ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
</code></pre>
<p>Attention! Code above is something like:</p>
<pre><code><?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
</code></pre>
<p>so in foreach loop you can use statements like in standard "The Loop" for example the_content, the_time().
To end this add</p>
<pre><code><?php endforeach; ?>
<?php else : ?>
<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php include (TEMPLATEPATH . "/searchform.php"); ?>
<?php endif; ?>
</code></pre>
<p><strong>EDIT:</strong></p>
<p>How I run a custom loop:</p>
<pre><code> <?php $custom_posts = new WP_Query(); ?>
<?php $custom_posts->query('category_name=Pictures'); ?>
<?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?>
<div class="content-block-2">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_content(); ?></a>
</div>
<?php endwhile; ?>
</code></pre>
| [] | [
{
"body": "<p>These are my suggestions</p>\n\n<ol>\n<li><p>Don't use mysql functions to connect and query Wordpress posts. \nYou can replace the first SQL statement with this WP_Query. </p>\n\n<pre><code>$query = new WP_Query('post_type=post&post_status=publish&orderby=date&order=DESC');\n$pageposts = $query->get_posts(); \n</code></pre>\n\n<p>This way the code is somewhat protected from future Wordpress database changes.</p></li>\n<li><p>The second select statement is a bit unnecessary as each $post in the $pagepost already contains the post id. \nOnly thing missing is the limit, but we'll add that to the WP_Query by adding</p>\n\n<pre><code>$query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);\n</code></pre></li>\n<li><p>Refactor and remove unused/unnecessary code</p>\n\n<p><code>global $wpdb, $voteiu_databasetable</code> - are not needed anymore<br>\n<code>$upperlimit</code> - assignment can be done on one line\n<code>$lowerlimit</code> - not used anymore as it's enough with the $upperlimit \n<code>$output = $pageposts;</code> - assigmentent before return is unnecessary</p></li>\n</ol>\n\n<p>So the complete <code>ShowPostByVotes</code> in votingfunctions.php would look something like this now:</p>\n\n<pre><code>function ShowPostByVotes() {\n\n $upperlimit = is_numeric(get_option('voteiu_limit')) ? get_option('voteiu_limit') : 100 ;\n\n $query = new WP_Query('post_type=post&post_status=publish&orderby=date&posts_per_page='.$upperlimit);\n $pageposts = $query->get_posts(); \n $votesarray = array();\n foreach ($pageposts as $post) {\n $vote_array = GetVotes($post->ID, \"array\");\n array_push($votesarray, array(GetVotes($post->ID)));\n }\n\n array_multisort($votesarray, SORT_DESC, $pageposts);\n return $pageposts;\n\n}\n</code></pre>\n\n<p>And you can use it in your index.php by using this code</p>\n\n<pre><code> <?php $pageposts = ShowPostByVotes(); ?>\n <?php if ($pageposts): ?>\n <?php global $post; ?>\n <?php foreach ($pageposts as $post): ?>\n <?php setup_postdata($post); ?>\n\n <div class=\"post\" id=\"post-<?php the_ID(); ?>\">\n <h2><a href=\"<?php the_permalink() ?>\" rel=\"bookmark\" title=\"Permanent Link to <?php the_title(); ?>\">\n <?php the_title(); ?></a></h2>\n <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>\n <div class=\"entry\">\n <?php the_content('Read the rest of this entry »'); ?>\n </div>\n\n <p class=\"postmetadata\">Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> \n <?php comments_popup_link('No Comments »', '1 Comment »', '% Comments »'); ?></p>\n </div>\n <?php endforeach; ?>\n\n <?php else : ?>\n <h2 class=\"center\">Not Found</h2>\n <p class=\"center\">Sorry, but you are looking for something that isn't here.</p>\n <?php include (TEMPLATEPATH . \"/searchform.php\"); ?>\n <?php endif; ?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T20:10:55.377",
"Id": "2580",
"Score": "0",
"body": "@Jonas Oh my god, I've been looking for this for years. How come you only have one badge? Thanks! (one more thing, how can move the `WP_Query` to the index page and use a while loop instead)?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T20:22:17.737",
"Id": "2581",
"Score": "0",
"body": "I assume you're trying to run your code in a recent version of Wordpress (?) WP_Query exists in /wp-includes/query.php and should be included and made available to you automatically in index.php (done in wp-settings.php , around line 105)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T20:39:55.960",
"Id": "2582",
"Score": "0",
"body": "@Jonas I'm using Wordpress 3.1. I always start custom loops like I show in the **EDIT** I included above. Is there any way of starting a loop like that with the code you provided?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T21:13:30.643",
"Id": "2583",
"Score": "0",
"body": "Ok, I'm not sure If I understand your problem, I think you should be able to retrieve exactly the same information by using the code I provided, only difference is the foreach instead of while and the extra call to setup_postdata(). Sorry but I don't see an easy way to sort the WP_Query using the Vote details. Once the WP_Query is executed you need to do the loop as I suggested"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T21:34:01.840",
"Id": "2584",
"Score": "1",
"body": "Had some issues editing my post so sorry for the \"nonexisting formatting\"\nThis code should present the same result as your custom query loop\n\n\n<?php global $post; ?>\n <?php $custom_posts =ShowPostByVotes(); ?>\n <?php foreach ($custom_posts as $post){ ?>\n <?php setup_postdata($post); ?>\n <div class=\"content-block-2\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>\" ><?php the_content(); ?></a>\n </div>\n <?php } ?>"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-27T20:01:04.217",
"Id": "1492",
"ParentId": "1464",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-25T21:07:39.553",
"Id": "1464",
"Score": "3",
"Tags": [
"php",
"mysql",
"wordpress"
],
"Title": "Function from WordPress VoteItUp function"
} | 1464 |
<p>I've been experimenting with Perl and MySql and wrote this code for connecting and writing to a database:</p>
<pre><code># MySQL DDL to create database used by code
#
# CREATE DATABASE sampledb;
#
# USE sampledb;
#
# CREATE TABLE `dbtable` (
# `id` int(11) NOT NULL AUTO_INCREMENT,
# `demo` longtext,
# PRIMARY KEY (`id`)
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# PERL MODULES
use strict;
use warnings;
use DBI; #http://dbi.perl.org
# CONFIG VARIABLES
my $platform = "mysql";
my $database = "sampledb";
my $host = "localhost";
my $port = "3306";
my $username = "root";
my $password = "password";
# DATA SOURCE NAME
my $dsn = "dbi:$platform:$database:$host:$port";
# PERL DBI CONNECT
my $connect = DBI->connect($dsn, $username, $password);
# VARS for Examples
my $query;
my $query_handle;
my $id;
my $demo;
# Example 1 using prepare() and execute() INSERT
# SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
$id = 1;
$demo = "test";
# INSERT
$query = "INSERT INTO dbtable (id, demo) VALUES ('$id', '$demo')";
$query_handle = $connect->prepare($query);
$query_handle->execute();
undef $query;
# Example 2 using do() UPDATE
# SAMPLE VARIABLE AND VALUES TO PASS INTO SQL STATEMENT
$id = 1;
$demo = "test 2";
# UPDATE
$query = "UPDATE dbtable SET demo = '$demo' WHERE id = $id";
$query_handle = $connect->do($query);
undef $query;
</code></pre>
<p>Is this the correct/idiomatic way to access a database in Perl? Are there any other improvements I could make?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:38:24.490",
"Id": "2603",
"Score": "0",
"body": "Is this a question?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:49:43.870",
"Id": "2605",
"Score": "0",
"body": "Would you describe what exactly your code does? I see a DDL and some insert and update statements. It's all right to ask for a general review, but we need more context."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T12:56:27.987",
"Id": "2638",
"Score": "0",
"body": "@Michael K: It's Perl for a database connector and sample INSERT and UPDATE, and very common code. Do you know Perl? Is there a template for information expected? Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T12:58:06.893",
"Id": "2639",
"Score": "0",
"body": "@Olli: Yes, it's working code -- and I wanted feedback; question is closed, and not posting again without and understanding of WHY it was closed. Thought that was the point of CodeReview. May I missing something? Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T13:14:40.390",
"Id": "2640",
"Score": "0",
"body": "@blunders: With your comments in mind I've edited the post to add that context in. The confusion arises because we aren't certain why the code was written. If it was meant as a module in a larger program we would read it differently than what it appears it is, a proof-of-concept database access standalone. Please look at my edits and edit the post as necessary - they should at least give you a guide to the information that would be helpful. I'm reopening the post now that there's more information available."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:38:29.477",
"Id": "2649",
"Score": "0",
"body": "@Michael K: Thanks for the edits, I've reviewed them and you're correct, they do give a better content to the question. Thanks!"
}
] | [
{
"body": "<p>Couple of things I noticed:</p>\n\n<p>When you connect to the database, you don't check that the connection succeeded. The most common way I've seen to do this in Perl is:</p>\n\n<pre><code>my $connect = DBI->connect($dsn, $username, $password)\n or die \"Connection Error: DBI::errstr\\n\";\n</code></pre>\n\n<p>If the connection fails, the program will then display the connection failure message so you can see what's going on.</p>\n\n<p>I see that you use two different ways of accessing the database. It would be better to pick one and use it for all your inserts/updates unless there is a compelling reason not to - it keeps future readers from trying to figure out why you did it differently. In this case I'd reccomend using <code>execute</code> since it allows you to execute multiple times:</p>\n\n<pre><code>$query_handle = $connect->prepare(\"INSERT INTO dbtable (id, demo) VALUES (?, ?)\");\n$query_handle->execute($id, $demo);\n$id = 2;\n$demo = \"test2\";\n$query_handle->execute($id, $demo);\n</code></pre>\n\n<p>Also don't forget to disconnect:</p>\n\n<pre><code>$connect->disconnect;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:45:26.880",
"Id": "2650",
"Score": "0",
"body": "+1 @Michael K: If I'm reading your answer correctly, you're saying \"do()\" does not allow for placeholders, but execute() does, right, or no? Main reason I've heard to use placeholders is to prevent SQL injection; which in this case would not be an issue, since the code is only used as an utility for importing data from flat files to a database. Agree about everything else, thanks!!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:57:48.150",
"Id": "2651",
"Score": "0",
"body": "@blunders: I'm sorry, I made a mistake there. `do` is for executing a query only once and *does* allow placeholders. The advantage of `prepare`/`execute` is that it creates a procedure on the database that you can execute multiple times with many arguments. So you could prepare the statement and then loop over the file, calling `execute` for every data set. It's faster than creating a new query every time, like `do`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:59:23.547",
"Id": "2652",
"Score": "0",
"body": "I edited my answer to reflect that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T13:53:13.710",
"Id": "1523",
"ParentId": "1465",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1523",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-25T23:30:43.523",
"Id": "1465",
"Score": "5",
"Tags": [
"mysql",
"perl"
],
"Title": "Perl DBI Sample with MySQL DDL"
} | 1465 |
<p>This is a collection of reasonably useful functions I put together for writing my blog.</p>
<pre><code>(require 'htmlize)
(defvar blog-mode-map nil
"Keymap for blog minor mode")
(unless blog-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-cl" 'insert-link)
(define-key map "\C-cp" 'insert-code-block)
(define-key map "\C-cc" 'insert-inline-code)
(define-key map "\C-cb" 'insert-bold)
(define-key map "\C-cq" 'insert-quote)
(define-key map "\C-cs" 'insert-sig)
(define-key map "\C-cf" 'insert-footnote)
(define-key map "\C-c\C-l" 'region-to-link)
(define-key map "\C-c\C-p" 'region-to-code-block)
(define-key map "\C-c\C-c" 'region-to-inline-code)
(define-key map "\C-c\C-b" 'region-to-bold)
(define-key map "\C-c\C-q" 'region-to-quote)
(define-key map "\C-c\C-s" 'region-to-sig)
(define-key map "\C-c\C-f" 'region-to-footnote)
(define-key map "/" 'smart-backslash)
(setq blog-mode-map map)))
(define-minor-mode blog-mode
"This is a collection of useful keyboard macros for editing Langnostic"
nil
" Blog"
(use-local-map blog-mode-map))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; simple definitions
(defun insert-tag (start-tag &optional end-tag)
"Inserts a tag at point"
(interactive)
(insert start-tag)
(save-excursion
(insert (or end-tag ""))))
(defun wrap-region (start end start-tag &optional end-tag)
"Inserts end tag at the end of the region, and start tag at point"
(goto-char end)
(insert (or end-tag ""))
(goto-char start)
(insert start-tag))
(defmacro definsert (tag-name start-tag end-tag)
"Defines insert function."
`(defun ,(make-symbol (concat "insert-" (symbol-name tag-name))) ()
(interactive)
(insert-tag ,start-tag ,end-tag)))
(defmacro defregion (tag-name start-tag end-tag)
"Defines region wrapper function."
`(defun ,(make-symbol (concat "region-to-" (symbol-name tag-name))) ()
(interactive)
(wrap-region (region-beginning) (region-end) ,start-tag ,end-tag)))
(definsert link (concat "<a href=\"" (x-get-clipboard) "\">") "</a>")
(defregion link (concat "<a href=\"" (x-get-clipboard) "\">") "</a>")
(definsert bold "<b>" "</b>")
(defregion bold "<b>" "</b>")
(definsert quote "<blockquote>" "</blockquote>")
(defregion quote "<blockquote>" "</blockquote>")
(definsert sig "<span class=\"sig\">" "</span>")
(defregion sig "<span class=\"sig\">" "</span>")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; <pre> and <code> definitions
(definsert code-block "<pre>" "</pre>")
(definsert inline-code "<code>" "</code>")
;; region versions are more complicated to accomodate htmlize
(defun region-to-inline-code ()
"HTMLize just the current region and wrap it in a <code> block"
(interactive)
(let((htmlified (substring (htmlize-region-for-paste (region-beginning) (region-end)) 6 -6)))
(delete-region (region-beginning) (region-end))
(insert-inline-code)
(insert htmlified)))
(defun region-to-code-block ()
"HTMLize the current region and wrap it in a <pre> block"
(interactive)
(let ((htmlified (htmlize-region-for-paste (region-beginning) (region-end))))
(delete-region (region-beginning) (region-end))
(insert (concat "<pre>" (substring htmlified 6)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; footnote definitions
(defun insert-footnote ()
"Inserts footnote, and a return link at the bottom of the file.
Moves point to footnote location."
(interactive)
(progn (footnotes-header)
(let ((footnote-name (format-time-string "%a-%b-%d-%H%M%S%Z-%Y" (current-time))))
(insert "<a href=\"#foot-" footnote-name "\" name=\"note-" footnote-name "\">[note]</a>")
(goto-char (point-max))
(insert "\n\n<a href=\"#note-" footnote-name "\" name=\"foot-" footnote-name "\">[back]</a> - "))))
(defun region-to-footnote ()
"Inserts a footnote at point and return link at the bottom. Moves the current region to the end of the file.
Leaves point where it is."
(interactive)
(save-excursion (kill-region (region-beginning) (region-end))
(insert-footnote)
(yank)))
(defun footnotes-header ()
"Inserts footnote header if not already present"
(unless (save-excursion (search-forward "<hr />\n<h5>Footnotes</h5>" nil t))
(save-excursion
(goto-char (point-max))
(insert "\n\n<hr />\n<h5>Footnotes</h5>"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; utility
(defun smart-backslash ()
"Backslash closes previous tag when used in the combination </. Self-inserts otherwise."
(interactive)
(if (equal (save-excursion (backward-char) (thing-at-point 'char)) "<")
(progn (backward-delete-char 1)
(sgml-close-tag))
(insert "/")))
(provide 'blog-mode)
</code></pre>
<p>I'd like some advice on how to remove duplication in a few obvious places. To my mind, I should be able to do something like <code>(deftag bold "b" "<b>" "</b>")</code> which would expand into a <code>definsert</code>, <code>defregion</code> and <code>define-key</code>. I'm not sure how to have a macro define multiple functions in Elisp though; <code>progn</code> (quoted or not) doesn't seem to help.</p>
<p>Feel free to point out any components I could replace with pre-built Emacs23 functions, or anything I could do more elegantly.</p>
<p>EDIT: Updated version of this code can be found <a href="https://github.com/Inaimathi/emacs-utils/blob/master/blog-mode.el">here</a>.</p>
| [] | [
{
"body": "<p>Not sure if this is relevant as it is a year old but, you can look at <a href=\"https://github.com/Neil-Smithline/defassoclist\" rel=\"nofollow\">https://github.com/Neil-Smithline/defassoclist</a> to see how to create multiple functions in a macro. </p>\n\n<p>You didn't include your failed attempts with <code>progn</code> so I can't tell you what you were doing wrong but <code>progn</code> does work. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-11T12:59:03.667",
"Id": "18735",
"Score": "0",
"body": "Yup; the updated version linked in that EDIT line contains the `progn` approach. It was a while ago, but I think it was to do with improper quoting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-11T03:22:50.767",
"Id": "11673",
"ParentId": "1467",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "11673",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-26T05:00:11.500",
"Id": "1467",
"Score": "10",
"Tags": [
"elisp"
],
"Title": "Minor mode for blog writing in HTML"
} | 1467 |
<p>This function changes a HashSet in the root of the class called 'commands' to a set of strings found in a file at "plugins/UC/Commands.txt" (it's what was requested by the people using the plugin). If the file doesn't exist, it copies a default file found in the zip file called "Commands.txt".</p>
<p>This is a weird request, and may be too much to ask for, but I realized my code is way over complicated. If you would be so kind as to show me how best to rewrite this, I would really appreciate it. When I originally wrote this, I just let Eclipse write it itself (with all the try/catch blocks being told to me), and I haven't done much to it, so it's in disarray. </p>
<pre><code>public void setComs () {
Set<String> temp = new HashSet<String>();
File file = null;
InputStream dflt = null;
InputStreamReader dfltReader = null;
FileReader fileReader = null;
FileOutputStream newFile = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader("plugins" + File.separator + "UC" + File.separator + "Commands.txt");
try {
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
temp.add(line);
}
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
System.out.println("[UC] couldn't read Commands.txt. Setting to default");
temp.clear();
dfltReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("Commands.txt"));
bufferedReader = new BufferedReader(dfltReader);
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
temp.add(line);
}
} catch (IOException e1) {
System.out.println("[UC] Cannot read default commands file. This is a critical error. " +
"Message user LRFLEW on bukkit.org if you see this");
}
} finally {
try {
fileReader.close();
} catch (IOException e) {}
}
} catch (FileNotFoundException e) {
System.out.println("[UC] couldn't find Commands.txt. Creating a new file with default settings");
file = new File("plugins" + File.separator + "UC");
try {
file.mkdir();
file = new File("plugins" + File.separator + "UC" + File.separator + "Commands.txt");
file.createNewFile();
newFile = new FileOutputStream(file);
dflt = this.getClass().getClassLoader().getResourceAsStream("Commands.txt");
byte[] buffer = new byte[dflt.available()];
for (int i = 0; i != -1; i = dflt.read(buffer)) {
newFile.write(buffer, 0, i);
}
temp.clear();
dfltReader = new InputStreamReader(dflt);
bufferedReader = new BufferedReader(dfltReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
temp.add(line);
}
dflt.close();
dfltReader.close();
bufferedReader.close();
} catch (IOException e1) {
System.out.println("[UC] cannot make new file. " +
"Either I don't have enough permissions to see the file or you need to change the permissions of the folder. " +
"Loading default settings...");
dfltReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("Commands.txt"));
bufferedReader = new BufferedReader(dfltReader);
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
temp.add(line);
}
} catch (IOException e2) {
System.out.println("[UC] Cannot read default file. This is a critical error. " +
"Message user LRFLEW on bukkit.org if you see this");
}
}
}
this.commands = temp;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T21:33:47.757",
"Id": "2561",
"Score": "0",
"body": "In regard to \"Community's\" comment added to the question, The FileReader's constructor can throw a FileNotFoundException and is not contained within an inner exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T22:38:48.747",
"Id": "3271",
"Score": "0",
"body": "What version of Java do you use? The later ones are much cleaner for file access using NIO."
}
] | [
{
"body": "<p>I have not coded in Java for some time, so I encourage you to use your own discretion while reading this. It should at-least give some general direction though.</p>\n\n<p>I noticed that you read lines into the hash set in several places, so I started by extracting it to a separate method.</p>\n\n<pre><code>void loadIntoHashSet(HashSet<string> set, Reader in)\n{\n BufferedReader bufferedReader = new BufferedReader(in);\n String line = null;\n\n while ((line = bufferedReader.readLine()) != null)\n {\n set.add(line);\n }\n\n bufferedReader.Close();\n}\n</code></pre>\n\n<p>I then noticed that you load the default values from the resource stream in two different locations and so extracted it into another method.</p>\n\n<pre><code>void loadDefaultsIntoHashSet(HashSet<string> set)\n{\n InputStreamReader dfltReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(\"Commands.txt\"));\n\n try\n {\n loadIntoHashSet(temp, dfltReader);\n }\n catch (IOException e1)\n {\n System.out.println(\"[UC] Cannot read default commands file. This is a critical error. \" + \n \"Message user LRFLEW on bukkit.org if you see this\");\n }\n\n dfltReader.Close();\n}\n</code></pre>\n\n<p>I find your use of the <code>for</code> construct in reading the resource stream to be a little unclear and so rewrote it as:</p>\n\n<pre><code>int read;\n\nwhile((read = dflt.read(buffer) != -1)\n{\n newFile.write(buffer, 0, read);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T06:56:32.697",
"Id": "1472",
"ParentId": "1468",
"Score": "5"
}
},
{
"body": "<p>Brian has some great suggestions so far, especially extracting reused functionality. When cleaning up a large method such as this, my first step is usually refactoring it up into smaller methods. I find short methods easier to conceptualize, clean up, and reuse (when possible).</p>\n\n<p>I highly recommend the book <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code: A Handbook of Agile Software Craftsmanship</a> for great coverage of writing clean, manageable code from the start. It also provides many tips on cleaning up existing code. While its examples are in Java, it applies to most every language.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T08:47:02.220",
"Id": "1473",
"ParentId": "1468",
"Score": "2"
}
},
{
"body": "<p>Have a look at commons-io lib from Jakarta Apache. 2 classes below look extremely useful for you.</p>\n\n<pre><code>org.apache.commons.io.IOUtils\norg.apache.commons.io.FileUtils\n</code></pre>\n\n<p>And I agree with the suggestions above. Make it more fine-grained. Idea is to have one method for one goal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T07:02:30.200",
"Id": "1901",
"ParentId": "1468",
"Score": "0"
}
},
{
"body": "<p>Agreeing to the above (Brian, David, Anton), my impression is, that there are 4 attemps to fill the set from different locations, which play together cascadingly. But it isn't visible if you look at the code. I think there should be a main method: </p>\n\n<pre><code>fillSet () {\n if (! fillfrom (x) || fillfrom (y))\n fillfrom (z) || fillfrom (a);\n}\n</code></pre>\n\n<p>Somehow like that. Instead, sometimes the exception is ignored, sometimes it is important (FileNotFound), sometimes the stream is closed immediately, sometimes in a finally. Maybe this is justified, but putting it all together seems not too easy. </p>\n\n<p>However, a handicap is, that there is this premature declaration at one place: </p>\n\n<pre><code>File file = null;\nInputStream dflt = null;\nInputStreamReader dfltReader = null;\nFileReader fileReader = null;\nFileOutputStream newFile = null;\nBufferedReader bufferedReader = null;\n</code></pre>\n\n<p>which can be easily delayed, and declared at different stages again, making the code more independent from its location. You don't save anything with a single declaration instead of 2 or 4 declarations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T05:08:28.753",
"Id": "1923",
"ParentId": "1468",
"Score": "1"
}
},
{
"body": "<p>Example with <code>Paths</code> and <code>Files</code> API from JDK 7 (but maybe the algorithm can be optimised):</p>\n\n<pre><code>public void setComs() {\n Path directory = Paths.get(\"plugins\" + File.separator + \"UC\");\n Path command = directory.resolve(\"Commands.txt\");\n\n List<String> lines;\n\n Path defaultSettings = Paths.get(this.getClass().getClassLoader().getResource(\"Commands.txt\").getPath());\n\n if (!Files.exists(command)) {\n System.out.println(\"[UC] couldn't find Commands.txt. Creating a new file with default settings\");\n\n try {\n if (!Files.exists(directory)) {\n Files.createDirectory(directory);\n }\n\n Path file = Files.createFile(command);\n\n Files.write(file, Files.readAllBytes(defaultSettings));\n\n lines = Files.readAllLines(defaultSettings, Charset.defaultCharset());\n\n } catch (IOException e1) {\n System.out.println(\"[UC] cannot make new file. \" +\n \"Either I don't have enough permissions to see the file or you need to change the permissions of the folder. \" +\n \"Loading default settings...\");\n\n lines = readDefaultSettings(defaultSettings);\n }\n } else {\n try {\n lines = Files.readAllLines(command, Charset.defaultCharset());\n } catch (IOException e) {\n System.out.println(\"[UC] couldn't read Commands.txt. Setting to default\");\n\n lines = readDefaultSettings(defaultSettings);\n }\n }\n\n this.commands = lines;\n}\n\nprivate List<String> readDefaultSettings(Path defaultSettings) {\n List<String> lines;\n try {\n lines = Files.readAllLines(defaultSettings, Charset.defaultCharset());\n } catch (IOException e1) {\n System.out.println(\"[UC] Cannot read default commands file. This is a critical error. \" +\n \"Message user LRFLEW on bukkit.org if you see this\");\n lines = Collections.emptyList();\n }\n return lines;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T16:49:39.020",
"Id": "48352",
"ParentId": "1468",
"Score": "1"
}
},
{
"body": "<p>One possible option, depending on the exact details of your use case, is to use </p>\n\n<pre><code>Properties p = new Properties();\nSet<String> s = Collections.checkedSet(Collections.newSetFromMap(p), String.class);\n</code></pre>\n\n<p>to store the data in question, rather than converting an existing <code>Set</code>.</p>\n\n<p>The <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Properties.html\" rel=\"nofollow\"><code>Properties</code></a> class is an implementation of the <code>Map</code> interface which includes methods for reading from and writing its contents to a file.</p>\n\n<p>Don't write what you don't need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T01:50:36.413",
"Id": "48380",
"ParentId": "1468",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-26T03:36:16.183",
"Id": "1468",
"Score": "2",
"Tags": [
"java",
"strings",
"file"
],
"Title": "Change HashSet to a set of strings found in a file"
} | 1468 |
<p>I'm cleaning build directories produced by GNOME build tool, <a href="http://live.gnome.org/Jhbuild" rel="nofollow">JHBuild</a>. This tool either downloads tarballs or clones git repositories, depending on set-up. After that, it proceeds to compilation (and then installation). Once in a while, something gets screwed up, and I need to clean the build directories so that I can start from scratch (because I don't know how to fix some of these problems).</p>
<p>Here's how I did it, and I'd like you to tell me if it can be improved:</p>
<pre><code>import os
import subprocess
top_level = os.path.expanduser("~/src/gnome")
for filename in os.listdir(top_level):
full_path = "{}/{}".format(top_level, filename)
if os.path.isdir(full_path):
cmd = "cd ~/src/gnome/{} && git clean -dfx".format(filename)
if subprocess.call(cmd, shell=True) != 0:
cmd = "cd ~/src/gnome/{} && make distclean".format(filename)
if subprocess.call(cmd, shell=True) != 0:
cmd = "cd ~/src/gnome/{} && make clean".format(filename)
subprocess.call(cmd, shell=True)
</code></pre>
| [] | [
{
"body": "<pre><code>full_path = \"{}/{}\".format(top_level, filename)\n</code></pre>\n\n<p>You can use <code>os.path.join(top_level, filename)</code> for that. That way it will also work on any system which does not use <code>/</code> as a directory separator (that's not really a realistic concern in this case, but using <code>os.path.join</code> doesn't cost you anything and is a good practice to get used to).</p>\n\n<pre><code>cmd = \"cd ~/src/gnome/{} && git clean -dfx\".format(filename)\n</code></pre>\n\n<p>First of all spelling out <code>~/src/gnome</code> again is bad practice. This way if you want to change it to a different directory you have to change it in all 4 places. You already have it in the <code>top_level</code> variable, so you should use that variable everywhere.</p>\n\n<p>On second thought you should actually not use <code>top_level</code> here, because what you're doing here is you're joining <code>top_level</code> and <code>filename</code>. However you already did that with <code>full_path</code>. So you should just use <code>full_path</code> here.</p>\n\n<p>You should also consider using <code>os.chdir</code> instead of <code>cd</code> in the shell. This way you only have to change the directory once per iteration instead of on every call. I.e. you can just do:</p>\n\n<pre><code>if os.path.isdir(full_path):\n os.chdir(full_path)\n if subprocess.call(\"git clean -dfx\", shell=True) != 0: \n if subprocess.call(\"make distclean\", shell=True) != 0:\n subprocess.call(\"make clean\", shell=True)\n</code></pre>\n\n<p>(Note that since <code>full_path</code> is an absolute path, it doesn't matter that you don't <code>chdir</code> back at the end of each iteration.)</p>\n\n<p>Another good habit to get into is to not use <code>shell=True</code>, but instead pass in a list with command and the arguments, e.g. <code>subprocess.call([\"make\", \"clean\"])</code>. It doesn't make a difference in this case, but in cases where your parameters may contain spaces, it saves you the trouble of escaping them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T18:03:46.160",
"Id": "2555",
"Score": "0",
"body": "Regarding your very last comment, I'm tempted to change the subprocess to something like `subprocess.call(\"git clean -dfx\".split())`. Is that kool?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T18:09:31.317",
"Id": "2556",
"Score": "0",
"body": "@Tshepang: The point of passing in an array instead of `shell=True` is that it will handle arguments with spaces or shell-metacharacters automatically correctly without you having to worry about. Using `split` circumvents this again (as far as spaces are concerned anyway), so there's little point in that. Since in this case you know that your arguments don't contain any funny characters, you can just keep using `shell=True` if you don't want to pass in a spelled-out array."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T18:16:40.643",
"Id": "2557",
"Score": "0",
"body": "In such cases, won't [shlex.split()](http:///doc.python.org/library/shlex.html#shlex.split) be useful?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T18:31:29.073",
"Id": "2558",
"Score": "1",
"body": "@Tshepang: I don't see how. If you already know the arguments, `subprocess.call(shlex.split('some_command \"some filename\"'))` buys you nothing over `subprocess.call([\"some_command\", \"some filename\"]` and IMHO has a higher chance that you might forget the quotes. However if the filename is inside a variable, `subprocess.call([\"some_comand\", filename])` still works no matter which special characters `filename` contains, while using `shlex.split` would require you to somehow escape the contents of `filename` first, in which case you could have just used `shell=True` in the first place."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T16:56:14.767",
"Id": "1477",
"ParentId": "1476",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1477",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-26T16:33:28.870",
"Id": "1476",
"Score": "3",
"Tags": [
"python",
"git",
"make"
],
"Title": "Cleaning multiple build directories"
} | 1476 |
<p>For an interview, I was asked to write code allocate memory for a rows*cols matrix, using a <em>single</em> <code>malloc()</code>. I want your comments about this code that I wrote:</p>
<pre><code>/*
Allots (in effect) space for a matrix of size rows*cols using a single malloc.
The whole space allotted consists of an array of size 'rows' of float ptrs,
followed by a float array of size 'rows' * 'cols'.
The float ptrs 1,2.., are assigned to row no. 1, 2,.. in the matrix that follows.
*/
float** allotMatrix(const size_t &rows, const size_t &cols)
{
// Compute size of allotment = rows * cols floats + rows float ptrs
size_t ptrsize = rows * sizeof(float*);
size_t datasize = rows * cols * sizeof(float);
size_t matsize = ptrsize + datasize;
// Get if possible a memory allotment of this size. We use char* for convenience
char* cmatrix = (char*) malloc(matsize);
if (cmatrix == NULL)
{
fprintf(stderr, "Unable to allot memory");
exit(1);
}
memset((void*) cmatrix, 0, matsize);
// Assign ptrs to data
float** ptrstart = (float**) cmatrix;
float* datastart = (float*) (cmatrix + ptrsize);
for (size_t i = 0; i != rows; ++i)
{
*ptrstart = datastart;
// Move to next ptr
++ptrstart;
// .. and move to the next data row
datastart += cols;
}
return (float**) cmatrix;
}
</code></pre>
| [] | [
{
"body": "<p>I would use <code>calloc</code> instead of <code>malloc</code> since you're anyway clearing the matrix after allocation. </p>\n\n<pre><code>void* cmatrix = calloc(1, matsize);\n...\n//memset((void*) cmatrix, 0, matsize); this is not needed anymore because of 'calloc'\n</code></pre>\n\n<p>Also I do not think there is any point in using <code>char*</code> here because. Looks like you're using <code>char*</code> only because it allows you to increment pointers by bytes. I think using <code>float**</code> here would be even more convinient: </p>\n\n<pre><code>float** cmatrix = (float**) calloc(1, matsize);\nif (cmatrix == NULL) { ... }\nfloat* datastart = (float*) (cmatrix + rows); // you don't need char pointers here\nfor (...) { ... }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T23:48:42.040",
"Id": "2563",
"Score": "0",
"body": "arithmetic such as (cmatrix+ptrsize) can't be done with void*."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T02:49:02.530",
"Id": "2569",
"Score": "2",
"body": "There's no guarantee in the C standard that the zeroing that `calloc()` does creates floating point zeroes. That said, with the IEEE 754 standard, you do get zeroes, and that covers an awful lot of machines these days."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T08:16:17.063",
"Id": "2572",
"Score": "0",
"body": "@Jonathan, I wasn't talking about floating point zeros, OP originally was zeroing the memory with `memset` and I believe it will behave in the same way as `calloc`. And I don't know how both these approaches work with floating point zeroz, I just say that one can be replaced with other."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T08:23:24.330",
"Id": "2573",
"Score": "0",
"body": "@Ganesh, got your point, updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-26T07:01:50.377",
"Id": "142387",
"Score": "1",
"body": "not good practice to cast the return value of calloc/malloc, it returns a void* so there is no need to cast"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-26T23:39:53.573",
"Id": "1481",
"ParentId": "1479",
"Score": "5"
}
},
{
"body": "<p>I would not pass rows and cols by reference in this case, most cases it will have the same size as a pointer, no gain using it as reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T21:44:16.053",
"Id": "2662",
"Score": "0",
"body": "does C even have references? I thought that was limited to C++. Was it added to the latest standard?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-30T14:13:17.693",
"Id": "2686",
"Score": "0",
"body": "As far I know no references for C, only pointers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T11:44:07.333",
"Id": "1499",
"ParentId": "1479",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "1481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-26T22:51:36.817",
"Id": "1479",
"Score": "4",
"Tags": [
"c",
"interview-questions",
"memory-management",
"matrix"
],
"Title": "Allocating memory for a matrix with a single malloc"
} | 1479 |
<p>I wrote an implementation of binary search in JavaScript earlier for kicks, but I noticed my version was significantly different than those found on Google. <a href="http://www.dweebd.com/javascript/binary-search-an-array-in-javascript/">Here</a> is an example of binary search I found on Google (copied here to combat link rot): </p>
<pre><code>Array.prototype.binarySearch = function(find, comparator) {
var low = 0, high = this.length - 1,
i, comparison;
while (low <= high) {
i = Math.floor((low + high) / 2);
comparison = comparator(this[i], find);
if (comparison < 0) { low = i + 1; continue; };
if (comparison > 0) { high = i - 1; continue; };
return i;
}
return null;
};
</code></pre>
<p>Most of the other implementations on Google are quite similar. But in mine, I don't subtract one from the low/high and continue from there. Instead, I divide the array in half and continue dividing the appropriate side in half until I reach the proper value. Code: </p>
<pre><code>function binary_search_iterative(arr, ele) {
var beginning = 0, end = arr.length,
target;
while (true) {
target = Math.floor((beginning + end) / 2);
if ((target === end || target === beginning) && arr[target] !== ele) {
return -1;
}
if (arr[target] > ele) {
end = target;
} else if (arr[target] < ele) {
beginning = target;
} else {
return target;
}
}
}
</code></pre>
<p>I wrote this recursive-style as well, but in testing I found this iterative version was faster.</p>
<p>In my tests, I've found that the examples I've found on Google (though they did not include the one above, they were nearly identical) are faster on smaller arrays, but as the input size increases, mine overtakes those. Since binary searches are usually limited (?) to larger input sizes, I see this as an improvement.</p>
<p>Is my thinking correct? Could this be done in an even better way? </p>
<p>I also do not like this: </p>
<pre><code>if ((target === end || target === beginning) && arr[target] !== ele) {
return -1;
}
</code></pre>
<p>And I was curious if there is a good way to eliminate it or refactor the function where it's cleaner in general.</p>
| [] | [
{
"body": "<p>I would just like to hi-light a few points of difference in the two and how I <em>think</em> they are reflected in what you are seeing.</p>\n\n<ul>\n<li><p>When making a comparison between <code>arr[target]</code> and <code>ele</code>, if they are not the same then you do not need to include <code>target</code> within the bounds of the next iteration (hence the +/- 1). This can reduce the number of comparisons though the effect is more significant on smaller datasets.</p></li>\n<li><p>When following the above point, it becomes sufficient terminate as \"not found\" when <code>beginning > end</code> rather then check that you are looking at the beginning or end value. Also your approach may provide a false negative when looking for \"B\" in the following situation.</p>\n\n<pre><code> target\n |\n v\n... A B\n ^ ^\n | |\n | end\n beginning\n</code></pre>\n\n<p>In this situation, because target === beginning and arr[target] !== B, it returns -1.</p></li>\n<li><p>The googled code uses <code>parseInt</code>, I'm not sure how this affects correctness but I suspect this has an adverse effect on the performance.</p></li>\n</ul>\n\n<p>I <em>think</em> what you are seeing in the scalability is because the googled code does fewer comparisons but the <code>parseInt</code> makes the comparisons more expensive. The reduced number of comparisons is more significant for small data sets, but for larger data sets cost of the comparison becomes more significant.</p>\n\n<p>I would suggest some experimentation/investigation to see if this is accurate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T05:43:23.533",
"Id": "1488",
"ParentId": "1480",
"Score": "18"
}
},
{
"body": "<p>Honestly I've never been a fan of while(true). In my opinion its best to put your main conditional there for readability and style. Here is the version I wrote a while back for kicks, if it helps - my goal here was mostly fitting it in a tweet - but I beautified it for this example. Notice I am using Math.floor instead of parseInt - my tests indicated Math.floor was about twice as fast when there was a .5, and just a tiny bit faster when done on an integer. This version may look weird (the ternary upperbound is assigned to -2 when match found) but again it was a byte shaving experiment.</p>\n\n<pre><code>Array.prototype.binarysearch = function (o) {\n var l = 0, u = this.length, m;\n while ( l <= u ) { \n if ( o > this[( m = Math.floor((l+u)/2) )] ) l = m+1;\n else u = (o == this[m]) ? -2 : m - 1;\n }\n return (u == -2) ? m : -1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T13:29:25.280",
"Id": "1490",
"ParentId": "1480",
"Score": "10"
}
},
{
"body": "<p>Apart from the use of parseInt, the performance difference between the different approaches is likely to depend most on the Javascript implementation. </p>\n\n<ul>\n<li><p>With an aggressive optimizer (e.g. in a JIT compiler), the different versions will probably work out pretty much the same. For others, it will be a lottery.</p></li>\n<li><p>For any given Javascript platform it will be hard to predict which version of the code will perform best. If it really matters, (and I suspect it won't) you need to benchmark the different versions of method on all of the Javascript platforms that you care about.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T03:31:11.093",
"Id": "2041",
"ParentId": "1480",
"Score": "1"
}
},
{
"body": "<p>Change <code>Math.floor((beginning + end) / 2)</code> to <code>((beginning + end) >> 1)</code> means the same thing and is much quicker:</p>\n\n<p><a href=\"http://jsperf.com/code-review-1480\">http://jsperf.com/code-review-1480</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T01:23:36.683",
"Id": "20354",
"Score": "4",
"body": "+1 I'm normally against bitwise operations in JS, but that's pretty cool. [And it holds up with larger arrays!](http://jsperf.com/code-review-1480/5)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T03:14:25.077",
"Id": "4491",
"ParentId": "1480",
"Score": "17"
}
},
{
"body": "<p>Your code won't generate a false negative as suggested by Brian; 'end' always points at an element that is considered greater than the value to be found (treating past the array as a logical element).</p>\n\n<p>Your code can reference the element past the end of the array, however. E.g. If the length of the array is zero, you will dereference arr[0]. In javascript, this might be acceptable, but for a C programmer, it looks weird.</p>\n\n<p>The primary difference in performance is going to come from the fact that the googled code calls a subroutine to perform the comparison and your code performs the comparison in line. To properly compare the two approaches, you should race your code against the googled code with inlined comparisons. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-12T07:21:29.063",
"Id": "31134",
"ParentId": "1480",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "1488",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-26T23:32:47.953",
"Id": "1480",
"Score": "38",
"Tags": [
"javascript",
"algorithm",
"search",
"binary-search"
],
"Title": "JavaScript binary search"
} | 1480 |
<p>This is a classic linked list problem.</p>
<ol>
<li>Deleting a node from linked list given the data to be deleted.</li>
<li>Inserting a node in a sorted linked list.</li>
</ol>
<p>I saw various versions of this and here is my version. Could you check and let me know if this code is efficient?</p>
<pre><code>void deletenode(struct node *&first, int data)
{
struct node * current = first;// first will have the node after deletion
struct node * prev = (node *)malloc(sizeof(node));
while(current!=NULL)
{
if(current->data!=data)
{
prev=current;
current = current->next;
}
else
{
prev->next = current->next;
delete current;
break;
}
}
}
void insertinsortedlist(struct node *& first, int data)
{
struct node * current = first;// first will have the node after insertion
struct node * newnode = (node *)malloc(sizeof(node));
newnode->data = data;
struct node * temp = (node *)malloc(sizeof(node));
while(current)
{
if((current->data < data) && (current->next->data > data))
{
temp = current->next;
current->next = newnode;
newnode->next = temp;
break;
}
current = current->next;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T02:06:40.350",
"Id": "2567",
"Score": "0",
"body": "In the future please indent your code by 4 spaces or use the code button (the one with the ones and zeros) to properly format your code."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T10:26:15.457",
"Id": "2576",
"Score": "0",
"body": "It's difficult to give a full review of your code without seeing your definition of `node`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T05:09:12.487",
"Id": "36392",
"Score": "0",
"body": "This program has a bug. If I want to delete the first node, it will not work. This is wrong: `prev=first=null\nprev.next !=null`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-04T16:03:42.903",
"Id": "280064",
"Score": "0",
"body": "This code looks more like C than C++ to me"
}
] | [
{
"body": "<p>The efficiency of your algorithm is fine, however there are a couple of other things you should take care of:</p>\n\n<p>First of all do <strong>not</strong> free memory, which was allocated with <code>malloc</code>, using <code>delete</code>. <code>delete</code> is for freeing memory which was allocated with <code>new</code>. To free <code>malloc</code>ed memory use <code>free</code>. Using <code>delete</code> on <code>malloc</code>ed memory is <strong>wrong</strong> and leads to undefined behavior.</p>\n\n<p>Also there is almost never a good reason to use <code>malloc</code> in C++ code. If in doubt use <code>new</code> and <code>delete</code>.</p>\n\n<p>Another serious bug in your code is that you allocate memory for <code>prev</code> in <code>deletenode</code>, but never free it.</p>\n\n<hr>\n\n<p>I also don't see why you pass in <code>first</code> as a reference to a pointer. Since you never change <code>first</code>, I see no reason not to pass it in as a plain pointer (or a plain reference which you then take the address of to assign to <code>current</code>).</p>\n\n<hr>\n\n<p>Another thing is that you don't need to add the <code>struct</code> keyword when declaring variables or parameters containing structs in C++ - that's a C thing. You should remove it as it only adds noise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T07:31:34.860",
"Id": "2571",
"Score": "2",
"body": "All the above, and don't malloc a new node for `previous` in the first place. Instead, check if `previous` is still `NULL` once you found the node to be deleted. If it is, assign `first = first->next` to delete the first node."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-08T22:27:48.217",
"Id": "36440",
"Score": "0",
"body": "To back this point up it's worth noting that if you use malloc to create instances of C++ objects, then the constructors won't get called. You'd have to use \"placement new\" manually after allocating the memory. This holds for destruction as well (ie. free doesn't call destructors)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T02:05:50.927",
"Id": "1486",
"ParentId": "1484",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-27T01:35:01.030",
"Id": "1484",
"Score": "3",
"Tags": [
"c++",
"linked-list"
],
"Title": "Deleting a linked list node"
} | 1484 |
<p>I have built a "reset and confirm password" section on a site. It works great. I just have this suspicion that maybe it isn't the most efficient way. I am relatively new to
jQuery but I can usually make things work well. I am just wanting to make sure I am doing them right. </p>
<p>Any suggestions are appreciated. </p>
<pre><code>/////////////// RESET PASSWORD /////////////////////
$('#reset_password').click(function reset_password(){
//Enter a password input field a button
$('#new_pass_field').html('<input type="text" id="new_password" name="new_password"><button id="submit_new_pass">Submit New Password</button>');
// Bind a click to the button
$('#submit_new_pass').bind('click', function submit_new_pass (){
// When clicked get val of the new_password field.
$get_val = $("#new_password").val();
// Hide the new_pass field and button so the confirm field and button can be entered.
$('#new_pass_field').hide("fast").html('<input type="text" id="password" name="password"><button id="confirm_new_pass">Confirm New Password</button>');
// Bind click to that confirm button
$('#confirm_new_pass').bind('click', function confirm_new(){
// Get val of the confirm pass field
$get_confirm_val = $("#password").val();
// Check valdation if 2 passwords match
if($get_val == $get_confirm_val){
// If they match send to DB and encrypt.
$.get(uri_base +'/AJAX/update_password/admin_users/'+$get_confirm_val+'/'+Math.random(), function(msg){
//If returns true then send msg password changed. and hide the password row.
if(msg){
$("#err_password").html("Your Password has been changed.").queue(function(){
setTimeout(function(){
$("#err_password").dequeue();
}, 3000);
})
$('#reset_pass_results').slideUp("slow");
$('#new_pass_field').hide("fast").html('');
}else{
// Error in the DB
$("#err_password").html("There was an error. Your password was not changed.");
}
});
}else{
// Passwords didn't match now reset the clicks to try again and hide the error
$("#err_password").html("Your Passwords didn't match!").delay(3000).fadeOut("slow");
$('#confirm_new_pass').bind('click', confirm_new);
$('#reset_password').bind('click', reset_password);
}
return false;
});
// Show the password field
$('#new_pass_field').show("fast");
return false;
});
// Show initial field and button.
$('#reset_pass_results').slideDown("slow", function(){
$('#new_pass_field').show("fast");
});
return false;
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T02:06:18.227",
"Id": "2566",
"Score": "4",
"body": "Just in glancing, I would not use a `GET` request to change a user's password - this leaves you open for [CSRF attacks](http://en.wikipedia.org/wiki/Cross-site_request_forgery). Use a `POST` and pass along a user-specific 'secret' token, as shown in the [Prevention section](http://en.wikipedia.org/wiki/Cross-site_request_forgery#Prevention)."
}
] | [
{
"body": "<p>Looks fine to me but one way to write a lot less code for these relatively simple ajax calls is to use the <a href=\"http://jquery.malsup.com/form/\" rel=\"nofollow\">Jquery Form</a> plugin that converts a form tag to an ajax call. I believe you'll find it a huge time save going forward.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T22:52:42.030",
"Id": "1508",
"ParentId": "1485",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1508",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-27T01:38:40.543",
"Id": "1485",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "jQuery password confirmation"
} | 1485 |
<p>I'm working on writing a scripting language with ANTLR and C++. This is my first actual move from ANTLR grammars into the C++ API, so I'd like to know if this would be a good way to structure the grammar (later I will be adding a tree parser or tree rewriting rules though).</p>
<pre><code>grammar dyst;
options
{
language = C;
output = AST;
ASTLabelType=pANTLR3_BASE_TREE;
}
program : statement*;
statement : stopUsingNamespaceStm|usingNamespaceStm|namespaceDefineStm|functionStm|defineStm|assignStm|funcDefineStm|ifStm|whileStm|returnStm|breakStm|eventDefStm|eventCallStm|linkStm|classDefStm|exitStm|importStm|importOnceStm|directive;
namespaceDefineStm : 'namespace' ident '{' statement* '}';
usingNamespaceStm : 'using' 'namespace' ident (',' ident)* ';';
stopUsingNamespaceStm : 'stop' 'using' 'namespace' ident (',' ident)* ';';
directive : '@' directiveId argList? ';';
directiveId : ID (':' ID)*;
importOnceStm : 'import_once' expression ';';
importStm : 'import' expression ';';
exitStm : 'exit' expression? ';';
classDefStm : 'class' ident ('extends' ident (',' ident)*)? '{' (classSection|funcDefineStm|defineStm|eventDefStm)* '}';
classSection : ('public'|'private'|'protected') ':';
linkStm : 'link' ident 'to' ident (',' ident)* ';';
eventCallStm : 'call' ident (',' argList)? ';';
eventDefStm : 'event' ident '(' paramList? ')' ';';
returnStm : 'return' expression ';';
breakStm : 'break' int ';';
ifStm : 'if' '(' expression ')' '{' statement* '}';
whileStm : 'while' '(' expression ')' '{' statement* '}';
defineStm : 'global'? 'def' ident ('=' expression)? ';';
assignStm : ident '=' expression ';';
funcDefineStm : 'function' ident '(' paramList? ')' ('handles' ident (',' ident)*)? '{' statement* '}';
paramList : param (',' param)?;
param : ident ('=' expression)?;
functionStm : functionCall ';';
functionCall : ident '(' argList? ')';
argList : expression (',' expression)*;
//Expressions!
term : functionCall|value|'(' expression ')';
logic_not : ('!')* term;
bit_not : ('~')* logic_not;
urnary : '-'* bit_not;
mult : urnary (('*'|'/'|'%') urnary)*;
add : mult ('+' mult)*;
relation : add (('<='|'>='|'<'|'>') add)*;
equality : relation (('=='|'!=') relation)*;
bit_and : equality ('&' equality)*;
bit_xor : bit_and ('^' bit_and)*;
bit_or : bit_xor ('|' bit_xor)*;
logic_and : bit_or ('&&' bit_or)*;
logic_or : logic_and ('||' logic_and)*;
expression : logic_or;
value : ident|float|int|string|boolean|newObject|anonFunc|null_val;
anonFunc : 'function' '(' paramList? ')' '{' statement* '}';
newObject : 'new' ident ('(' argList ')')?;
ident : ID (('.'|'::') ID)*;
float : FLOAT;
int : INTEGER;
string : STRING_DOUBLE|STRING_SINGLE;
boolean : BOOL;
null_val : NULL_VAL;
FLOAT : INTEGER '.' INTEGER;
INTEGER : DIGIT+;
BOOL : 'true'|'false';
NULL_VAL : 'null'|'NULL';
STRING_DOUBLE : '"' .* '"';
STRING_SINGLE : '\'' .* '\'';
ID : (LETTER|'_') (LETTER|DIGIT|'_')*;
fragment DIGIT : '0'..'9';
fragment LETTER : 'a'..'z'|'A'..'Z';
NEWLINE : ('\n'|'\r'|'\t'|' ')+ {$channel = HIDDEN;};
COMMENT : '#' .* '\r'? '\n' {$channel = HIDDEN;};
MULTI_COMMENT : '/-' .* '-/' {$channel = HIDDEN;};
</code></pre>
<p>If you are wondering about exactly what it is I'm using this for, you can take a look <a href="http://dev.redxdev.com/p/dyst" rel="nofollow noreferrer">here</a>.</p>
| [] | [
{
"body": "<ol>\n<li><p>The grammar itself is pretty unreadable \"as is\". A rule like:</p>\n\n<pre><code>statement : stopUsingNamespaceStm|usingNamespaceStm|namespaceDefineStm|functionStm|defineStm|assignStm|funcDefineStm|ifStm|whileStm|returnStm|breakStm|eventDefStm|eventCallStm|linkStm|classDefStm|exitStm|importStm|importOnceStm|directive;\n</code></pre>\n\n<p>would be far more readable when declared like this:</p>\n\n<pre><code>statement \n : stopUsingNamespaceStm\n | usingNamespaceStm\n | namespaceDefineStm\n | functionStm\n | defineStm\n | assignStm\n | funcDefineStm\n | ifStm\n | whileStm\n | returnStm\n | breakStm\n | eventDefStm\n | eventCallStm\n | linkStm\n | classDefStm\n | exitStm\n | importStm\n | importOnceStm\n | directive\n ;\n</code></pre></li>\n<li><p>You'll want to explicitly end the entry point of your parser, the rule <code>program</code>, with the end-of-file token, otherwise your parser might stop parsing prematurely. With <code>EOF</code>, you force the parser to read the entire tokens stream.</p>\n\n<pre><code>program \n : statement* EOF\n ;\n</code></pre></li>\n<li><p>Make explicit tokens for keywords, don't mix them inside your parser rules.</p>\n\n<p>Instead of:</p>\n\n<pre><code>importStm \n : 'import' expression ';'\n ;\n</code></pre>\n\n<p>it's better to do:</p>\n\n<pre><code>importStm \n : Import expression ';'\n ;\n\nImport\n : 'import'\n ;\n</code></pre>\n\n<p>This will make your life easier at a later (tree walking) stage. Without explicit lexer tokens, it is unclear for you when debugging what tokens there actually are in your tree.</p></li>\n<li><p>Your lexer rules:</p>\n\n<pre><code>STRING_DOUBLE : '\"' .* '\"';\nSTRING_SINGLE : '\\'' .* '\\'';\n</code></pre>\n\n<p>can never contain either double- or single quotes. So, it's impossible to have a string literal with a double- and single quote in it.</p>\n\n<p>Better to do something like this:</p>\n\n<pre><code>STRING_DOUBLE \n : '\"' ('\\\\' ('\\\\' | '\"') | ~('\\\\' | '\"'))* '\"'\n ;\n</code></pre>\n\n<p>which will allow a double quoted string to contain double quotes as well.</p></li>\n</ol>\n\n<p>That's all I saw at a first glance. I didn't look real close, so there might be more that can be improved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T18:04:20.143",
"Id": "2756",
"Score": "0",
"body": "Thanks a lot, especially with the quote thing. I was having trouble with that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T18:08:58.423",
"Id": "2757",
"Score": "0",
"body": "@Sam, you're welcome. Note that the string literals now also accepts line breaks. If you don't want that, do something like this: `STRING_DOUBLE : '\"' ('\\\\' ('\\\\' | '\"') | ~('\\\\' | '\"' | '\\r' | '\\n'))* '\"' ;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-31T13:51:27.320",
"Id": "1582",
"ParentId": "1487",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "1582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-27T03:24:11.313",
"Id": "1487",
"Score": "8",
"Tags": [
"c++",
"grammar"
],
"Title": "Parsing a basic scripting language"
} | 1487 |
<p>Here is my PHP class for solving Sudoku:</p>
<p><a href="https://gist.github.com/889044" rel="nofollow">GitHub</a></p>
<p><strong>Sudoku</strong></p>
<pre><code><?php
/**
* Bootstrap file
*
* This is an example of how to use the SudokuSolver Class
* Here the input array has been hardcoded. It could be send
* as get or post in the real application.
*
* @author Anush Prem <goku.anush@gmail.com>
* @package Solver
* @subpackage Sudoku
* @version 0.1
*/
/**
* Required Class files
*/
include_once "SudokuSolver.class.php";
// The application could take longer than normal php execution
// time. So set the execution time limit to 0(unlimited).
set_time_limit(0);
// input sudoku array in the format row == col array mapping
$sudoku = array(
array(0,4,0,0,5,3,1,0,2),
array(2,0,8,1,0,0,7,0,0),
array(5,0,1,4,2,0,6,0,0),
array(8,1,4,0,3,0,2,0,7),
array(0,6,0,2,0,5,0,1,9),
array(0,5,0,7,4,0,0,6,3),
array(0,0,0,0,7,4,5,8,1),
array(1,8,5,9,0,2,0,0,0),
array(4,0,3,0,0,8,0,2,6)
);
// create an object of SudokuSolver.
$solver = new SudokuSolver();
// Pass the input sudoku to the $solver object.
$solver -> input ($sudoku);
// Solve the sudoku and return the solved sudoku.
$solved = $solver -> solve ();
// printing the formated input sudoku
print "<B>Input Sudoku:</B><br />";
foreach ($sudoku as $row){
foreach ($row as $col ){
print $col . "&nbsp;&nbsp;";
}
print "<br />";
}
print "<hr />";
// printing the formated solved sudoku.
print "<B>Solved Sudoku:</B><br />";
foreach ($solved as $row){
foreach ($row as $col ){
print $col . "&nbsp;&nbsp;";
}
print "<br />";
}
?>
</code></pre>
<p><strong>Sudoku Solver</strong></p>
<pre><code><?php
/**
* @author Anush Prem <goku.anush@gmail.com>
* @package Solver
* @subpackage Sudoku
* @version 0.1
*/
/**
* <i>Sudoku Solver</i> class
*
* This class solves the sudoku in my own logic.
*
* This solver takes time to execute according to the
* complexity of the sudoku.
*
* @author Anush Prem <goku.anush@gmail.com>
* @package Solver
* @subpackage Sudoku
* @version 0.1
*/
Class SudokuSolver{
/**
* To store the input Sudoku
* @access private
* @var array $_input row == column mapping
*/
private $_input;
/**
* To store the currently solved sudoku at any moment of time
* @access private
* @var array $_currentSudoku row == column mapping
*/
private $_currentSudoku;
/**
* To store the probable values for each cell
* @access private
* @var array $_probable [row][col] == possible values array mapping
*/
private $_probable;
/**
* to store weather the sudoku have been solved or not
* @access private
* @var bool
*/
private $_solved = false;
/**
* store weather each cell is solved or not
* @access private
* @var array $_solvedParts row == column (bool) values
*/
private $_solvedParts = array (
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false ),
array ( false, false, false, false, false, false, false, false, false )
);
/**
* SudokuSolver constructor
*
* If the input sudoku is provided it will store to the {@link _input} property.
*
* @access public
* @param array $input row == column mapping
* @return void
*/
public function __construct($input = null){
// check if the input sudoku is provided, if yes then
// store it in $_input
if ( $input !== null ) $this -> _input = $input;
}
/**
* Input Method
*
* Explictly give a new input array if its not already provided in
* the constructor. If already provieded in the constructore then
* it will be replaced
*
* @access public
* @param array $input row == column mapping
* @return void
*/
public function input($input){
// store the received input into $_input
$this -> _input = $input;
}
/**
* Solve Method
*
* The main function to start solving the sudoku and return the
* solved sudoku
*
* @access public
* @return array row == column mapping of solved sudoku
*/
public function solve (){
// Copy the input sudoku to _currentSudoku
$this -> _currentSudoku = $this -> _input;
// update _solvedParts of the given sudoku
$this -> _updateSolved ();
// Start solving the sudoku
$this -> _solveSudoku();
// return the solved sudoku
return $this -> _currentSudoku;
}
/**
* updateSolved Method
*
* Update the _solvedParts array to match the values of
* _currentSudoku.
*
* @access private
* @return void
*/
private function _updateSolved(){
// loop for rows
for ($i = 0; $i < 9; $i++ )
// loop for columns
for ($j = 0; $j < 9; $j++ )
// if the value exists for the corresponding row, column
// then update the _solvedParts corresponding row, column
// to true
if ( $this -> _currentSudoku[$i][$j] != 0 )
$this -> _solvedParts[$i][$j] = true;
}
/**
* _solveSudoku Method
*
* Main sudoku solving method
*
* @access private
* @return void
*/
private function _solveSudoku(){
// continue running untill the sudoku is completly solved
do{
// calculate the probable values for each cell an solve
// available cells
$this -> _calculateProbabilityAndSolve();
// check weather the sudoku is completly solved
$this -> _checkAllSolved();
}while (!$this -> _solved); // run till the _solved value becomes true
}
/**
* _calculateProbabilityAndSolve Method
*
* Find the possible values for each cell and
* solve it if possible
*
* @access private
* @return void
*/
private function _calculateProbabilityAndSolve(){
// find possible values for each cell
$this -> _findPosibilites();
// check if each cell is solveable and if yes solve it
$this -> _solvePossible();
}
/**
* _findPosibilites Method
*
* Find possible values for each cell
*
* @access private
* @return void
*/
private function _findPosibilites(){
// loop for rows
for ($i = 0; $i < 9; $i++ ){
// loop for columns
for ($j = 0; $j < 9; $j++ ){
// if the ixj cell is not solved yet
if ( !$this -> _solvedParts[$i][$j] ){
// find all possible values for cell ixj
$this -> _findAllProbables ($i, $j);
}
}
}
}
/**
* _solvePossible Method
*
* Solve possible cells using probable values calculated
*
* @access private
* @return void
*/
private function _solvePossible(){
// loop for rows
for ($i = 0; $i < 9; $i++ ){
// loop for column
for ($j = 0; $j < 9; $j++ ){
// if cell ixj is not solved yet
if ( !$this -> _solvedParts[$i][$j] ){
// solve the cell ixj if possible using probable values
// calculated
$this -> _solveIfSolveable ($i, $j);
}
}
}
}
/**
* _checkAllSolved Method
*
* check if all the cells have been solved
*
* @access private
* @return void
*/
private function _checkAllSolved(){
// pre assign all solved as true
$allSolved = true;
// loop for rows
for ($i = 0; $i < 9; $i++ ){
// loop for columns
for ($j = 0; $j < 9; $j++ ){
// if allSolved is still true an the cell iXj is not
if ( $allSolved and !$this -> _solvedParts[$i][$j] ){
// set all solved as false
$allSolved = false;
}
}
}
// copy the value of allSolved into _solved.
$this -> _solved = $allSolved;
}
/**
* _solveIfSolveable Method
*
* Solve a single cell $rowx$col if it is solveable using
* available probable datas
*
* @access private
* @param int $row 0-8
* @param int $col 0-8
* @return bool
*/
private function _solveIfSolveable ($row, $col){
// if there is only one probable value for the cell $rowx$col
if ( count ($this -> _probable[$row][$col]) == 1 ){
// copy the only possible value to $value
$value = $this -> _probable[$row][$col][0];
// set the value of cell $rowx$col as $value an update solvedParts
$this -> _setValueForCell ($row, $col, $value);
// return true as solved
return true;
}
// pre assign $value as 0. ie; not solved
$value = 0;
// loop through all the possible values for $row x $col
// and check if any possiblity can be extracted from it
// by checking if its possible for the same number to be
// positioned anywhere else thus confilicting with current
// cell. If a possibility is not a possibility for any other
// cell in the confilicting places then it is the value for
// current cell
foreach ($this -> _probable[$row][$col] as $possible){
// a try-catch exception handling used here
// as a control statement for continuing the main loop
// if a value is possible in some place.
try{
// loop through the current column
for ($i = 0; $i < 9; $i++ ){
// if the cell is solved continue the loop
if ($this -> _currentSudoku[$i][$col] != 0)
continue;
// if the possible is also possible in the $i x $col cell
// then throw a ContinueException to continue the outer loop
if (in_array($possible, $this -> _probable[$i][$col]))
throw new ContinueException ("Exists");
}
// loop through the current row
for ($i = 0; $i < 9; $i++ ){
// if the cell is solved continue the loop
if ($this -> _currentSudoku[$row][$i] != 0)
continue;
// if the possible is also possible in the $i x $col cell
// then throw a ContinueException to continue the outer loop
if (in_array($possible, $this -> _probable[$row][$i]))
throw new ContinueException ("Exists");
}
// find the start of the 3x3 grid with $row x $col cell
$gridRowStart = $this -> _findGridStart($row);
$gridColStart = $this -> _findGridStart($col);
// loop row through the current 3x3 grid
for ($i = $gridRowStart; $i < $gridRowStart + 3; $i++){
// loop column through the current 3x3 gri
for ($j = $gridColStart; $j < $gridColStart + 3; $j++){
// if its the current $row x $col cell then
// continue the loop
if ($i == $row && $j == $col )
continue;
// if the cell is already solved then
// continue the loop
if ($this -> _currentSudoku[$row][$i] != 0)
continue;
// if the possible is also possible in the
// $i x $j cell then throw a ContinueException
// to continue the outer loop
if (in_array($possible, $this -> _probable[$i][$j]))
throw new ContinueException ("Exists");
}
}
// if the loop is not continued yet,
// then that means this possible value is
// not possible in any other conflicting
// cells. So assign the value of $value to
// $possible and break the loop.
$value = $possible;
break;
}catch (ContinueException $e){
// if a ContinueException is thrown then contine
// the outer loop
continue;
}
}
// if the value of $value is not 0 then the value of
// the cell is $value.
if ($value != 0){
// set the value of cell $rowx$col as $value an update solvedParts
$this -> _setValueForCell ($row, $col, $value);
// return true as solved
return true;
}
// return false as not solved yet.
return false;
}
/**
* _setValueForCell Method
*
* If a cell is solved then update the value for
* that cell, and also update the {@link _solvedParts}.
*
* @access private
* @param int $row 0-8
* @param int $col 0-8
* @param int $value 1-9
* @return void
*/
private function _setValueForCell($row, $col, $value){
// update the solved parts in _currentSudoku.
$this -> _currentSudoku[$row][$col] = $value;
// update the corresponding _solvedParts.
$this -> _solvedParts[$row][$col] = true;
}
/**
* _findAllProbables Method
*
* Find all possible values for any given cell using
* other already solved or given cell values.
*
* @access private
* @param int $row 0-8
* @param int $col 0-8
* @return void
*/
private function _findAllProbables ($row, $col){
// initially set the $probable as array 1 to 9.
$probable = range(1,9);
// loop through current column
for ($i = 0; $i < 9; $i++ )
// if the cell $i x $col is solved and the value of
// cell $ix$col is in the $probable array then remove
// that element.
if (
( $current = $this -> _currentSudoku[$i][$col] ) != 0
and
( $key = array_search($current, $probable) ) !== false
)
unset ($probable[$key]);
// loop through the current row
for ($i = 0; $i < 9; $i++ )
// if the cell $row x $i is solved and the value of
// cell $rowx$i is in the $probable array then remove
// that element.
if (
( $current = $this -> _currentSudoku[$row][$i] ) != 0
and
( $key = array_search($current, $probable) ) !== false
)
unset ($probable[$key]);
// find the start of the 3x3 grid with $row x $col cell
$gridRowStart = $this -> _findGridStart($row);
$gridColStart = $this -> _findGridStart($col);
// loop row through the current 3x3 grid
for ($i = $gridRowStart; $i < $gridRowStart + 3; $i++)
// loop column through the current 3x3 grid
for ($j = $gridColStart; $j < $gridColStart + 3; $j++)
// if the cell $i x $j is solved and the value of
// cell $ix$j is in the $probable array then remove
// that element.
if (
( $current = $this -> _currentSudoku[$i][$j] ) != 0
and
( $key = array_search($current, $probable) ) !== false
)
unset ($probable[$key]);
// Store the rest of the probable values to
// _probable[$row][$col]
$this -> _probable[$row][$col] = array_values($probable);
}
/**
* _findGridStart Method
*
* Find the start of the 3x3 grid in which the value
* comes
*
* @access private
* @param int $value 0-9
* @return int
*/
private function _findGridStart ($value){
// return the start of the current 3x3 grid
return floor( $value / 3 ) * 3;
}
}
/**
* <i>ContinueException</i> class
*
* Extends Exception. Used to throw exception for
* continue the outer most loop.
*
*/
Class ContinueException extends Exception{}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T15:19:09.917",
"Id": "2579",
"Score": "0",
"body": "Please include the source code you want reviewed in your post next time, don't just link to it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T23:42:33.027",
"Id": "2585",
"Score": "0",
"body": "And make sure you maintain correct indentation. It's painful to read all starting in the first column."
}
] | [
{
"body": "<p>Here's a few comments on the code rather than the algorithm - I'll leave that to someone else :)</p>\n\n<p><strong>Commenting</strong></p>\n\n<ul>\n<li><p>Quite a few comments repeat what the code does. For example:</p>\n\n<pre><code>// initially set the $probable as array 1 to 9. \n$probable = range(1,9);\n</code></pre></li>\n<li>There are a few spelling/grammatical mistakes in your comments and function names\n<ul>\n<li>Weather should be whether.</li>\n<li>completly should be completely</li>\n<li>confilicting should be conflicting</li>\n<li>_findPosibilites() should be _findPossibilities()</li>\n</ul></li>\n</ul>\n\n<p><strong>For loops</strong></p>\n\n<ul>\n<li>for loops in _findAllProbables and _updateSolved don't have braces. I think it'd be more readable and less liable to introducing bugs if you put braces in; especially on nested for loops.</li>\n</ul>\n\n<p><strong>Input</strong></p>\n\n<p>How come you've separated input and solve? Is there any case where you'd want to call one without the other? What happens if you call solve when there isn't any input given? A better interface in my opinion would be:</p>\n\n<pre><code> solve($input)\n</code></pre>\n\n<p><strong>_checkAllSolved</strong></p>\n\n<p>Would this be better returning a boolean? You could then get rid of the <code>$this->_solved</code> I think. You should certainly return earlier on ln. 268. In fact wouldn't it be better to just store the number you have solved?</p>\n\n<p>Hope that helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-27T13:56:10.273",
"Id": "1491",
"ParentId": "1489",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-27T12:48:52.290",
"Id": "1489",
"Score": "4",
"Tags": [
"php",
"php5",
"sudoku"
],
"Title": "Sudoku solving class in PHP"
} | 1489 |
<p>In the absence of a full-fledged tutorial, I am teaching myself to program in the <a href="http://factorcode.org/">Factor</a> language by writing a bunch of functions that I will eventually use in command-line scripts.</p>
<p>One common operation I like to perform is to change the case of names of files contained in a given directory to uppercase or lowercase. I wrote the following code to perform this operation in Factor:</p>
<pre><code>USING: fry kernel io.directories sequences unicode.case ;
IN: util.directories
: move-each-directory-file>lower ( pathname -- )
[ dup >lower ] move-each-directory-file ;
: move-each-directory-file>upper ( pathname -- )
[ dup >upper ] move-each-directory-file ;
: each-directory-file ( pathname quot -- )
'[ [ @ ] each ] with-directory-files ; inline
: move-each-directory-file ( pathname quot -- )
'[ @ move-file ] each-directory-file ; inline
</code></pre>
<p>I have tried to factor as much code as possible into a reusable vocabulary. I look forward to suggestions for improvement.</p>
| [] | [
{
"body": "<p>Comments! Comments are good, especially to people who are just learning Factor right now. Admittedly, for Factor, it's pretty readable -- I finally got it, after staring a while and doing lots of Googling -- but comments are always nice.</p>\n\n<p><del>I can't find anything about the <code>: name>something ( etc -- etc )</code> word syntax online -- namely, the <code>>something</code> part. Because of that, I'm just gonna assume that it's good syntax and move on.</del> Alright, I finally found it! And yes, that's good syntax -- you're supposed to use <code>a>b</code> for functions converting <code>a</code> to <code>b</code>, and that's exactly what you do. It might be better called <code>directory-file-names>upper</code>/<code>>lower</code>, but that's just personal preference.</p>\n\n<p>It looks good, though. After figuring out how Factor works, it's pretty readable (for Factor), and actually makes me want to use the language more. Plus, as far as I can tell, you're following <a href=\"http://concatenative.org/wiki/view/Factor/Coding%20Style\" rel=\"nofollow\">the official coding style</a> to the letter. Well done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-08T19:44:57.140",
"Id": "336622",
"Score": "0",
"body": "I ended up not using Factor much more, but I did write [my own concatenative language](https://github.com/nic-hartley/concaten), so I think that counts."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T02:04:13.203",
"Id": "94955",
"ParentId": "1493",
"Score": "3"
}
},
{
"body": "<p>I've spent a good few hours figuring out Factor.\nIt's a very interesting language.</p>\n\n<p>Your implementation seems very good and straightforward:</p>\n\n<ul>\n<li><p>Using higher order functions, essentially passing a name transformation operation to a file move operation, which in turn is passed to a file iterator operation. Thanks to this, there is no duplicated logic anywhere in this code</p></li>\n<li><p>The names you came up with are all top-notch:</p>\n\n<ul>\n<li><code>each-directory-file</code>: consistent with <code>with-directory-files</code> from <code>io.directories</code>, and <code>each</code> in the language itself</li>\n<li><code>move-each-directory-file</code>, ...<code>>lower</code>, ...<code>>upper</code>: all doing exactly what they say, the <code>move-</code> prefix and <code>>lower</code>, <code>>upper</code> suffixes all makes sense</li>\n<li><code>pathname</code>: good, but \"path\" might be slightly better, to be consistent with <a href=\"http://docs.factorcode.org/content/word-with-directory-files,io.directories.html\" rel=\"nofollow\"><code>with-directory-files</code></a></li>\n<li><code>quot</code>: consistent with many examples in the language</li>\n</ul></li>\n</ul>\n\n<p>When I tried to run the program,\nthe compiler complains:</p>\n\n<blockquote>\n<pre><code>4: : move-each-directory-file>lower ( pathname -- )\n5: [ dup >lower ] move-each-directory-file ;\n ^\nNo word named “move-each-directory-file” found in current vocabulary search path\n</code></pre>\n</blockquote>\n\n<p>It seems you cannot define a word in terms of another word that is not yet known. I can load your program if I reorder the declarations like this:</p>\n\n<pre><code>USING: fry kernel io.directories sequences unicode.case ;\nIN: util.directories\n\n: each-directory-file ( pathname quot -- )\n '[ [ @ ] each ] with-directory-files ; inline\n\n: move-each-directory-file ( pathname quot -- )\n '[ @ move-file ] each-directory-file ; inline\n\n: move-each-directory-file>lower ( pathname -- )\n [ dup >lower ] move-each-directory-file ;\n\n: move-each-directory-file>upper ( pathname -- )\n [ dup >upper ] move-each-directory-file ;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T11:15:50.567",
"Id": "173195",
"Score": "1",
"body": "Well technically you could add one other function which calls `dup` while passing in the case conversion function. \"Pathnames\" are also what's used in the documentation, so that's arguably better than \"path\". Another interesting thing is the documentation facilities, so for each function it's possible to add add very detailed docstrings, the [scaffolding tool](http://docs.factorcode.org/content/article-tools.scaffold.html) will generate a skeleton for a vocabulary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T11:35:45.157",
"Id": "173197",
"Score": "0",
"body": "@ferada if you write up an answer on all that I would upvote"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T09:42:14.333",
"Id": "94979",
"ParentId": "1493",
"Score": "3"
}
},
{
"body": "<p>Comment to @janos now as a full post:</p>\n\n<ul>\n<li><p>Technically you could add one other function which calls <code>dup</code> while\npassing in the case conversion function. The code I had saved some\ntime ago (<code>directories.factor</code>) looked like this (btw. I could load\nthis with <code>USE: util.directories</code> without any problems:</p>\n\n<pre><code>USING: fry kernel io.directories sequences unicode.case ;\nIN: util.directories\n\n: each-directory-file ( pathname quot -- )\n '[ [ @ ] each ] with-directory-files ; inline\n\n: move-each-directory-file ( pathname quot -- )\n '[ @ move-file ] each-directory-file ; inline\n\n: transform-each-directory-file ( pathname quot -- )\n '[ dup @ ] move-each-directory-file ; inline\n\n: move-each-directory-file>lower ( pathname -- )\n [ >lower ] transform-each-directory-file ;\n\n: move-each-directory-file>upper ( pathname -- )\n [ >upper ] transform-each-directory-file ;\n</code></pre></li>\n<li><p>\"Pathnames\" are also\n<a href=\"http://docs.factorcode.org/content/article-io.pathnames.html\" rel=\"nofollow\">what's used in the documentation</a>,\nso that's using the \"correct\" naming convention.</p></li>\n<li><p>Another interesting thing is the documentation facilities, so for each\nfunction it's possible to add add very detailed docstrings, the\n<a href=\"http://concatenative.org/wiki/view/Scaffold%20tool\" rel=\"nofollow\">scaffolding</a>\n<a href=\"http://docs.factorcode.org/content/article-tools.scaffold.html\" rel=\"nofollow\">tool</a>\nwill generate a skeleton for a vocabulary. After running\n<code>USE: tools.scaffold</code> and\n<code>\"resource:work\" \"util.directories\" scaffold-vocab</code> and filling in the\nspots I ended up with another file (<code>directories-docs.factor</code>) like\nthis:</p>\n\n<pre><code>USING: help.markup help.syntax kernel quotations ;\nIN: util.directories\n\nHELP: each-directory-file\n{ $values\n { \"pathname\" \"a pathname string\" } { \"quot\" quotation }\n}\n{ $description \"Run the quotation on each filename in a directory.\" } ;\n\nHELP: move-each-directory-file\n{ $values\n { \"pathname\" \"a pathname string\" } { \"quot\" quotation }\n}\n{ $description \"Move each file in a directory to the return value of the quotation running on the filename.\" } ;\n\nHELP: move-each-directory-file>lower\n{ $values\n { \"pathname\" \"a pathname string\" }\n}\n{ $description \"Rename each file in a directory to lower case.\" } ;\n\nHELP: move-each-directory-file>upper\n{ $values\n { \"pathname\" \"a pathname string\" }\n}\n{ $description \"Rename each file in a directory to upper case.\" } ;\n\nHELP: transform-each-directory-file\n{ $values\n { \"pathname\" \"a pathname string\" } { \"quot\" quotation }\n}\n{ $description \"Rename each file in a directory to the return value of running the quotation on the filename.\" } ;\n\nARTICLE: \"util.directories\" \"util.directories\"\n{ $vocab-link \"util.directories\" }\n;\n\nABOUT: \"util.directories\"\n</code></pre>\n\n<p>This is really nice to document everything in more detail and access it\nvia the inbuilt browser etc.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-29T13:15:55.263",
"Id": "95082",
"ParentId": "1493",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T00:13:49.270",
"Id": "1493",
"Score": "33",
"Tags": [
"file-system",
"factor-lang"
],
"Title": "Factor script to change case of all filenames in a directory"
} | 1493 |
<p>After reading an article on Skull Security mentioning the potential weakness of php's mt_rand function because of weak auto-seeding (<a href="http://ow.ly/4nrne" rel="nofollow">http://ow.ly/4nrne</a>), I decided to see what -- if any -- entropy I could find available from within php. The idea is to have enough (weak) sources that even if one or two are manipulated, lost or recovered, there's enough left to thwart brute force against the resulting passwords later.</p>
<p>Hopefully the result is both readable and usable, although I don't expect it to be production-quality.</p>
<pre><code><?php
/**
* Return a random password.
*
* v1.01
* Jumps through many hoops to attempt to overcome autoseed weakness of php's mt_rand function
*
*/
function myRandomPassword() {
// Change this for each installation
$localsecret = 'qTgppE9T2c';
// Determine length of generated password
$pwlength = 10;
// Character set for password
$pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';
$l = strlen( $pwchars ) - 1;
// Get a little bit of entropy from sources that should be inaccessible to outsiders and non-static
$dat = getrusage(); // gather some information from the running system
$datline = md5(implode($dat)); // wash using md5 -- it's fast and there's not enough entropy to warrant longer hash
$hardToGuess = $datline;
$self = __FILE__; // a file the script should have read access to (itself)
$stat = stat($self); // information about file such as inode, accessed time, uid, guid
$statline = md5(implode($stat)); // wash
$hardToGuess .= $statline;
$preseed = md5(microtime()) . getmypid() . $hardToGuess . memory_get_usage() . disk_free_space('.') . $localsecret;
$seed = sha1( $preseed ); // final wash, longer hash
// Seed the mt_rand() function with a better seed than the standard one
mt_srand ($seed);
// Pick characters from the lineup, using the seeded mt_rand function
$pw = '';
for ( $i = 0; $i < $pwlength; $i++ ) {
$pw .= $pwchars{ mt_rand( 0, $l ) };
}
// Return the result
return $pw;
}
echo myRandomPassword();
?>
</code></pre>
<p>Revision 1.01 adds a local secret.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T10:34:43.660",
"Id": "2596",
"Score": "0",
"body": "Just realized, while reviewing my own code the day after, that the whole thing is currently useless because the mt_srand function expects an integer as seed."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T11:04:40.310",
"Id": "2598",
"Score": "0",
"body": "It's easy to cast the seed as a number (using hexdec, for example) but the problem is that the number will be too large to fit as an integer and become a float."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T11:12:12.440",
"Id": "2599",
"Score": "0",
"body": "So, basically, I could use a suggestion on how to reduce the float value to an integer that fits into the current system's integer size, but does not lose too much of the gathered entropy in the process."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-02T12:14:03.150",
"Id": "2800",
"Score": "0",
"body": "Having done some searching, I believe the best implementation of a crc64-algorithm is currently this one, written in C:\nhttp://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/\nAll I have to do now is convert it to php. Too bad I don't know C, this is going to be a challenge."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-03T10:34:06.420",
"Id": "2847",
"Score": "0",
"body": "OK, so I learned elsewhere that the rand() and mt_rand() functions are actually separately seeded. This should mean that using both means you have to attack both, at the same time, to recover the result (unless attacking the 32-bit-problem). Essentially, we can do no worse by adding rand() to the mix, and probably make attacks quite a bit harder. I've implemented this by using str_shuffle on the character set, because that invokes the rand() function, not mt_rand(), according to the documentation. As a side effect, this code now \"works\" on 64-bit systems, but very weakly."
}
] | [
{
"body": "<p>I actually don't get the point of injecting so much system information into the <code>mt_srand</code> function. Looks like a total (and maybe even pointless) paranoia :)</p>\n\n<p>But here you go with a cleaner code:</p>\n\n<pre><code><?php\n/**\n* Random password generator\n* v2.0\n*/\n\ndefine('APP_SECRET_KEY', 'qTgppE9T2c');\n\nfunction randomPassword($length=10) {\n $charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';\n $charsetSize = strlen($charset) - 1;\n\n // Seeding the generator with a bunch of different system data and the secret key\n mt_srand(crc32(md5(microtime())\n . getmypid()\n . md5(implode(getrusage()))\n . md5(implode(stat(__FILE__)))\n . memory_get_usage()\n . disk_free_space('.')\n . APP_SECRET_KEY)\n );\n\n $password = '';\n foreach (range(1, $length) as $_)\n $password .= $charset{mt_rand(0, $charsetSize)};\n\n return $password;\n}\n\necho randomPassword(), \"\\n\";\n</code></pre>\n\n<p>Maybe you'll like the more perverted superslow version which returns CRC32 of randomly ordered entropy each time you generate a new symbol.</p>\n\n<pre><code><?php\n/**\n* Random password generator\n* v2.1\n*/\n\nfunction randomPassword($length=10) {\n $charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';\n $charsetSize = strlen($charset) - 1;\n\n $seeders = array(\n function () { return md5(microtime()); },\n function () { return md5(getmypid()); },\n function () { return md5(implode(getrusage())); },\n function () { return memory_get_usage(); },\n function () { return disk_free_space('.'); }\n );\n\n $randomSeed = function () use ($seeders) {\n shuffle($seeders);\n\n $entropy = '';\n foreach ($seeders as $seeder)\n $entropy .= $seeder();\n\n return crc32($entropy);\n };\n\n $password = '';\n foreach (range(1, $length) as $_) {\n mt_srand($randomSeed());\n $password .= $charset{mt_rand(0, $charsetSize)};\n }\n\n return $password;\n}\n\necho randomPassword(), \"\\n\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T23:29:50.453",
"Id": "2762",
"Score": "0",
"body": "Thanks for the input! Your code is certainly much nicer than mine, in several ways. And the idea of using crc32 to cast the entropy into an integer is a good one -- except for one small thing. The primary point of the excersize is to increase both the entropy and the pool of intitial seed states to more than 32 bit."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T23:37:11.977",
"Id": "2763",
"Score": "0",
"body": "I understand why it may seem pointless to seed the random number generator in a stronger fashion than what PHP already does. But the problem is that because the random generator is actually only pseudo-random, based on the seed, it will return the exact same series of values every time if called with the same seed.This means that if you know the function, and you know that the seed it limited to only 32 bits, this means that there's only (2^32=) 4.294.967.296 potential passwords, which is a lot less than you can check in a reasonable time frame."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T23:42:09.400",
"Id": "2764",
"Score": "0",
"body": "More information on the problems of weak seeds at http://www.suspekt.org/2008/08/17/mt_srand-and-not-so-random-numbers/ and the blog I linked in the original post."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T15:48:54.877",
"Id": "1584",
"ParentId": "1494",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1584",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T02:19:28.757",
"Id": "1494",
"Score": "4",
"Tags": [
"php",
"security",
"random"
],
"Title": "Password-generation function using custom seed"
} | 1494 |
<p>I'm making a scripting language parser and it's shaping up well but it takes about 30ms to do 30 or so odd/even checks.</p>
<p><code>Profiler</code> tells me that it's taking most of the time in the <code>InvokeOperator.Operate</code> function but that doesn't tell me a lot because the Operate call the Run method on the <code>CodeBlock</code> which in turn again calls the Operate call and makes it very hard to actually determine what's taking as long.</p>
<p>Here's the <a href="https://github.com/LukaHorvat/Kento" rel="nofollow">Github repo</a></p>
<p>Here are the most important bits of the code:</p>
<pre><code>Stack<Token> solvingStack = new Stack<Token>();
for ( int i = 0 ; i < value.Count ; ++i )
{
if ( value[ i ] is Operator )
{
Operator op = (Operator)value[ i ];
if ( op.Type == OperatorType.PrefixUnary || op.Type == OperatorType.SufixUnary )
{
op.Operate( ( solvingStack.Pop() as Value ), new NoValue() );
} else
{
Value second = (Value)solvingStack.Pop();
Value result = op.Operate( ( solvingStack.Pop() as Value ), second );
solvingStack.Push( result );
}
} else
{
solvingStack.Push( value[ i ] );
}
}
Compiler.ExitScope();
if ( solvingStack.Count == 0 ) return new NoValue();
else return (Value)solvingStack.Peek();
</code></pre>
<p>It's how the code is parsed after the infix expression is turned into RPN.
A token can be an operator or a value and a value can be a literal, identifier, <code>codeblock</code>.</p>
<p>A somewhat special case is a function because it's not parsed to RPN directly but only the code inside of it is. Then is there's an invoke operator, it takes the array of arguments that was provided and the function before it and runs the function (which inherits from <code>CodeBlock</code>, so it also runs the same thing that is shown here).</p>
<p>What each operator does on different types of values is determined by the operator itself in the Operators.cs file.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T09:06:33.807",
"Id": "2594",
"Score": "3",
"body": "see `Make sure you include your code in your question` part in [FAQ](http://codereview.stackexchange.com/faq)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T12:14:14.123",
"Id": "2600",
"Score": "3",
"body": "As @Snowbear points out, we do require questions to contain the relevant code inside the post. If you can edit your post to contain the most important parts of the code and a summary of the ones you left out, so that the code can be meaningfully reviewed based on the code in the question, please do so. If that's not possible, I'm afraid this question is not appropriate here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T18:30:37.977",
"Id": "2606",
"Score": "0",
"body": "Is this the InvokeOperator.Operate method?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T21:22:37.563",
"Id": "2609",
"Score": "0",
"body": "@Michael, no, it's `CodeBlock.Run()` method"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T21:26:23.970",
"Id": "2610",
"Score": "0",
"body": "`30 ms` doesn't sound too bad."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T04:43:52.820",
"Id": "2625",
"Score": "0",
"body": "Could you post how you wrote the odd/even checks?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T09:14:00.830",
"Id": "2633",
"Score": "0",
"body": "Well, there's a function that mods the number it gets by 2 and checks the result. Nothing complicated really."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T13:18:49.127",
"Id": "2641",
"Score": "1",
"body": "@Darwin, replace it with `(num & 1) == 1`, it should be faster"
}
] | [
{
"body": "<p>I suggest you try using a profiler of some sort in order to determine exactly where the bottleneck is. Once you do that, it will much easier to find how to avoid it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T09:12:49.770",
"Id": "2632",
"Score": "0",
"body": "Profiler tells me that it's taking most of the time in the InvokeOperator.Operate function but that doesn't tell me a lot because the Operate call the Run method on the CodeBlock which in turn again calls the Operate call and makes it very hard to actually determine what's taking as long."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T10:32:06.597",
"Id": "2636",
"Score": "0",
"body": "What you need to do is profile the function calls inside the operate call, then figure out which one exactly is taking so long. Then go into that and do the same thing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T00:44:23.530",
"Id": "1511",
"ParentId": "1495",
"Score": "1"
}
},
{
"body": "<p>I am not sure if these are bottlenecks, but they are at least performance improvements.</p>\n\n<ol>\n<li><p>Replace <code>Stack<Token></code> with <code>Stack<Value></code> since you are only pushing/popping <code>Value</code>. This way there is no need to do expensive casts.</p></li>\n<li><p>You can replace</p>\n\n<pre><code>if ( value[ i ] is Operator )\n{\n Operator op = (Operator)value[ i ];\n</code></pre>\n\n<p>with</p>\n\n<pre><code>Operator op = value[ i ] as Operator;\nif ( op != null ) // it was an Operator\n</code></pre>\n\n<p>to have only one typecheck (<code>x as y</code>) instead of two (<code>x is y</code> and <code>(y) x</code>).</p></li>\n<li><p>You can replace </p>\n\n<pre><code>for ( int i = 0 ; i < value.Count ; ++i )\n</code></pre>\n\n<p>with</p>\n\n<pre><code>foreach(Token item in value)\n</code></pre>\n\n<p>to eliminate the index operations <code>value[ i ]</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T07:10:48.357",
"Id": "2179",
"ParentId": "1495",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-28T07:14:24.023",
"Id": "1495",
"Score": "7",
"Tags": [
"c#",
"parsing"
],
"Title": "Scripting language parser"
} | 1495 |
<p>I have the following code for reading <a href="http://htk.eng.cam.ac.uk/" rel="nofollow">HTK</a> feature files. The code below is working completely correct (verified it with unit tests and the output of the original HTK toolkit).</p>
<pre><code>from HTK_model import FLOAT_TYPE
from numpy import array
from struct import unpack
def feature_reader(file_name):
with open(file_name, 'rb') as in_f:
#There are four standard headers. Sample period is not used
num_samples = unpack('>i', in_f.read(4))[0]
sample_period = unpack('>i', in_f.read(4))[0]
sample_size = unpack('>h', in_f.read(2))[0]
param_kind = unpack('>h', in_f.read(2))[0]
compressed = bool(param_kind & 02000)
#If compression is used, two matrices are defined. In that case the values are shorts, and the real values are:
# (x+B)/A
A = B = 0
if compressed:
A = array([unpack('>f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE)
B = array([unpack('>f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE)
#The first 4 samples were the matrices
num_samples -= 4
for _ in xrange(0,num_samples):
if compressed:
yield ((array( unpack('>' + ('h' * (sample_size//2)),in_f.read(sample_size)) ,dtype=FLOAT_TYPE) + B) / A)
else:
yield (array( unpack('>' + ('f' * (sample_size//4)),in_f.read(sample_size)), dtype=FLOAT_TYPE))
</code></pre>
<p>How can I speed up this code, are there things I should improve in the code?</p>
| [] | [
{
"body": "<pre><code> data = in_f.read(12)\n num_samples, sample_period, sample_size, param_kind = unpack('>iihh', data)\n A = B = 0\n if compressed:\n A = array('f')\n A.fromfile(in_f, sample_size/2)\n B = array('f')\n B.fromfile(in_f, sample_size/2)\n #The first 4 samples were the matrices\n num_samples -= 4\n</code></pre>\n\n<p>And so on</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T12:27:11.493",
"Id": "1500",
"ParentId": "1496",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-28T07:57:03.323",
"Id": "1496",
"Score": "5",
"Tags": [
"python",
"performance",
"file",
"numpy",
"serialization"
],
"Title": "Reading a binary file containing periodic samples"
} | 1496 |
<p>I have an extension that implements all the BinaryReader/BinaryWriter in the Stream class. I want to create generic methods for them. Is there a nicer way of doing this?</p>
<pre><code>public static void Write<T>(this Stream stream, T num)
{
if (num is byte)
{
stream.Write((byte)(object)num);
}
else if (num is Int16)
{
stream.Write((Int16)(object)num);
}
else if (num is Int32)
{
stream.Write((Int32)(object)num);
}
}
public static T Read<T>(this Stream stream)
{
object ret = null;
if (typeof(T) == typeof(byte))
ret = stream.ReadInt8();
else if (typeof(T) == typeof(Int16))
ret = stream.ReadInt16();
else if (typeof(T) == typeof(Int32))
ret = stream.ReadInt32();
if (ret == null)
throw new ArgumentException("Unable to read type - " + typeof(T));
return (T)ret;
}
</code></pre>
<p>Now using this for the Read method.</p>
<pre><code>static Dictionary<Type, Func<Stream, object>> ReadFuncs = new Dictionary<Type, Func<Stream, object>>()
{
{typeof(bool), s => s.ReadBoolean()},
{typeof(byte), s => s.ReadInt8()},
{typeof(Int16), s => s.ReadInt16()},
{typeof(Int32), s => s.ReadInt32()},
{typeof(Int64), s => s.ReadInt64()},
{typeof(string), s => s.ReadString()},
};
public static T Read<T>(this Stream stream)
{
if (ReadFuncs.ContainsKey(typeof(T)))
return (T)ReadFuncs[typeof(T)](stream);
throw new NotImplementedException();
}
</code></pre>
| [] | [
{
"body": "<p>I'm guessing you defined more write methods than this? Otherwise the <code>Write()</code> would call itself recursively infinitely. You probably have overloads for every supported type, <strong>making the generic write method superfluous</strong>. This would also explain the weird casting you are doing. I'm guessing an overloaded function with a specific type has precedence over a generic method, which is why it could work. This however, doesn't make it a clean solution.</p>\n\n<p>Your <code>Read()</code> method seems to be more useful. Instead of throwing a <code>ArgumentException</code> I would prefer throwing a <code>NotSupportedException</code>.</p>\n\n<p>As a sidenote, are you sure you want to make these extension methods of <code>Stream</code> and not some more specific stream? Stream can be <strong>any</strong> type of stream.</p>\n\n<hr>\n\n<p>In what way is this an improvement over using <code>BinaryWriter</code>/<code>BinaryReader</code>? For the purposes I gather from your code I would only create a <code>Read<T></code> extension method for BinaryReader.</p>\n\n<p>If you feel like experimenting a bit, there might be a more performant/cleaner solution, although you'll have to benchmark to be sure. You could create a <code>Dictionary<Type, Func<object>></code> to hold a matching 'reader' for every type. Initializing the delegates to store in this dictionary is the tough part, on which information can be found <a href=\"https://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx\" rel=\"nofollow noreferrer\">in this article</a>. Most likely this is not worth the effort, although it still is a very interesting article. :) Be sure to also check out the same solution implemented by using Expression Trees in the comments of the article. For a similar implementation example I did, check out <a href=\"https://codereview.stackexchange.com/q/1070/2254\">this question</a> I posted on Code Review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T12:53:46.190",
"Id": "2601",
"Score": "0",
"body": "Well BinaryReader/Writer both take a Stream so I figured I would make the extension for Stream. The Write is really just because I want to do Write<byte>(5) instead of Write((byte)5). Is there any nicer way to do the Read function though?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T13:18:13.907",
"Id": "2602",
"Score": "0",
"body": "@High: I updated my answer with a possible alternate solution, although for the small amount of supported types from BinaryReader, your current implementation is probably better."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T00:26:32.510",
"Id": "2612",
"Score": "0",
"body": "I don't think I will end up using the Write generic but I still created an extension for regular Write. Reason is because it does not require you to create an instance of an object to read from a stream. Also BinaryReader/Writer both Close the stream when they are disposed which I do not like. I updated my question with what I am assuming your second suggestion is."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T09:47:30.347",
"Id": "2634",
"Score": "0",
"body": "@High: Ow .. that makes a lot more sense, .. i was trying to make things too complicated. ;p Yes that is along the lines I meant."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T12:46:21.363",
"Id": "1501",
"ParentId": "1498",
"Score": "5"
}
},
{
"body": "<p>I know your trying to simplify your code, but I think it will be better to go the opposite way, avoid generic types, and doing specific type procedures:</p>\n\n<pre><code>public static void WriteByte(this Stream stream, byte num) { ... }\npublic static void WriteInt16(this Stream stream, Int16 num) { ... }\npublic static void WriteInt32(this Stream stream, Int32 num) { ... }\n</code></pre>\n\n<p>Why. Because its very easy to call the wrong method, calling \"Write(<int32>)\" instead of \"Write(<byte>)\". And in some scenario, the developer may not treat those integer types as the same.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T00:06:05.057",
"Id": "2611",
"Score": "0",
"body": "The generics are separate from the other Write methods so I am not worried about calling the wrong one. Also WriteByte is not possible due to the fact that Stream already has a method by that name that returns an integer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:41:33.963",
"Id": "1505",
"ParentId": "1498",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1501",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T11:22:37.440",
"Id": "1498",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Generic BinaryReader/Writer Read/Write methods"
} | 1498 |
<p>I have the following code which uses four if statements to check the value in four different combo boxes. </p>
<pre><code>if (!String.IsNullOrEmpty(tx_cmb_Circuits1.Text.Trim()))
emp.CircuitEmail_Group_Rels.Add(
new Circuit_Email_Group_Rel
{
Circuits = (Circuits) tx_cmb_Circuits1.SelectedItem,
Group = emp
});
if (!String.IsNullOrEmpty(tx_cmb_Circuits2.Text.Trim()))
emp.CircuitEmail_Group_Rels.Add(
new Circuit_Email_Group_Rel
{
Circuits = (Circuits) tx_cmb_Circuits2.SelectedItem,
Group = emp
});
if (!String.IsNullOrEmpty(tx_cmb_Circuits3.Text.Trim()))
emp.CircuitEmail_Group_Rels.Add(
new Circuit_Email_Group_Rel
{
Circuits = (Circuits) tx_cmb_Circuits3.SelectedItem,
Group = emp
});
if (!String.IsNullOrEmpty(tx_cmb_Circuits4.Text.Trim()))
emp.CircuitEmail_Group_Rels.Add(
new Circuit_Email_Group_Rel
{
Circuits = (Circuits) tx_cmb_Circuits4.SelectedItem,
Group = emp
});
</code></pre>
<p>Is there are shorter way to do the same. Please review my code.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T15:54:38.913",
"Id": "2751",
"Score": "0",
"body": "your tabs are very annoying. only 4 spaces are needed for indentation."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T14:25:23.647",
"Id": "2979",
"Score": "2",
"body": "I'd go with 2 spaces..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:33:09.587",
"Id": "99256",
"Score": "0",
"body": "If you are using C# 4.0, you can use the `String.IsNullOrWhiteSpace` method instead of `IsNullOrEmpty` and `Trim`."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T12:07:02.263",
"Id": "99257",
"Score": "0",
"body": "Or write your own extension method to do it if you are < 4.0."
}
] | [
{
"body": "<p>Add all items to a list and do a foreach instead.</p>\n\n<pre><code>var buttons = new List<Button>\n{\n tx_cmb_Circuits1,\n tx_cmb_Circuits2,\n ...\n};\n\nforeach ( var button in buttons )\n{\n if ( !String.IsNullOrEmpty( button.Text.Trim() ) )\n {\n emp.CircuitEmail_Group_Rels.Add(\n new Circuit_Email_Group_Rel\n {\n Circuits = (Circuits) button.SelectedItem,\n Group = emp\n } );\n }\n}\n</code></pre>\n\n<p>P.S.: Consider giving your variables better names. No real need for abbreviations like <code>tx_cmb</code> nowadays.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:32:26.010",
"Id": "1503",
"ParentId": "1502",
"Score": "13"
}
},
{
"body": "<p>Since the statements inside all the ifs are similar, you can re-factor the statements into an action such as <code>Action<Button></code> and invoke it for all the buttons.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T04:18:11.797",
"Id": "1516",
"ParentId": "1502",
"Score": "1"
}
},
{
"body": "<p>Here's another approach based on Steven Jeuris's answer:</p>\n\n<pre><code>emp.CircuitEmail_Group_Rels.AddRange(from button in buttons\n where !String.IsNullOrEmpty(button.Text.Trim())\n select new Circuit_Email_Group_Rel\n {\n Circuits = button,\n Group = button\n }).ToList());\n</code></pre>\n\n<p>The ToList() may or may not be required, depending on the CircuitEmail_Group_Rels type.\nAnd if possible, try to trim the button.Text previously. Preferably only once each time the .Text is updated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T14:25:12.597",
"Id": "2978",
"Score": "0",
"body": "Linq is appropriate here indeed. I'm trying to figure out what you mean with `ToList()` being required or not."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T16:49:39.070",
"Id": "2984",
"Score": "1",
"body": "Well, I was assuming CircuitEmail_Group_Rels was a List<Circuit_Email_Group_Rel> and in the end it was necessary to convert the select's output to a List. However after some checking, since List<T> comes from IEnumerable<T>, the .ToList() is redundant. My mistake :) Always learning!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-07T11:16:36.800",
"Id": "1714",
"ParentId": "1502",
"Score": "4"
}
},
{
"body": "<p>I'm a fan of pulling out the common operation into a function with a self-documenting name. Hard to know exactly what that name should be in this case, given the missing context, but something like this:</p>\n\n<pre><code>public void GetCircuitEmailFrom(ComboBox emailBox, MyThingy emp)\n{\n if (!String.IsNullOrEmpty(emailBox.Text.Trim()))\n emp.CircuitEmail_Group_Rels.Add(\n new Circuit_Email_Group_Rel\n {\n Circuits = (Circuits)emailBox.SelectedItem,\n Group = emp\n });\n}\npublic void foo()\n{\n GetCircuitEmailFrom(tx_cmb_Circuits1, emp);\n GetCircuitEmailFrom(tx_cmb_Circuits2, emp);\n GetCircuitEmailFrom(tx_cmb_Circuits3, emp);\n GetCircuitEmailFrom(tx_cmb_Circuits4, emp);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-08T17:13:16.167",
"Id": "1735",
"ParentId": "1502",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1503",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-28T15:17:02.837",
"Id": "1502",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Is there a shorter way to write the following if statements?"
} | 1502 |
<p>I have been trying to learn more about using bits/bitfields/bitmask or whatever you call them exactly in PHP for different settings and permissions. With the help of others, I have come up with this class. It has come a long way from when I started it but I am looking for any ideas on how to improve it more.</p>
<pre><code><?php
abstract class BitField {
private $value;
public function __construct($value=0) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function get($n) {
if (is_int($n)) {
return ($this->value & (1 << $n)) != 0;
}else{
return 0;
}
}
public function set($n, $new=true) {
$this->value = ($this->value & ~(1 << $n)) | ($new << $n);
}
public function clear($n) {
$this->set($n, false);
}
}
class UserPermissions_BitField extends BitField
{
const PERM_READ = 0;
const PERM_WRITE = 1;
const PERM_ADMIN = 2;
const PERM_ADMIN2 = 3;
const PERM_ADMIN3 = 4;
}
class UserPrivacySettings_BitField extends BitField
{
const PRIVACY_TOTAL = 0;
const PRIVACY_EMAIL = 1;
const PRIVACY_NAME = 2;
const PRIVACY_ADDRESS = 3;
const PRIVACY_PHONE = 4;
}
?>
</code></pre>
<p>Example usage: </p>
<pre><code><?php
$user_permissions = 0; //This value will come from MySQL or Sessions
$bf = new UserPermissions_BitField($user_permissions);
// turn these permission to on/true
$bf->set($bf::PERM_READ);
$bf->set($bf::PERM_WRITE);
$bf->set($bf::PERM_ADMIN);
$bf->set($bf::PERM_ADMIN2);
$bf->set($bf::PERM_ADMIN3);
//turn permission PERM_ADMIN2 to off/false
$bf->clear($bf::PERM_ADMIN2); // sets $bf::PERM_ADMIN2 bit to false
// check if permission PERM_READ is on/true
if ($bf->get($bf::PERM_READ)) {
// can read
echo 'can read is ON<br>';
}
if ($bf->get($bf::PERM_WRITE)) {
// can write
echo 'can write is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN)) {
// is admin
echo 'admin is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN2)) {
// is admin 2
echo 'admin 2 is ON<br>';
}
if ($bf->get($bf::PERM_ADMIN3)) {
// is admin 3
echo 'admin 3 is ON<br>';
}
?>
</code></pre>
| [] | [
{
"body": "<p>You are kind of missing the point of using bitmasks.</p>\n\n<p>You should be making use of simple bit operations.</p>\n\n<p>If each bit represents a privacy settings, then the operations should be:</p>\n\n<ol>\n<li><p>Check if a value is set, using & operator.</p>\n\n<p><code>($this->value & $n) == $n;</code></p></li>\n<li><p>Set a value using the | operator (or |=).</p>\n\n<p><code>$this->value |= $n;</code></p></li>\n<li><p>Clear a value using the & operator (or &=).</p>\n\n<p><code>$this->value &= ~$n;</code></p></li>\n</ol>\n\n<p>And then your values should be powers of 2. Usually 0 is saved for a null value or invalid value.</p>\n\n<pre><code>class UserPrivacySettings_BitField extends BitField\n{\n const PRIVACY_EMAIL = 1;\n const PRIVACY_NAME = 2;\n const PRIVACY_ADDRESS = 4;\n const PRIVACY_PHONE = 8;\n const PRIVACY_ALL = 15;\n}\n</code></pre>\n\n<p>Now the first 4 values correspond to 1 bit. And you can make use of PRIVACY_ALL by using the combination of all the other values.</p>\n\n<p>i.e. In bits</p>\n\n<pre><code>PRIVACY_EMAIL = 0001\nPRIVACY_NAME = 0010\nPRIVACY_ADDRESS = 0100\nPRIVACY_PHONE = 1000\nPRIVACY_ALL = 1111\n</code></pre>\n\n<p>This way if you set all the values individually, and then check PRIVACY_ALL, that will evaluate to true.</p>\n\n<p>Here's some revised code, with examples at the end.</p>\n\n<pre><code><?php\nabstract class BitField {\n\n private $value;\n\n public function __construct($value=0) {\n $this->value = $value;\n }\n\n public function getValue() {\n return $this->value;\n }\n\n public function get($n) {\n return ($this->value & $n) == $n;\n }\n\n public function set($n) {\n $this->value |= $n;\n }\n\n public function clear($n) {\n $this->value &= ~$n;\n }\n}\n\nclass UserPrivacySettings_BitField extends BitField\n{\n const PRIVACY_EMAIL = 1;\n const PRIVACY_NAME = 2;\n const PRIVACY_ADDRESS = 4;\n const PRIVACY_PHONE = 8;\n const PRIVACY_ALL = 15;\n}\n\n$bf = new UserPrivacySettings_BitField();\necho \"Setting PRIVACY_EMAIL<br/>\";\n$bf->set(UserPrivacySettings_BitField::PRIVACY_EMAIL);\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_EMAIL));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_NAME));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_ADDRESS));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_PHONE));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_ALL));\necho \"Setting PRIVACY_NAME<br/>\";\n$bf->set(UserPrivacySettings_BitField::PRIVACY_NAME);\necho \"Setting PRIVACY_ADDRESS<br/>\";\n$bf->set(UserPrivacySettings_BitField::PRIVACY_ADDRESS);\necho \"Setting PRIVACY_PHONE<br/>\";\n$bf->set(UserPrivacySettings_BitField::PRIVACY_PHONE);\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_EMAIL));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_NAME));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_ADDRESS));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_PHONE));\nvar_dump($bf->get(UserPrivacySettings_BitField::PRIVACY_ALL));\n</code></pre>\n\n<p>As an example, look at the values for the Error Constants in PHP. <a href=\"http://php.net/manual/en/errorfunc.constants.php\" rel=\"noreferrer\">http://php.net/manual/en/errorfunc.constants.php</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T01:36:25.867",
"Id": "2613",
"Score": "0",
"body": "jason's idea here is to pass in bit indexes (3) instead of the raw bit fields (8). Otherwise he may as well just use a raw integer."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T02:04:39.260",
"Id": "2614",
"Score": "0",
"body": "@David Harkness There doesn't seem to be much point in using bit fields at all in that case, why not use an associative array?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T02:44:28.303",
"Id": "2618",
"Score": "0",
"body": "thanks for the updated code, I will deffinately play with it, I ran some test and you code seems to be slightly faster, other then a speed increase, both your class and my original are doing the same thing right? Just you'r is less complex as mine has to get the power of 2 for the constants and your's skips this step, am i right? Thanks a bunch for the help"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T03:07:22.887",
"Id": "2619",
"Score": "0",
"body": "@jasondavis, yes they are doing the same thing but in mine the left shifting it part of the constant, whereas yours does it every time. Plus mine allows for a combination (PRIVACY_ALL is a combination of all the others). You could define the constants like `const PRIVACY_EMAIL = 1 << 0` and `const PRIVACY_NAME = 1 << 1`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T06:25:34.027",
"Id": "2629",
"Score": "0",
"body": "I would most likely use a bare int with a class that holds the pre-shifted bit field constants. This makes dealing with them really easy for the user. But if you're going to design a class to use indexes, you may as well go hole-hog. ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T00:36:02.877",
"Id": "1510",
"ParentId": "1509",
"Score": "6"
}
},
{
"body": "<p>If you really want to drink the PHP Kool-Aid, you could implement the <a href=\"http://php.net/manual/en/class.arrayaccess.php\" rel=\"nofollow\">ArrayAccess interface</a> so that clients could use</p>\n\n<pre><code>$bf[UserPermissions_BitField::PERM_READ] = true;\n...\nif ($bf[UserPermissions_BitField::PERM_READ]) { ... }\n</code></pre>\n\n<p>Given that you're encapsulating the integer implementation of the bit field, you should probably add a <code>$size</code> parameter to the constructor to allow the accessor methods to make sure the given <code>$field</code> is within bounds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T02:42:01.973",
"Id": "2617",
"Score": "0",
"body": "thanks for the ideas, I am new to all this, been stuck in the procedural ways for a few years now but i'm learning...anyways I was recommended this by another user before and I checked it out, i'm just not sure is there any real benefit of making it look or work as an array? I'm just curious if i'm missing something as you are the 2nd person to suggest this, thanks for the comments"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T06:27:11.327",
"Id": "2630",
"Score": "0",
"body": "@jasondavis - As I said in a comment to Jacob's answer, I probably wouldn't use a class here, but that's not because it's a bad idea. Rather, I would probably have whoever owns the bit field manage the values with named accessors instead of exposing the constants to the user. With your class, making it work like an array is more a neat ability of PHP. Named methods are probably better and more intuitive. You'll get autocomplete help for them unlike the array access."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T01:49:49.803",
"Id": "1512",
"ParentId": "1509",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-29T00:02:47.023",
"Id": "1509",
"Score": "4",
"Tags": [
"php",
"php5",
"bitwise"
],
"Title": "PHP Bitmask class"
} | 1509 |
<blockquote>
<p>Given an array that is first sorted non-decreasing and then rotated
right by an unspecified number of times, find the index of its minimal
element efficiently. If multiple such minimal elements exist, return
the index of any one.</p>
<p>Idea: Conceptually, divide the array into two parts: the "larger"
subpart (to the left) which consists of large numbers brought here
from the extreme right by rotation, and the "smaller" subpart which
starts with the smallest element. We can always tell in which part we
are, and move left/right accordingly.</p>
</blockquote>
<p>Notes: When the array has multiple minimal elements, the index of the leftmost one in the "right" subpart is returned.</p>
<pre><code>int getMinimIndex (const int *const a, size_t left, size_t right)
{
assert(left<= right);
// Special cases:
// 1 If left & right are same , return
if (left ==right)
return left;
// 2 For an array of size 2, return the index of minimal element
if (left == right - 1)
return a[left]<=a[right]?left:right;
// 3 If the array wasn't rotated at all,
if (a[left] < a[right])
return left;
// General case
// Go to the middle of the array
size_t mid = (left + right) >> 1;
// If we stepped into the "larger" subarray, we came too far,
// hence search the right subpart
if (a[left] <= a[mid] )
return getMinimIndex(a, mid, right);
else
// We're still in the "smaller" subarray, hence search left subpart
return getMinimIndex(a,left, mid);
}
</code></pre>
<p><strong>Unit tests:</strong></p>
<pre><code>\#define lastIndex(a) ((sizeof(a)/sizeof(a[0]))-1)
int main()
{
int a1[] = {7,8,9,10,11,3};
int a2[] = {1};
int a3[] = {2,3,1};
int a4[] = {2,1};
int a5[] = {2,2,2,2,2};
int a6[] = {6,7,7,7,8,8,6,6,6};
int a7[] = {1,2,3,4};
printf("\n%d", getMinimIndex(a1,0, lastIndex(a1))); // 5
printf("\n%d", getMinimIndex(a2,0, lastIndex(a2))); // 0
printf("\n%d", getMinimIndex(a3,0, lastIndex(a3))); // 2
printf("\n%d", getMinimIndex(a4,0, lastIndex(a4))); // 1
printf("\n%d", getMinimIndex(a5,0, lastIndex(a5))); // 3
printf("\n%d", getMinimIndex(a6,0, lastIndex(a6))); // 6
printf("\n%d", getMinimIndex(a7,0, lastIndex(a7))); // 0
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T04:22:17.397",
"Id": "2624",
"Score": "0",
"body": "I made a small error here: the return type of the getMinimIndex() should be size_t not int , and the printf formatting should change accordingly to %ud"
}
] | [
{
"body": "<p>Your algorithm works for sequences that are strictly increasing (as @Moron points out). If efficiency is a consideration, you may wish to employ iteration instead of recursion.</p>\n\n<pre><code>int getMinimIndex (const int *const a, size_t left, size_t right)\n{\n while (1)\n {\n assert(left<= right);\n\n // Special cases:\n // 1 If left & right are same , return \n if (left ==right)\n return left;\n\n // 2 For an array of size 2, return the index of minimal element\n if (left == right - 1)\n return a[left]<=a[right]?left:right;\n\n // 3 If the array wasn't rotated at all, \n if (a[left] < a[right])\n return left;\n\n\n // General case\n // Go to the middle of the array\n size_t mid = (left + right) >> 1;\n\n // If we stepped into the \"larger\" subarray, we came too far, \n // hence search the right subpart \n if (a[left] <= a[mid])\n left = mid;\n else\n // We're still in the \"smaller\" subarray, hence search left subpart\n right = mid;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T04:10:59.417",
"Id": "2622",
"Score": "0",
"body": "True, but I only meant running time complexity by \"efficiency\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T04:20:02.703",
"Id": "2623",
"Score": "0",
"body": "Well, in that case, your algorithm already runs in O(log n), which is the best you can do for searching."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T01:12:20.060",
"Id": "2739",
"Score": "1",
"body": "Actually the algorithm is unsound. See my answer for a failing test case."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T10:57:15.063",
"Id": "2747",
"Score": "0",
"body": "@Moron: Hah, serves me right for not writing enough tests. Good catch."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T03:48:26.633",
"Id": "1515",
"ParentId": "1514",
"Score": "6"
}
},
{
"body": "<pre><code>if (a[left] <= a[mid] )\n return getMinimIndex(a, mid, right);\nelse\n// We're still in the \"smaller\" subarray, hence search left subpart\n return getMinimIndex(a,left, mid);\n</code></pre>\n\n<p>In the second line it seems that it can be <code>left = mid + 1</code>. Because we already know that <code>mid</code> is part of larger subarray so we can skip it and search starting from the next item.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T09:46:18.400",
"Id": "1520",
"ParentId": "1514",
"Score": "5"
}
},
{
"body": "<p>The algorithm does not work correctly.</p>\n\n<p>It fails on the following:</p>\n\n<pre><code>int a1[] = {10,1,10,10,10,10,10};\n\nprintf(\"\\n%d\", getMinimIndex(a1,0, lastIndex(a1))); // 5\n</code></pre>\n\n<p>It prints <code>5</code> instead of <code>1</code>.</p>\n\n<p>The problem is in case the elements can repeat, you assumption that we can recurse on the left or right half is wrong.</p>\n\n<p>In fact, if elements can repeat, any algorithm will be in the worst case Omega(n), while yours is always O(logn), so it is incorrect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T06:15:21.917",
"Id": "2745",
"Score": "0",
"body": "thanks for pointing out the subtle error. But without repetitions it should still work"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-31T00:58:39.697",
"Id": "1566",
"ParentId": "1514",
"Score": "7"
}
},
{
"body": "<p>Why not just?</p>\n\n<pre><code>int minimumIndex(size_t arrayLength, const int* const array){\n int lowestIndex = 0;\n for(size_t curIndex = 0; curIndex < arrayLength; ++curIndex){\n if(array[curIndex] < array[lowestIndex]){\n lowestIndex = curIndex;\n }\n }\n return lowestIndex;\n}\n</code></pre>\n\n<ul>\n<li>Runs with O(n) complexity, and unless using really huge arrays and ancient hardware will still be fast enough.</li>\n<li>Even if the entire array is the same value, it will still <strong>only</strong> <strong>ever</strong> return the first index.</li>\n<li>It doesn't care whether the array is sorted or not.</li>\n<li>Unless provided with invalid input, it will always work correctly.</li>\n<li>Provably correct even if the numerical type in the array is changed.</li>\n<li>Uses 0 extra memory, 0 pointers.</li>\n<li>Doesn't self recurse, so it will never hit recursion depth limits.</li>\n<li>Only a <strong>single function call</strong>, since each recursive call requires a new stack frame, a jump, and a ret instruction. Plus any memory allocs/deallocs because of it being a new scope.</li>\n</ul>\n\n<p>If it's just for kicks, Feel free to disregard this answer (I recently implemented Merge Sort \"just for kicks\" so I think I understand why you wrote it)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-22T17:14:57.673",
"Id": "139376",
"ParentId": "1514",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1566",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-29T02:19:39.403",
"Id": "1514",
"Score": "11",
"Tags": [
"c",
"algorithm",
"interview-questions"
],
"Title": "Finding the minimum in a sorted, rotated array"
} | 1514 |
<p>Using the property that GCD(a, b) = GCD(b, r) where r is the remainder when you compute (a / b), you can write a recursive function as follows:</p>
<pre><code>(define (gcd a b)
; recursive
(if (= 0 b) a
(gcd b (remainder a b))))
</code></pre>
<p>I also tried to write the following as an iterative function, but it still looks very similar to the recursive solution to my eye. Is this a correct, iterative solution?</p>
<pre><code>(define (i-gcd a b)
; is this iterative?
(i-gcd-iter (remainder a b) b))
(define (i-gcd-iter acc b)
(if (= 0 b) acc
(gcd b (remainder acc b))))
</code></pre>
<p>EDIT: It appears that the first solution was actually iterative, and in fact very similar to the solution written in SICP (http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html). What would a recursive solution to this problem look like?</p>
| [] | [
{
"body": "<p>Indeed, both versions you have are iterative. I'm not actually sure that a recursive solution makes sense in this case---usually a recursive approach is for the classical pattern of holding the result of operating on the first item, then recursing into the remaining items. Calculating the GCD doesn't fit that pattern.</p>\n\n<p>One small suggestion: you can use <code>(zero? b)</code> instead of <code>(= 0 b)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:02:11.613",
"Id": "2642",
"Score": "0",
"body": "How is the first solution not recursive? It calls itself until the problem is solved, the passes the result up the call stack until the caller is reached."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:15:35.220",
"Id": "2643",
"Score": "0",
"body": "@Michael: In Scheme, tail recursion is treated as iteration (and indeed, in Scheme, that's the _only_ way to do iteration; there is no `goto` facility). Therefore, Schemers treat tail recursion (\"iteration\") as a separate concept from non-tail recursion (\"recursion\")."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:17:41.677",
"Id": "2644",
"Score": "0",
"body": "(For readers unfamiliar with Scheme: all Scheme implementations are [required to implement \"proper tail calls\"](http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%_sec_3.5), \"tail call optimisation\", or whatever you call it---again, because that's the only available method to implement iteration.)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:18:51.943",
"Id": "2645",
"Score": "0",
"body": "So that (gcd) call essentially becomes (remainder), goto (if) ?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:20:14.093",
"Id": "2646",
"Score": "0",
"body": "@Michael: Pretty much, yes."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:24:26.040",
"Id": "2647",
"Score": "0",
"body": "@Chris I've seen the optimization in other languages, but didn't realize that it was always done in Scheme."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T14:30:19.077",
"Id": "2648",
"Score": "0",
"body": "@Michael: \\*nods\\* Scheme provides other facilities for iteration (like `do`, `for-each`, etc.), but those are all macros or functions built on top of \"named `let`\", which is macro commonly used to create a recursive function that is then (in the case of `do`, `for-each`, etc.) called in tail position. :-)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T16:03:29.263",
"Id": "2653",
"Score": "0",
"body": "@Chris good summary of tail-calling, but I would disagree with your claim that iterative recursion is not \"recursion.\" A recursive procedure is one that calls itself, period. So OP's solution is both recursive and iterative. Minor point. Sorry."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T16:42:15.377",
"Id": "2654",
"Score": "0",
"body": "@John - In SICP, they contrast \"linear recursive process\" against \"iterative processes\" (In context, an \"iterative process\" is a repetition that happens in constant space, where a \"recursive process\" builds up intermediate state [link here](http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.1))."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T19:33:37.307",
"Id": "2659",
"Score": "0",
"body": "@Inaimathi - It looks like SICP is careful, though, to distinguish \"recursive processes\" from \"recursive procedures.\""
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-30T01:25:53.037",
"Id": "2664",
"Score": "0",
"body": "@John - Yup, but the word \"recursive\" shows up in both senses, so I've learned to expect this particular ambiguity. At first I assumed Chris made the distinction, but on second reading it's unclear whether he's talking about recursive processes or recursive functions; he uses the words \"solution\" and \"approach\", which could conceivably refer to either. I'm assuming he's referring to processes since the alternative wouldn't make sense. It could use clarification though."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-29T12:55:08.223",
"Id": "1522",
"ParentId": "1517",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "1522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-03-29T05:40:38.573",
"Id": "1517",
"Score": "4",
"Tags": [
"lisp",
"scheme"
],
"Title": "GCD - is this solution iterative?"
} | 1517 |